Save image in gallery in android

Question: Asks: How to pass an image URL to intent when updating compile-SDK?
When I update compile-SDK to Version 30. This message appears in Android Studio. And the app crashes. but when I downgrade it to a lower version, for example, 29, the application works very well.
I tried a lot to solve it, but unfortunately, it did not work ... can You help me.
FilterCollageActivity
    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.img_save -> {
                checkClick()
                isFromSaved = true
                try {
                    saveBitmap(screenShot)
                } catch (th: Throwable) {
                    th.printStackTrace()
                }
                val intent = Intent(this, ShowImageActivity::class.java)
                intent.putExtra("image_uri", savedImageUri!!.toString())
                startActivityForResult(intent, 2)
                finish()
            }
        }
    }

ShowImageActivity

    class ShowImageActivity : AppCompatActivity(), View.OnClickListener {

        private var image_uri: String? = null
        private var img_show: ImageView? = null
        private var saved_file: File? = null
        private var density: Float = 0.toFloat()
        internal var D_height: Int = 0
        internal var D_width: Int = 0
        private var display: DisplayMetrics? = null

        private var mLastClickTime: Long = 0
        fun checkClick() {
            if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
                return
            }
            mLastClickTime = SystemClock.elapsedRealtime()
        }

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            requestWindowFeature(Window.FEATURE_NO_TITLE)
            window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
            setContentView(R.layout.activity_show_image)

            image_uri = intent.getStringExtra("image_uri")
            saved_file = File(image_uri!!)
            img_show = findViewById<View>(R.id.img_show) as ImageView

            display = resources.displayMetrics
            density = resources.displayMetrics.density
            D_width = display!!.widthPixels
            D_height = (display!!.heightPixels.toFloat() - density * 150.0f).toInt()

            val layoutParams = RelativeLayout.LayoutParams(D_width, ViewGroup.LayoutParams.WRAP_CONTENT)
            layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE)
            img_show!!.layoutParams = layoutParams

            img_show!!.setImageURI(Uri.parse(image_uri))

    ...

        }

2022-06-13 15:47:38.495 20691-20691/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.cocnanvd.nvdframe, PID: 20691
    java.lang.NullPointerException
        at com.cocnanvd.nvdframe.FilterCollageActivity.onClick(FilterCollageActivity.kt:53)
        at android.view.View.performClick(View.java:8160)
        at android.view.View.performClickInternal(View.java:8137)
        at android.view.View.access$3700(View.java:888)
        at android.view.View$PerformClick.run(View.java:30236)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:246)
        at android.app.ActivityThread.main(ActivityThread.java:8653)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

Answer: after api level 30, maybe your saveBitmap() method not work  so  hare                             intent.putExtra("image_uri", savedImageUri!!.toString())                     you got a null pointer exception. may be other reasons as well like write permission etc . please add full FilterCollageActivity code
Answer: Here is the solution.
Step : 1
private fun checkPermissionAndProceed() {
        val permission: Collection<String> =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) arrayListOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_MEDIA_LOCATION
            ) else arrayListOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )

        Dexter.withContext(this@SolutionActivity)
            .withPermissions(permission)
            .withListener(object : MultiplePermissionsListener {
                override fun onPermissionsChecked(multiplePermissionsReport: MultiplePermissionsReport) {
                    if (multiplePermissionsReport.areAllPermissionsGranted()) {
                        addImageToGallery(
                            "IMG_" + System.currentTimeMillis() + ".JPEG",
                            bitMap!!, this@SolutionActivity
                        )
                    }

                    if (multiplePermissionsReport.isAnyPermissionPermanentlyDenied) {
                        //showSettingsDialog()
                        //Tell user why you need this permission.
                    }
                }

                override fun onPermissionRationaleShouldBeShown(
                    list: List<PermissionRequest>,
                    permissionToken: PermissionToken
                ) {
                    permissionToken.continuePermissionRequest()
                }
            }).onSameThread().check()
    }

Step : 2
private fun addImageToGallery(fileName: String, bitmap: Bitmap, ctx: Context) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {

                val fos: OutputStream
                val resolver = contentResolver
                val values = ContentValues()

                values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
                values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
                values.put(
                    MediaStore.MediaColumns.RELATIVE_PATH,
                    Environment.DIRECTORY_PICTURES + File.separator + "MyImages"
                )

                val imageUri = resolver.insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values
                )
                fos = resolver.openOutputStream(imageUri!!) as OutputStream
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                fos.close()
                Toast.makeText(ctx, getString(R.string.saved_in_gallery), Toast.LENGTH_SHORT).show()

            } else {
                val values = ContentValues()
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
                values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, fileName)
                values.put(MediaStore.Images.ImageColumns.TITLE, fileName)

                val uri: Uri? = ctx.contentResolver.insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values
                )
                uri?.let {
                    ctx.contentResolver.openOutputStream(uri)?.let { stream ->
                        val oStream = BufferedOutputStream(stream)
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, oStream)
                        oStream.close()
                        Toast.makeText(
                            ctx, getString(R.string.saved_in_gallery), Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            }
        } catch (e: Exception) {
            Toast.makeText(ctx, e.localizedMessage, Toast.LENGTH_SHORT).show()
        }
    }

Save image in gallery in android


Use epsilon delta to prove $x^2+1/x^2+2$ is continuous at $x=1$

Question:
Use $\epsilon - \delta$ definition to prove that the function $f(x) =
 \frac{(x^2+1)}{(x^2+2)}$ is continuous at $x=1$.

I think I am setting the problem up correctly and end up with
$\frac{1}{3}|x+1||x-1||$$\frac{1}{x^2+2} |$<$\epsilon$
Then I do
If $|x-1|<2, \ldots , |x+1|<4$
But I am confused as to what to do with |$\frac{1}{x^2+2} |$|
The final answer should be something along the lines of
$\delta\min\{2,\frac{3\epsilon}{4},???\}$ I think
I might be missing an essential step or have made a mistake somewhere in the beginning but I am completely lost as to how to complete this problem.
Any help would be much appreciated.
Answer: The observation that $x^{2}+2\geq 2$, so $\dfrac{1}{x^{2}+2}\leq\dfrac{1}{2}$ may help. You may choose $\delta=\min\{1,2\epsilon\}$ to get $|x+1|\leq |x-1|+2<1+2=3$, the rest should be easy.
Answer: Use the fact that
$$ \frac {1}{2+x^2}<1$$
to get
$$|f (x)-f (1)|<\frac 13 |x+1||x-1|$$
now you suppose that $|x-1|<\color {red}{1}$ since $x $ is not far from $1$.
this additional condition gives
$0 <x <2$ and $1 <x+1 <3$.
then
$$|f (x)-f (1)|<|x-1|.$$
thus you can take $$\delta=\min (\color {red}{1},\epsilon) $$
Answer: $f(x)=\dfrac{x^2+1}{x^2+2} $.
$|f(x) -f(1)| =|\dfrac{x^2+1}{x^2+2} -\dfrac{2}{3}| =$
$|\dfrac{3x^2 +3 -2x^2 -4}{3(x^2+2)}|=$
$|\dfrac{x^2-1}{3(x^2+2)}|=$
$|\dfrac{(x-1)(x+1)}{3(x^2+2)}|.$
Consider $0<x<2$, I.e. $|x-1|<1.$
Let $\epsilon >0$ be given.
Choose $\delta = \min(1,2 \epsilon)$
Then $|x-1| < \delta$ implies
$|f(x)-f(1)| =| \dfrac{(x-1)(x+1)}{3(x^2+2)}| \lt $
$|\dfrac{3\delta}{3 \times 2}| = |\dfrac{\delta}{2}| \le \epsilon.$


Doctrine 2 ResultSetMapping Many-To-Many example

Question: I'm trying to use ResultSetMappingBuilder to get data from Native query.
<code>$sql = "SELECT e.start_date FROM se_events e
            LEFT JOIN se_event_tags tg ON e.id = tg.event_id
            LEFT JOIN se_event_type t ON tg.event_type_id = t.id
            WHERE t.id = :id";
</code>
I have no idea how to build ResultSetMappingBuilder.
<code>public function createResultSetMapping() {
    $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($this->getEntityManager());
    $rsm->addRootEntityFromClassMetadata('Event', 'e');
    return $rsm;
}
</code>
Thanks for help in advance.
Answer: So I've used row SQL:
<code>$sql = "SELECT e.start_date FROM se_events e
LEFT JOIN se_event_tags tg ON e.id = tg.event_id
LEFT JOIN se_event_type t ON tg.event_type_id = t.id
WHERE t.id = $id";
$stmt = $this->getEntityManager()->getConnection()->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();
</code>


Min and Max with two constraints

Question: I'm asked to find the minimum and maximum values of $f(x, y, z) = x^2+y^2+z^2$ given the constraints $x+2y+z=3$ and $x-y=7$.
I'm pretty sure I need to set up Lagrange equations, giving:
$$2x = A+B$$
$$2y = 2A-B$$
$$2z = A$$
From here, I'm not sure where to go.
Answer: Well Lagrange multiplier will help you, but since you have 2 equations, you can easily to reduce the function to a one variable, which is easily to maximize or minimize. So from the two equations, you have:
$$x=y+7; \quad \text{and} \quad$$
$$x+2y + z = 3 \iff y+7+2y+z=3 \iff z=-4-3y$$
Now you have:
$$f(x,y,z) = x^2 + y^2 + z^2 \iff f(x)=(y+7)^2 + y^2 + (-4-3y)^2$$
$$f(x) = y^2 + 14y + 49 + y^2 + 16 + 24y + 9y^2 = 11y^2 + 38y + 65$$
Now find the derviative, set it to 0 and find the extreme point:
$$f'(x) = 22y + 38 = 0 \implies y= -\frac{19}{11}$$
Obviously this is the minimum of the function. So the minimum occurs at:
$$f\left(\frac{58}{11}, -\frac{19}{11}, -\frac{13}{11}\right)= \frac{3894}{121} = 32.(18)$$
On the other side this function doesn't have maximum. Let $y \to \infty$, from this we have: $x \to \infty$ and $z\to -\infty$, obviouslt $x^2 + y^2 + z^2 \to \infty$
Answer: Here's how to do it with Lagrange multipliers.
Put $g(x,y,z) = x + 2y + z -3 = 0$ and $h(x,y) = x - y - 7 =0$ as constraints.
Then we have 5 equations

$f_x = 2x = \lambda g_x + \mu h_x = \lambda + \mu$
$f_y = 2y = \lambda g_y + \mu h_y = 2\lambda  - \mu$
$f_z = 2z = \lambda g_z + \mu h_z = \lambda + 0 = \lambda$
$g(x,y,z) = x + 2y + z -3 = 0$
$h(x,y) = x - y - 7 =0$

Now, from (3) we have $\frac{\lambda}{2} = z$. Using our expressions for $x$ and $y$ from (1) and (2) and substituting them in in (4) and (5),
we have now

$\frac{\lambda + \mu}{2} + 2\lambda - \mu + \frac{\lambda}{2} -3 = 3\lambda - \frac{\mu}{2} -3 = 0$
$\frac{\lambda + \mu}{2} - \lambda + \frac{\mu}{2} - 7 = -\frac{\lambda}{2} + \mu -7 = 0$.

Now we have two linear equations, two unknowns. Multiply the first by two and add to the second two get

$\frac{11 \lambda}{2} -13 =0 \rightarrow \lambda = \frac{26}{11}$.

Plugging this into the first equation above, $\mu = \frac{90}{11}$.
Now from (1), (2), (3), we see that our only critical point occurs at the point where $x = \frac{58}{11}, y = \frac{-19}{11}, z= \frac{13}{11}$.
Plugging this into our equation for $f$, this comes out to $f(\frac{58}{11}, \frac{-19}{11}, \frac{13}{11}) = \frac{3894}{121} = \frac{354}{11}$.
Now, how do we know whether this is the minimum or maximum? To figure it out we just have to produce a point whose function value is less than or greater than $\frac{354}{11}$. If there's one with a higher function value, than this must be a minimum, and if there's one with a lower function value it's a maximum.
We want points satisfying (4) and (5). For ease, let $z=0$. Then we just pick the point of intersection of the lines $ y = \frac{-x}{2} + \frac{3}{2}$ and $y = x -7$. This point is $(\frac{17}{3}, \frac{-4}{3})$.
Plugging this into $f$, we see $f(\frac{17}{3}, \frac{-4}{3}, 0)= \frac{305}{9} \gt \frac{354}{11} = f(\frac{58}{11}, \frac{-19}{11}, \frac{13}{11})$. So our point must be a minimum.
Then we must have the minimum of $f$ is $f(\frac{58}{11}, \frac{-19}{11}, \frac{13}{11}) = \frac{3894}{121} = \frac{354}{11}$.
Comment: Lagrange multipliers don't guarantee it is a minimum or maximum, just that they are the only candidates.  You would need some other evidence that an extreme existed before you could conclude that this point is a minimum

Min and Max with two constraints


Why do we need MX record, can't we directly use A Record?

Question: This question might look basic, but I was wondering that let's say for email routing there's a use of MX record which points to FQDN of Mail server and that points to A record. What is reason to have MX record when eventually, we are resolving FQDN and getting A record for information, I mean why can't instead of fetching MX record of Domain, it fetches A record of the domain and sent an email.
Thanks for Help in advance :)
Answer: There's nothing stopping you from relying soley on 'A' records for email delivery.
Suppose you have example.net with no published 'MX' record, but you have an 'A' record for server.example.net.  If someones sends an email to email@example.com, as long as server1 has a configured SMTP server, and user1 exists, the email should be delivered.
MX records however, enable you to distribute load across several servers and have a fallback option.
In fact, I think the use of SMTP actually predates the use of DNS.  RFC 821 which describes SMTP, was published in 1982.  RFC 883 which describes DNS was not published until a year later, in November of 1983 and was not implemented until 1984.  Until then the standard mechanism for name resolution was HOSTS.TXT which has no facility to distinguish resource record types, and was only a table of ip address to hostname mappings, it is what we know today as /etc/hosts
for more information see https://en.wikipedia.org/wiki/MX_record
Comment: Way back then, and even into the 1990s, you did indeed address mail to users at specific machines (and occasionally not hear back because they don't log in to that machine for months at a time). The MX record and domain-addressed mail alleviated this problem, for the most part, though of course even today you can still send mail to a specific machine.
Comment: Yeah I setup a lot of email servers in the 1990's and none had an MX record. I'm sure they have an MX record now though.
Answer: The fundamental reason is that you may want to use the same domain name in different ways for different services. Ie, the domain part of an email address may also be used for something else than just incoming email.
Eg with email@example.com, you may want to have address records (A/AAAA) for example.com that are used for something else than the SMTP server. Maybe a web server, maybe something else, it doesn't really matter what exactly.
That said, if no MX is present, then the standard is to fall back to looking up address records and using those also for email delivery.
Sidenote, if this was all designed today, MX would actually be redundant as SRV was later introduced as essentially a generic form of MX that can work for any service.
With SRV you specify which service type should be mapped to which host, rather than having a dedicated record type for one particular type of service like with MX.
Additionally, http client such as web browsers would presumably also use SRV instead of just looking up address records if SRV had just been around earlier, which would actually be quite nice. But that is not what we have, and so far no change is happening in that regard.
Answer: Because that is the standard. Period. You can do whatever you want - but millions of other players have agreed on that being the standard and use that. At the end that is what it boils down to - not everything in DNS makes sense these days, but the standard has grown over time.
Also note that the MX entry has additional info that an IN A record does not have - so there is a functional difference if you have multiple email servers and want to give a priority. Multiple IN A records do not allow prioritization.
But ultimately, the "why" answer is "because that is the standard as it was decided a long time ago".


How can I add a boost to a search_api_solr query if a field has a value?

Question: I'm trying to add a boost to a search api Solr query when a field has a particular value, e.g. when its nid = 123. Looking at Solr version 8.7 docs for boosting (my solr server version), this looks pretty straightforward. I just need to add a bq parameter like:
bq=nid:123^10

When I go to my Solr server's admin UI and add a query there - first checking the edismax parser checkbox, and then adding nid:123^10 into the bq field - I see results where my node with nid is at the top of the list (as I'd expect) with all other results after it. If I remove the option, my node with nid 123 is no longer at the top (also as I'd expect).
The search_api_solr module provides a hook to alter queries, hook_search_api_solr_query_alter(), where I can add my boost. (Side note, I've used this hook in the past to boost results based on a date basically as documented in this bkosborne comment.)
My understanding is that I should be able to implement something like:
function MY_MODULE_search_api_solr_query_alter(\Solarium\Core\Query\QueryInterface $solarium_query, \Drupal\search_api\Query\QueryInterface $query) {
  $solarium_query->addParam('bq', 'nid:123^10');
}

However, this has no impact on the relevancy scores of my results (I'm printing the relevancy score in my view and my node with nid 123 has the same score whether I add this parameter or not), nor, predictably, the order of the results.
What am I missing here?
Version Information:

Drupal core: 9.1.10
Search API: 8.x-1.19
Search API Solr: 4.1.12
Solr Server: 8.7.0

p.s. my nid field key is actually its_nid in the index, but I just used nid in this question for readability.
Answer: I just needed to read more closely. All of the information is in the example code in the hook_search_api_solr_query_alter() documentation. (I think the format I was using may have been recommended for much older versions of search_api_solr, versions that are only recently no longer required on certain enterprise hosts.)
The simplest way to get this to work was to add the defType parameter to my query to tell it to use the edismax parser. This is documented in hook_search_api_solr_query_alter(). The following works:
function MY_MODULE_search_api_solr_query_alter(\Solarium\Core\Query\QueryInterface $solarium_query, \Drupal\search_api\Query\QueryInterface $query) {
  $solarium_query->addParam('bq', 'nid:123^10');
  // Avoid the conversion into a lucene parser expression, keep edismax.
  $solarium_query->addParam('defType', 'edismax');
}

However, reading the hook documentation, it shows an alternative approach that seems preferable:
function MY_MODULE_search_api_solr_query_alter(\Solarium\Core\Query\QueryInterface $solarium_query, \Drupal\search_api\Query\QueryInterface $query) {
  $boost_queries['special_node'] = [
    'query' => 'nid:123^10.0',
  ];
  $boost_queries['some_less_special_node'] = [
    'query' => 'nid:321^5.0',
  ];
  /** @var \Solarium\Component\EdisMax $edismax */
  $edismax = $solarium_query->getEDisMax();

  $edismax->addBoostQueries($boost_queries);

  // Avoid the conversion into a lucene parser expression, keep edismax.
  $solarium_query->addParam('defType', 'edismax');
}


Proving the Second Mean Value Theorem for Integrals using Abel's Lemma.

Question: This is a problem and solution from Spivak's Calculus. I'm trying to fill in the details of the final paragraph in the solution, to prove the conclusion in problem (c).
Problem:

$\rm(b)$ Suppose that $\{b_n\}$ is nonincreasing, with $b_n\geq0$ for each $n$, and that $$m\leq a_1+\cdots+a_n\leq M$$ for all $n$. Prove Abel's Lemma: $$b_1m\leq a_1b_1+\cdots+a_nb_n\leq b_1M.$$ (And, moreover, $$b_km\leq a_kb_k+\cdots+a_nb_n\leq b_kM,$$ a formula which only looks more general, but really isn't.)
  $\rm(c)$ Let $f$ be integrable on $[a,b]$ and let $\phi$  be nonincreasing on $[a,b]$ with $\phi(b)=0$. Let $P=\{t_0,\ldots,t_n\}$ be a partition of $[a,b]$. Show that the sum $$\sum_{i=1}^n f(t_{i-1})\phi(t_{i-1})(t_i-t_{i-1})$$ lies between the smallest and the largest of the sums $$\phi(a)\sum_{i=1}^k f(t_{i-1})(t_i-t_{i-1}).$$ Conclude that $$\int_a^b f(x)\phi(x)\,dx$$ lies between the minimum and the maximum of $$\phi(a)\int_a ^xf(t)\,dt,$$ and that it therefore equals $\phi(a)\displaystyle\int_a^\xi f(t)\,dt$ for some $\xi$ in $[a,b]$.

Solution:

$(\rm c)$ If we set $$a_i=f(x_i)(t_i-t_{i-1})$$ and let $$\begin{align}m&=\text{smallest of the }\sum_{i=1}^k f(x_i)(t_i-t_{i-1})\\M&=\text{largest of the }\sum_{i=1}^k f(x_i)(t_i-t_{i-1})\end{align}$$ then $m\leq a_1+\cdots+a_k\leq M$ for all $k$. Letting $b_k=\phi(x_k)$ in part $\rm(b)$, we find that $$\sum_{i=1} ^n f(x_i)\phi(x_i)(t_i-t_{i-1})$$ lies between the smallest and the largest of the sums $$\phi(x_1)\sum_{i=1}^k f(x_i)(t_i-t_{i-1}).$$ $\,\,\,$ Since we can approximate $\int_a^b f(x_i)\phi(x)\,dx$ by sums $\sum\limits_{i=1}^n f(x_i)\phi(x_i)(t_i-t_{i-1}),$ and $\int_a^x f(t)\,dt$ by sums like $\sum\limits_{i=1}^k f(x_i)(t_i-t_{i-1})$, the final result should follow from the above. However, some care is required for the argument: $\,\,\,$ Given $\varepsilon>0$ we can choose $\delta>0$ so that whenever all $t_i-t_{i-1}<\delta$ we have $$\tag{1}\left|\int_a^b f(x)\,dx-\sum_{i=1}^n f(t_{i-1})(t_i-t_{i-1})\right|<\varepsilon$$ We claim that for any $\varepsilon'>\epsilon$ it also follow that for each $k$ $$\left|\int_a^{t_k}f(x)\,dx-\sum_{i=1}^k f(t_{i-1})(t_i-t_{i-1})\right|<\varepsilon'.$$ The idea is that if we had $$\tag{2}\left|\int_a^{t_k}f(x)\,dx-\sum_{i=1}^k f(t_{i-1})(t_i-t_{i-1})\right|\geq\varepsilon',$$ then by choosing some $p>n$ and new $t_{k+1}<t_{k+2}<\cdots<t_p=b$ we could make the sums on $[t_k,b]$ so close to $\int_{t_k}^b f(x)\, dx$ that inequality $(2)$ would contradict $(1)$. More precisely, choose $t_{k+1},\ldots, t_p$, still with $t_i-t_{i-1}<\delta$, so that $$\tag{3}\left|\int_{t_k}^bf(x)\,dx-\sum_{i=k+1}^p f(t_{i-1})(t_i-t_{i-1})\right|<\varepsilon'-\varepsilon>0.$$

My work:
Let $F(x)=\int_a^x f(t)dt$ on $[a,b]$, then since $F$ is continuous on $[a,b]$, it attains its minimum and maximum on some $t_k$ and $t_l$.
Now given any $\epsilon \gt 0$, there is some $\delta \gt 0$ such that for any partition with mesh less than $\delta$, we have
$|\int_a^b f(x)dx-\sum_{i=1}^n f(t_{i-1})(t_i-t_{i-1})|\lt \epsilon.$
Then by the claim after (1) in the solution, we have
$|\int_a^{t_k} f(x)dx- \sum_{i=1}^k f(t_{i-1})(t_i-t_{i-1})|\le \epsilon.$ for any $k\in \{1,\cdots, n\}$.
Hence for a given partition with mesh less than $\delta$ having the specified $t_k$ and $t_l$ as endpoints, we get
$|\phi(a)\int_a^{t_k} f(x)dx- \phi(a)\sum_{i=1}^k f(t_{i-1})(t_i-t_{i-1})|\le \phi(a)\epsilon.$
and
$|\phi(a)\int_a^{t_l} f(x)dx- \phi(a)\sum_{i=1}^l f(t_{i-1})(t_i-t_{i-1})|\le \phi(a)\epsilon.$
Clearly, $\phi(a)\int_a^{t_k} f(x)dx$ and $\phi(a)\int_a^{t_l} f(x)dx$ are the minimum and maximum of $\phi(a)\int_a^x f(t)dt$ for $x\in [a,b]$.
Now this is where my solution has hit a problem. Assume that the smallest and largest of the sums $\phi(a)\sum_{i=1}^k f(t_{i-1})(t_i-t_{i-1})$ for $k \in \{1, \dots, n\}$, are $\phi(a)\sum_{i=1}^k f(t_{i-1})(t_i-t_{i-1})$, and $\phi(a)\sum_{i=1}^l f(t_{i-1})(t_i-t_{i-1})$, respectively.
Then we have, combining the inequalities (1) and (2) in the solution and the first thing proven in problem (c),
$\phi(a)\int_a^{t_k} f(x)dx-(\phi(a)+1)\epsilon \le \phi(a)\sum_{i=1}^k f(t_{i-1})(t_i-t_{i-1})-\epsilon \le \sum_{i=1}^n f(t_{i-1})\phi(t_{i-1})(t_i-t_{i-1})-\epsilon \lt \int_a^b f(x)\phi(x)dx \lt \sum_{i=1}^n f(t_{i-1})\phi(t_{i-1})(t_i-t_{i-1})+\epsilon \le \phi(a)\sum_{i=1}^l f(t_{i-1})(t_i-t_{i-1})+\epsilon \le \phi(a)\int_a^{t_l} f(x)dx+(\phi(a)+1)\epsilon.$
Since $\epsilon$ is arbitrary, we get
$\phi(a) \int_a^{t_k} f(x)dx \le \int_a^b f(x)\phi(x)dx \le \phi(a) \int_a^{t_l} f(x)dx$, which is the desired conclusion.
However, this answer depends on the "assumption" I made in the bold sentence above. I've tried to prove this part, but have been unsuccessful. I think I followed the intentions of the written sketch in the last paragraph of the solution, but I can't get this part straight by any means. I would immensely appreciate it if anyone could show me how to solve this part, thanks for reading this long writing.
Answer: Your assumption is not valid.  The smallest and largest sums do not necessarily coincide with the smallest and largest values of $F(x)$, but you can salvage your proof.
Denote as follows
$$S(P) = \sum_{i=1}^n f(t_{i-1})\phi(t_{i-1})(t_i - t_{i-1}), \\ S(P_j) = \sum_{i=1}^j f(t_{i-1})(t_i - t_{i-1}). $$
We have that
$$m \phi(a) \leqslant S(P) \leqslant M \phi(a),$$
where for $1 \leqslant j \leqslant n$
$$m \leqslant S(P_j) \leqslant M.$$
For any $\epsilon >0$ if the mesh of the partition is sufficiently small, then we have both
$$S(P)-\epsilon < \int_a^b f(t) \phi(t) \, dt  < S(P) + \epsilon ,$$
and for $1 \leqslant j \leqslant n$
$$\int_a^{x_j} f(t) \, dt -\epsilon < S(P_j) < \int_a^{x_j} f(t) \, dt  + \epsilon .$$
Using the first inequality it follows that
$$m\phi(a) - \epsilon < \int_a^b f(t)\phi(t) \, dt  < M\phi(a) + \epsilon.$$
The second inequality implies
$$\inf_{x \in [a,b]}\int_a^{x} f(t) \, dt - \epsilon < m \leqslant M <  \sup_{x \in [a,b]}\int_a^{x} f(t) \, dt + \epsilon.$$
Combining we find that for any $\epsilon > 0$ we have
$$\phi(a)\inf_{x \in [a,b]}\int_a^{x} f(t) \, dt - \epsilon(1 + \phi(a)) \leqslant \int_a^b f(t)\phi(t) \, dt  \leqslant  \phi(a)\sup_{x \in [a,b]}\int_a^{x} f(t) \, dt + \epsilon(1 + \phi(a)),$$
and the conclusion follows since $\epsilon$ can be made arbitrarily small.
Comment: If $\int_a^{x_j} f(t) \, dt -\epsilon < S(P_j)$ and $m = \min_{1 \leqslant j \leqslant n} S(P_j)$, then $\inf_{x} \int_a^{x} f(t) \, dt -\epsilon < m.$
Comment: I think I almost got it from your answer but just a few questions. First, shouldn't $S(P_j)$ be $\sum_{i=1}^j f(t_{i-1})(t_i-t_{i-1})$? I don't see how the second inequality makes sense if $\phi(t_{i-1})$ is includes in $S(P_j)$. Second, I'm guessing that the inequality involving $S(P_j)$ and $\int_a^{x_j}f$ follows from the claim proven in the solution? And in that case shouldn't it be $\le$ instead of the strict inequality? Finally, how does the second inequality imply the infimum of $\int_a^x f -\epsilon \le m$ and the right side as well?
Comment: @takecare:  On your first comment - sorry, that is a typo on my part.  Will correct.
Comment: Regarding the second question on the inequality involving $S(P_j)$ and the integral -- choosing a sufficiently fine partition we can ensure that a finite number of Riemann sums are all within $\epsilon$ of the respective integrals.


Validation constraints on form fields ignored

Question: Trying to figure out custom validation with constraints, but no luck yet. Right now, my form posts content and gives no errors when form is filled out incorrectly.
(Please avoid suggesting validation modules -- I know those exist.)
Maybe somebody knows what I'm missing? Or maybe it's done different when I'm doing specific fields? Or maybe this isn't how to do it on a back-end content submission form?  Here's what I have so far:
I built a module called "custom_validation." It contains custom_validation.module:
  <?php

/**
 * @file
 */

/**
 * Implements hook_entity_type_alter().
 */
function custom_validation_entity_type_alter(array &$entity_types) {

  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */

  $entity = $entity_types['node'];
  $entity->addConstraint('BlogpostError');
}

Then, in subfolder src/Plugin/Validation/Constraint, I've got two files.
BlogpostErrorConstraint.php contains:

namespace Drupal\custom_validation\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Prevent article creation if errors.
 *
 * @Constraint(
 *   id = "BlogpostError",
 *   label = @Translation("Added blog post category instead of story author in author field", context = "Validation"),
 *   type = "string"
 * )
 */
class BlogpostErrorConstraint extends Constraint {

  /**
   * {@inheritdoc}
   */

    public $notByline = '%value is a blog post type. Please add a byline';

    public $noImageSource = 'need image source';

}

BlogpostErrorConstraintValidator.php contains:

namespace Drupal\custom_validation\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the BlogpostError constraint.
 */
class BlogpostErrorConstraintValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {

    if (!isset($items)) {
      return;
    }

    // limit this to 'blog entries' content type
    if ($items->bundle() == 'blog_entry') {

      // now loop through each field...
      foreach ($items as $delta => $item) {
        // an array of phrases we don't want in the field
        $bad_bylines = [];
        array_push($bad_bylines,"Value one","value two","abc123");

        // adding validation...
        //byline field
        if (in_array($item['field_byline'], $bad_bylines)) {
           // not sure of syntax here
           $this->context->addViolation($constraint->notByline, ['%value' => $item->value]);
        }

        //main image source field...
        if ($item['field_main_image_source'] == '') {
           $this->context->addViolation($constraint->noImageSource, ['%value' => $item->value]);
        }
      }

    }

  }

}

Comment: Is that a typo, or does your file's name start with a lowercase 'b'? Talking about blogpostErrorConstraint.php
Comment: just a typo. the file is BlogpostErrorConstraint.php - I just corrected it
Comment: All right. Is the code you have in the validate() function complete or is there more to it?
Comment: Yes, that's complete. It's just a starting point as I try and figure out how it works.
Comment: Well, that won't really work that well and it's not even a problem of implementing the Validation API. The code has several problems and needs to be revised, e.g. `$items` comes out of nowhere, `if ($field['field_main_image_source'] = '')` performs an assignment and not a comparison, and so on. Try to revise and update your question once the code is in order and it does come down to the Validation API. So far as I have tried your code locally, it does hook into the Validation API properly.
Comment: I think you should add the validation to fields not content entity as per this guide https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-custom-validation-constraint Also your second if statement contains single equal sign
Comment: Actually, that is the guide I referenced. I've made a couple edits above, but still trying to learn and figure out what I've done wrong. I'll edit again once / if I figure out more
Comment: Making some progress. At this point, I think I need to figure out how to get the field label out of each $item, so I can start validating, right?
Comment: There is a lot of code here. First step I would advise is to step through it with xdebug to determine where its failing, and potentially, why.
Comment: Aside from debugging it, are you using the right hook? The referenced guide uses `hook_entity_bundle_field_info_alter`, not `hook_entity_type_alter`. Also the id and the class name of the constraint differ, which may also be a potential issue.
Comment: @Kevin The current code seems to work, using the `hook_entity_type_alter` (thought the same); I tested it locally and XDebug brings me inside the `BlogpostErrorConstraintValidator ::validate()` function when saving a node form.
Comment: new day, starting to look at this again. Without xdebug, I can see that I need to change up the "$field[]" bit. I'm trying to figure out how to get the field name out of $item that gets looped. For now, I'll stay with hook_entity_type_alter, as @StefanosPetrakis says it seems to be working.
Comment: on a side note I don't think xdebug is feasible to install on the environment I'm using. Security permissions issue. Maybe Devel covers my needs? I have that.
Comment: Yeah.. I may have to tackle another project. This one's over my head and experience level. I got as far as the above modified code giving me an invalid argument exception. "Unable to get a value with a non-numeric delta in a list. (line 98 of ... ItemList.php) Bummer.
Answer: Turns out I was trying too hard. Typical beginner mistake. :)  I threw out the code above, and started from scratch. I replaced everything with the code examples in this tutorial: https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-custom-validation-constraint
Within the validator, I replaced if (!is_int($item->value)) with  if ($item->value == "Value one" || "value two"), to get what I needed to validate on. Then I modified the variable names, field names and error messages to suit my needs. It only handles one field, but gets me closer to what I need.
Comment: But `$item->value = "Value one"` is still an assignment... you'd want `if ($item->value == "Value one" || $item->value == "value two")` to do a comparison.
Comment: ok... just tested with that correction, and it's working. I modified the text above to reflect the correction.
Comment: For the `if` statement `$item->value == "Value one" || "value two"` is equivalent to `TRUE`.
Comment: Correct. I want it to be true if it's value one or value two. If it's not, then false. There's probably a better way of doing this. In the code I first posted, I was trying to see if the field value was in an array of unwanted values, else true. The above is working for me as the same thing, without an array to check, and I didn't want to 'rock the boat' for the moment.
Comment: Isn't that just saying "OR [anything]"? It's true so long as its not literally `FALSE`. If you are looking for value and type, use `===` instead of `==`.
Comment: ah dang.. I see what you're saying now. It also thinks it's an error when the field contains a name not 'value one' or 'value two' ... Damn. Just when I thought I had this. It's doing it, regardless of == or ===
Comment: Ok.. yeah. I'm back to square one. The above solution is no good and I'm not understanding something fundamentally about how to do this, even though it seems like exactly what I need. I can't even use an array, it completely ignores that.
Comment: What the heck!??? I can't even get this to work with something as simple as "if (strpos($item->value, 'Value one') !== false) {" . Please somebody just tell me what the heck I'm missing so I can get past this thing and learn from it?
Comment: This is why you need a debugger... so you can step through line by line and inspect scope.
Comment: bummer.. I'm using Acquia Dev Destop - on a mac. Acquia's instructions for adding xdebug are for windows only. I tried anyway, and it didn't seem to work. UPDATE: and, they only have xdebug for PHP 5. not included for 7


Solmization with syllables - du da di

Question: First of all, I am an absolute noob regarding music, so please bear with me.
I am trying to understand an exercise (from my son's school lesson, where teacher seems to be reluctant to explain this in detail ...) about solmization with syllables "du da di". I am giving the solution to the exercise question as an image here:
The question reads in english like:
Write down the corresponding solmization syllables below the notes.
The question is provided just with the notes, but without the syllables, of course.
I do not understand the rules for when to put what syllable below the notes.
I already did some gooling and searching in here, but could not find a hint about this. Regarding solmization I only find explanation about "do re mi fa so", so it seems to me this "du da di" syllable are some custom stuff.
So my questions are:
What kind of rule is behind this solmization? When do I put which syllable in? Is there any general convention about what syllables will be used (du da di) or is this just a convention that each teacher can agree with their students?
Comment: Kodaly and later, Gordon, came up with rhythmic names for various rhythms (!). It seems very complex and really not that enlightening. Personally, I find it fairly pointless.
Comment: Interesting, I didn't know this was done in German-speaking countries. Is this common over there?
Answer: The names of the notes depend not on their length, but on their position in the measure. The six eighth notes per measure are named:
du  da  di  du  da  di
♪   ♪   ♪   ♪   ♪   ♪

No matter how long a note is, it gets the name of the position where it starts; e.g. a note which starts on the third eighth note would be a "di":
du  da  di  du  da  di
        ♩
        di

So the example in the question would become:
du  da  di  du  da  di    du  da  di  du  da  di    du  da  di  du  da  di
♪   ♪   ♪   ♪   ♪   ♪     ♩       ♪   ♩        ♪     ♪   ♩       ♩       ♪
du  da  di  du  da  di    du      di  du      di    du  da      du      di

I guess it's an exercise in keeping track of where you are in the rhythm, though it would probably be clearer if you sang "o-one three fou-our six" instead of "duuu di duuu di".
Comment: Counting numbers has worked for me for 60 yrs...
Comment: @Tim The problem in German is of course that "eins", "zwei" and "drei" all have the same vowel. If a whole class is singing "doo dah dee" you can easily hear (and see) when someone makes a mistake.
Comment: More the position in the beat rather than which beat in the measure,  I think.
Comment: I'm guessing it's only a problem counting in German. French, Spanish, English and most other languages don't have numbers that sound similar.
Comment: FWIW  in the USandA  a common method is "One-eee-and-aa; Two-eee-and-aa" for 16th-notes;  "One-and-aa,..." for triplets,  "One-and" for duplets.
Answer: Maybe this helps you to understand it more clearly:
Comment: Thanks, this was very helpful. Since only one answer can be marked as solution, I gave it to Uncle Bobs answer, but surely upvoted yours.

Solmization with syllables - du da di


Solving $z^2-2iz+1=0$ in complex numbers

Question:
Solve: $z^2-2iz+1=0$

I did:
$$(z-i)^2-(i)^2+1=0$$
$$(z-i)^2+2=0$$
$$((z-i)-\sqrt{2})((z-i)+\sqrt{2})$$
but that's wrong. Why?
Answer: If by rt(2) you mean the squareroot of $2$, so $\sqrt{2}$, the problem is that you have to "put the $2$ on the other side" so you nee to take root of $-2$.
Or, recall $X^2 - a^2 = (X-a)(X+a)$ and so $X^2 + a^2 = (X-ia)(X+ia)$.
Comment: oh ok thanks so much


How to improve the clarity of hierarchical taxonomy terms in edit forms?

Question: I have a hierarchical taxonomy vocab. When I go to -say- a node edit form that uses this, with checkboxes, the hierarchy is represented simply by prepending a - for every level of depth. This really does not represent the hierarchy very well - it's hard to see, and ideally it would be semantic (nested list), or at least add a class on the container elements like taxonomy-level-N.
Is there a module for this? Or some other hack?
Comment: Is your answer specific to checkboxes?  Or do you just want any answer that will work with multiple selection?
Comment: Good point. I guess the `SELECT` elements are visually a little clearer (because there's nothing to the left of the hyphen identifying a child). My particular use-case is checkboxes (multiple selections), so an answer for that would be great.
Comment: Sorry, not sure about checkboxes, I've provided a possible solution but that's all I can do.
Answer: One way you could approach this is to use select boxes with an 'add more items' button.
I use Simple Hierarchical Select for single value selections in a taxonomy with levels, but there's no reason you can't use it for multiple selections.
If that module doesn't make an 'add more items' button pop up then put the field in a Field Collection, yes even by itself.  I know for a fact that you can have multiples of those.


Which offences result in indirect free kicks?

Question: If a player commits a direct free kick offence in their own penalty area, this results in a penalty kick instead of a direct free kick. However, if the offence is an indirect free kick offence, it remains as an indirect free kick as shown here.
What offences result in an indirect free kick?
Comment: You should consider changing the accepted answer to Mormegil instead, since Orangecrush answer in not complete by a long way.
Answer: The penalty kick is a kind of penalty used if and only if a team commits an offense warranting a direct free kick inside its own penalty area, in which case, a penalty kick is used instead of the direct free kick. As this does not apply to indirect free kicks, nothing is special there.
The only special case here is that there are specific offenses warranting an indirect free kick which apply only inside your own penalty area; those are specific for the goalkeeper. (Not that those offenses would be handled specially inside the penalty area, just that they cannot occur anywhere else by definition/plain logic.)
Therefore, an indirect free kick inside the penalty area is awarded to the attacking team if either

the goalkeeper of the defending team commits any of the following four offenses:

controls the ball with his hands for more than six seconds before releasing it from his possession
touches the ball again with his hands after he has released it from his possession and before it has touched another player
touches the ball with his hands after it has been deliberately kicked to him by a team-mate
touches the ball with his hands after he has received it directly from a throw-in taken by a team-mate

or if any player of the defending team

plays in a dangerous manner
impedes the progress of an opponent
prevents the goalkeeper from releasing the ball from his hands (which is obviously impossible inside your own penalty area)
commits any other offence, not previously mentioned in Law 12, for which play is stopped to caution or send off a player

I believe indirect free kicks for the "generic" offenses are quite rare in penalty area; the offense would usually be either ignored completely, or a "similar" offense warranting a direct free kick and therefore a penalty kick would be ruled instead, etc. However, these do happen. A quick example video found with Google: during the 36th minute of Real Madrid CF vs Sevilla on April 29, 2012, Fazio played with a high foot on Ronaldo inside the penalty area, and an indirect free kick against Sevilla for playing in a dangerous manner was awarded. See this YouTube video: Free kick inside the penalty box ? Real Madrid v Sevilla 29. (Please disregard the confused/mistaken title and some comments).
And note that there is one specialty regarding the procedure for an indirect free kick awarded to the attacking team: If the indirect free kick was awarded inside the goal area, the kick must be taken on the goal area line parallel to the goal line at the point nearest to where the infringement occurred.
Comment: Oh, yeah, definitely. While quite rare, this is definitely not unheard of. A quick example found using Google: https://www.youtube.com/watch?v=9gnOfzQE8nY – note the confused&mistaken title and some comments. This was an indirect free kick (direct free kick is obviously impossible inside penalty area) awarded for playing in a dangerous manner (playing with a foot very high and near the attacker's head but _not_ hitting him, which would be a penalty kick).
Comment: Has there been any instance of a team being awarded an indirect free kick inside the penalty box ? (other than the goalie reasons, I mean)
Comment: Player of Defending team  impedes the progress of an opponent?
Isn't that a penalty.
Comment: @Yaitzme: No. _Holding_, _tripping_, _striking_, … etc., which is "careless, reckless, or using excessive force" are offences warranting a direct free kick (or penalty kick if inside penalty area). _Impeding the progress of an opponent_ "means moving into the path of the
opponent to obstruct, block, slow down or force a change of direction by an opponent when the ball is not within playing distance of either player". And this warrants just an indirect free kick.
Comment: This should be marked as the correct answer as it explains the concept - although you've still missed a lot of examples of offences. I don't believe listing them is helpful as there are so many.
Comment: @studro: Thanks, but I am not sure what you mean by missing examples. Specific _instances_, obviously. Specific "types" (e.g. "what counts as 'playing in a dangerous manner'"), sure. But the list of offences is exhaustive, directly from the Laws of the Game.
Comment: @Mormegil You've only covered Law 12. There are a few other examples of reasons to award an indirect free kick in Laws 3, 4, 13, 14, 15, 16 and 17 as well.
Comment: Right; you basically refer to expanding on the last point, even though I could imagine even different (hypothetical and quite funny) situations. :-) But I think I won't complicate the answer any more. Thanks for the suggestions.
Comment: @Mormegil - I gave up on replying at the time, but that's not entirely correct - they aren't expansions on the last point, as the last point only refers to offences for which play is stopped to issue a caution or send-off. They are things like touching a free-kick twice, throwing objects onto/off the field, re-entering without permission etc. These situations are not common, but are for from hypothetical or funny. As there has been a big rewrite of the Laws, I decided to put together a complete list. See [my answer](http://sports.stackexchange.com/a/14783/35260) for details.
Comment: @Mormegil - as it turns out, it didn't end up complicating the answer all that much.
Answer: Inside the penalty box, an indirect free kick, instead of a penalty, will be awarded

if the goalkeeper controls the ball with his hands for more than six seconds.
if the goalkeeper touches the ball with his hands after he has released it from his possession and before it has touched another player.
if the goalkeeper handles a back pass.
if the goalkeeper handles the ball directly from a throw-in taken by a team-mate
plays in a dangerous manner.

Sources: This and this. More details about the procedure, positions and rules about indirect free kicks can be read here.
Comment: You neglected to include all of the relevant information:

An indirect free kick is also awarded to the opposing team if, in the opinion of the referee, a player:
* plays in a dangerous manner
* impedes the progress of an opponent
* prevents the goalkeeper from releasing the ball from his hands
* commits any other offence, not previously mentioned in Law 12, for which play is stopped to caution or send off a player
Comment: your missing all the offenses that can be committed by other players (everyone except the goalie).
Comment: You've missed so many offences that result in an indirect free kick. Perhaps it would be better to explain the concept (ie. only direct free kick offences become penalty kicks when the offence occurs inside the penalty area of the team who committed the offence).
Comment: I've had another go at answering this, in light of recent changes. See [my answer](http://sports.stackexchange.com/a/14783/3526) for more information.
Comment: I agree with Ticky, this only answers a fraction of what offences result in an indirect free kick. As so it should not have been accepted as the correct answer. Instead Mormegil answer should have been marked as the correct answer.
Answer: Indirect free kicks in the box were quite common at all levels of the game until about 20 years ago. It is nearly always for "obstruction". The problem has been that players now deliberately obstruct, which can be seen as "reckless or excessively forceful", hence a direct free kick/penalty.
Referees tend to see all obstructions now as deliberate, leading to far more penalties (or calls for penalties from attackers deliberately barging into defenders to try to "win" a penalty) being given.
With more games televised there are more controversies about the awarding of pens, especially in "homer" situations.
Unfortunately unless players begin to behave better (and stop cheating,) the obstruction rule will continue to lead to direct free kicks only.
Comment: This is because there is no offence called "obstruction" any more. It's "impeding the progress of an opponent" if there is no contact in what used to be called obstruction, resulting in an indirect free kick. If there is contact, it's now sanctioned as "holding" or "charging", which results in a direct free kick or penalty kick.
Comment: As studro says, the "rule of thumb" in the direct versus indirect free kick issue, is the presence of actual physical contact. That is not just applicable for the "obstruction" situations, but for pretty much all offenses. When there's an offense including physical contact, the correct decision is almost always a direct free kick (or a penalty, when inside the box). When there's a wrongdoing without contact, it's usually ruled an indirect free kick. There are of course a couple of exceptions, but it's a good rule of thumb for those who are not completely sure about the distinction.
Answer: It may be easier to list only the offences that result in a penalty kick being awarded (ie. direct free kick offences), as there are a lot less of them. The vast majority of possible infringements result in an indirect free kick, in spite of direct free kick offences being far more common.
A number of the other answers have focused only on Law 12 offences, however, there are many others that result in an indirect free kick. This answer will endeavour to list them all in light of recent changes to the Laws. Pertinent changes have been emphasised.
An indirect free kick is awarded to the opposing team if:

a player, temporarily off the field of play (ie. for treatment, correcting equipment) re-enters the field of play without permission. The indirect free kick is taken from the location of the ball when play was stopped (Laws 3.8 and 4.5). If the player committed any other Law 12 offence (ie. a foul or misconduct), play is restarted with the appropriate restart for that offence.
a player commits an offside offence by interfering with play, interfering with an opponent or gaining an advantage from being in that position (Law 11.2). The indirect free kick is taken from the location at which the player interfered or gained an advantage (up until recently it was taken from where they were located when the ball was last touched by a team-mate) (Law 11.4).
a player plays in a dangerous manner. The indirect free kick is taken from where the player played in a dangerous manner (Law 12.2).
a player impedes the progress of an opponent without making contact. The indirect free kick is taken from where the opponent was impeded (Law 12.2).
a player prevents the goalkeeper from releasing the ball from his hands or kicks or attempts to kick the ball when the goalkeeper is in the process of releasing it. The indirect free kick is taken from where the attempted release occurred (Law 12.2).
a player commits misconduct (ie. a cautionable or sending-off offence) without the restart being listed elsewhere in the Laws. The indirect free kick is taken from where the player committed the misconduct (Law 12.2).
a goalkeeper controls the ball with the hands for more than six seconds without releasing the ball. The indirect free kick is taken from where the goalkeeper was handling the ball when the six seconds expired (Law 12.2).
a goalkeeper touches the ball with the hands after releasing it and before it has touched another player, after it has been deliberately kicked to the goalkeeper by a team-mate, or after receiving it directly from a throw-in taken by a team-mate. The indirect free kick is taken from where the goalkeeper handles the ball (Law 12.2).
a player standing inside the field of play throws an object at any person outside the field of play, or a substitute or substituted player throws an object at an opponent standing inside the field of play (Law 12.4). The indirect free kick is taken from where the ball was located when play was stopped (Law 3.5).
a player touches the ball a second time once it is in play, before it touches another player, after taking a free kick, penalty kick, throw-in, goal kick or corner kick. The indirect free kick is taken from where the ball was touched for the second time (Laws 13.3, 14.2, 15.2, 16.2 and 17.2). (If the second touch was a deliberate handling by a player other than the goalkeeper within their own penalty area, the deliberate handling offence takes precedence and the restart is a direct free kick or penalty kick accordingly.)
after the referee has signalled for a penalty kick to be taken, but before it is taken, a player taking a penalty kick or a team-mate of the player taking a penalty kick commits any infringement listed in the Laws and the subsequent kick does not enter the goal. The indirect free kick is taken from where the infringement occurred (Law 14.2). (If both teams infringe the Laws between the signal and kick, the penalty kick is retaken instead).
after the referee has signalled for a penalty kick to be taken, the penalty kick is kicked backwards by the kicker, the kicker feints once their run-up is completed, or a team-mate of the designated kicker takes the kick instead (up until recently, if the ball entered the goal, the penalty kick was taken again). The indirect free kick is taken from the penalty mark (ie. where offence occurred) (Law 14.2).
a player unfairly distract or impedes an opponent taking a throw-in, or stands closer than 2m to an opponent taking a throw-in and the throw-in ends up being taken correctly. The indirect free kick is taken from where the player committing the offence was located (Law 15.2).

If the location of the indirect free kick ends up being in the goal area, to be taken by:

the attacking team, it is instead taken from the nearest point on the goal area line that runs parallel to the goal line.
the defending team, it is taken from any point within the goal area.

(Law 13.2)


Modify article body for one particular article to add data

Question: How do I modify an article's body field before the end user sees it for one particular article?
Background: Currently the content editors are updating this data manually twice per week. We want to automatically update it every 8 hours with a cron job instead. We will get data from an external source, it comes to us in JSON format. We process the data into a render array.
When I'm ready to see some output on the page, how do I put it there?
Comment: I don't get it. You mean like with `MYMODULE_preproccess_field__body(&$variables)`?
Comment: It really depends on what you want to achieve. Sure you could build a custom field formatter to fetch data from an external API field by field and node by node and render that according your needs. But what about caching then? Maybe have a look at [`hook_cron`](https://api.drupal.org/api/drupal/core%21core.api.php/function/hook_cron/8.2.x) and [Batch operations](https://api.drupal.org/api/drupal/core%21includes%21form.inc/group/batch/8.2.x). With that you can build something to fetch your data and then update nodes accordingly. Node cache will automatically get rebuild on node updates.
Comment: I ended up taking a different approach. I modified the node and saved it (this will eventually happen on cron).
Comment: Though if I follow your thoughts a little bit further, you may actually be looking for some API approach to really update existing data, instead of just overriding/preprocessing the existing data, no?
Comment: Oh. Ha! Yep. That's probably just what I was looking for. Thanks! I'm still new to Drupal. Would a custom field formatter be better?
Comment: Consider answering your own question providing the snippet that you used in the end. Maybe it helps future readers.
Answer: I ended up modifying the node when cron runs.
<code>define("JMT_CLASSES_CLASSES_ED_NODE_ID", 574);
// 60 * 60 * 8 - measured in seconds.
define("JMT_CLASSES_EIGHT_HOURS", 28800);

/**
 * Implements hook_cron().
 */
function jmt_classes_cron() {
  // Check current config for time, if greater than 8hrs check for updates.
  $timeOfLastUpdate = \Drupal::configFactory()
    ->get('jmt_classes.settings')
    ->get('last_run');
  $currentTime = \Drupal::time()
    ->getCurrentTime();
  $intervalSinceLastUpdate = $currentTime - $timeOfLastUpdate;

  if ($intervalSinceLastUpdate >= JMT_CLASSES_EIGHT_HOURS || $timeOfLastUpdate == NULL) {
    // Check for updates.
    $raw = jmt_classes_get_classes('https://example.com/Client.WebApi/api/Route?url=query/get?url=jmt');
    if ($raw) {
      $newBodyValueHtml = jmt_classes_render_html($raw);
      $classesEdNode = Node::load(JMT_CLASSES_CLASSES_ED_NODE_ID);
      jmt_classes_update_class_node($classesEdNode, $newBodyValueHtml);

      \Drupal::configFactory()->getEditable('jmt_classes.settings')
        ->set('last_run', $currentTime)
        ->save();
    }
  }
}

/**
 * Update node with new html for the body field and log that it was updated.
 *
 * @param string $node
 *   The node (output page) that should be updated with new data.
 * @param string $newBodyValueHtml
 *   The HTML to set the body to.
 */
function jmt_classes_update_class_node($node, $newBodyValueHtml) {
  $node->body->value = $newBodyValueHtml;
  $node->save();
  \Drupal::logger('jmt_classes')->notice("Successfully updated body field of articles/upcoming-education-classes-field-days");
}

/**
 * Get raw json output for JMT classes. Log error or success.
 *
 * @param string $uri
 *   JMT api uri: should be something like:
 *   'https://example.com/Client.WebApi/api/Route?url=query/get?url=jmt'.
 *
 * @return string
 *   Raw json data or empty if nothing returned from request.
 *
 * @throws \GuzzleHttp\Exception\GuzzleException
 */
function jmt_classes_get_classes($uri) {

  try {
    $response = \Drupal::httpClient()->request('GET', $uri, ['timeout' => 120]);
  }
  catch (Exception $e) {
    \Drupal::logger('jmt_classes')->error("Attempted to get data
from $uri but failed. $php_errormsg");
    return '';
  }

  $data = (string) $response->getBody();
  $data_array = json_decode($data);

  // If this isn't json data return nothing.
  if (empty($data_array)) {
    return '';
  }
  // Otherwise, return raw json data.
  else {
    \Drupal::logger('jmt_classes')->notice("Successfully got data from $uri");
    return $data;
  }
}
</code>
This has the advantage that I don't do any preprocessing. The change happens when the data changes when cron runs, not on every page load. This is important because fetching the data is SLOW!


How to connect database in php file?

Question: I have a custom module and in this module I've a .php file and inside this file I need to insert the data into database. I am using below code:
  define('DRUPAL_ROOT', getcwd());
  header('Access-Control-Allow-Origin: *');
  include_once DRUPAL_ROOT . '../includes/bootstrap.inc';

  include_once DRUPAL_ROOT . '../includes/database.inc';
  include_once DRUPAL_ROOT . '../includes/database.mysql.inc';
  conf_init();
  drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);
  drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
  $userid = $_POST['user'];
  $module_name = $_POST['module'];
  $name = "_user_role_".$userid;
  $fe_id = db_insert('role')
    ->fields(array(
      'name' => $name,
    ))
    ->execute();

Its give below error:
Answer: getcwd gets the current working directory, i.e. the one you're executing the script from.
If you need DRUPAL_ROOT to refer to the root of your Drupal installation, run the script from that directory, not the one that contains your module.
If you want to execute it from the module directory, fix the paths to the includes in your script.
Answer: Your code has issue in first line it-self:
define('DRUPAL_ROOT', getcwd());

getcwd() as per described on PHP.net

Gets the current working directory

Because of getcwd() your Drupal Root directory is set to your module directory and PHP isn't able to find bootstrap.inc and database.inc.

How to connect database in php file?


Show: $(X,d_X)$ is complete $\Leftrightarrow $ $f(X)$ is closed in $(Y, d_Y)$ ($f: X \to Y$ is an isometric embedding)

Question: I have the following task:

Show that a metric Space $(X,d_X)$ is complete if and only if for every isometric embedding $f: X \to Y$ in another metric Space $(Y, d_Y)$ it holds true that $f(X)$ is closed in $Y$

Any ideas or hints on how to prove this? Thanks in advance.
(I know that since $f$ is isometric it preserves the distance between two points and that since it's an embedding it's injective and continous. I further know that for every metric space there exists a completion i. e. there exists a metric space $(Z, d_Z)$ and an isometry $\phi : X \to Z$ so that $\phi (X) $ is dense in $Z$. But i don't really know how to pack all this together and get the prove)
Answer: The more difficult part is, in fact "$ \Leftarrow $", i.e the fact that $(X,d_x)$ is complete, but according to what you have written you have all the necessary ingredients.
Consider the obvious inclusion $i$ of $(X,d_x)$ into it's completion $(X_c, d_{X_c})$ (which, also obviously, is an isometry) and consider the image of a Cauchy sequence $x_n$ under this inclusion. This is, of course, also a Cauchy sequence since $i$ is an isometry. Since the target $X_c$ is complete, $i(x_n) $ converges to $x_c\in X_c$, and since the image is closed, $x_c=i(x)$ for some $x$. Since $i$ is an isometry, $d(x_n, x) = d(i(x_n), x_c)$ which tends to $0$, so $x_n\rightarrow x$ and $X$ is complete w.r.t $d_X$
I leave the other direction, which is a bit simpler, to you (or someone else).
Comment: @DeltaChief One criterion for a subset of a metric space $X$ to be closed is as follows: $A$ is closed in $X$ if and only if for every sequence $x_n$ with $x_n \in A$ which converges to some $x_* \in X$ the conclusion $x_* \in A $ is true. I just applied this to the sequence $i(x_n)$ and the fact that, by assumption, the image of $i$ is closed (in $X_c$).
Comment: @DeltaChief Hmm, $f^{-1}$ is defined only on the image of $f$. The idea goes into the correct direction, though. If you are not sure about how to deal with closed sets you should drill into the topic until it's clear. But you can argue along the lines of the criterion I just told you about. Consider $f(x_n)\rightarrow y\in Y$. So $f(x_n)$ is Cauchy. Then $x_n$ is Cauchy (Here we apply $f^{-1}$, but only on an allowed set), so there is $x$ such that $x_n\rightarrow x$. Then $f(x)=y$ (why?), and we see that $y\in f(X)$, so $f(X)$ is closed (using the property from my previous remark).
Comment: Why exactly do you know that if the image $i(X)$ is closed in $X_c$ that there exists a $x\in X $ so that $i(x)=x_c$ (i. e. how do you know that $i$ is surjective)? I think i don't really understand what it means that $i()$ is closed **IN** $X_c$
Comment: Ah ok, thanks a lot, i have an idea for the other direction: since $f$ and $f^{-1}$ are continuous and $X$ is both open and closed (clopen), i can say that it is closed and then use that preimages of closed sets are closed: $f^{-1}$ continuous and $X$ is closed $\Rightarrow$ ${f^{-1}}^{-1}(X)=f(X)$ is closed. Is this reasoning correct ? (I'm not sure about saying that $X $ is closed).


How to validate data while using the getters and setters short hand in C#

Question: I want to ask that can I validate data if I use the getters and setters short hand
public int GrossSallery { get;set; }

Actually I don't want users to come and just provide some random input. I know I can use the extended properties like
public int GrossSallery
    {
        get
        {
            return this.tax;
        }
        set
        {
            if (value <= 0)
            {
                return;
            }
            this.tax = value;
        }
    }

Comment: Possible solution is creating a custom validation class inherited from the [ValidationAttribute Class](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.validationattribute?redirectedfrom=MSDN&view=net-7.0). Usually this solution is using when required to validate a few properties with similar logic. See [Validating properties in c#](https://stackoverflow.com/q/4946227/6630084)
Comment: You might want to rename your property GrossSalary.
Comment: depending on your use-case you could validate using data annotations and validation attributes e.g. https://stackoverflow.com/questions/7926693/validation-using-attributes
Comment: Simpler syntax is in the language to be used on simpler problems. If you need something more complex then use the facilities also in the language that help in those situations. Don't try to hard to come up with something clever surrounding a simple syntax to attach somehow the more complex stuff. Applied here using explicit getter/setters is not "bad" when you need something to do something in there.
Comment: One comment about the provided code. When the value is zero or less, you do a direct return. This means that the caller never knows when the value actually is set or not. Either throw an OutOfRangeException or create a method to `bool TrySetGrossSallery(value)`
Answer: As far as I know this isn't possible without a private field. But you can shorten your example like this.
private int tax;
public int GrossSallery
{
    get=> tax;
    set => tax = value <= 0 ? tax : value;
}

Answer: I recommend using a method instead of the setter because a property setter should not contain logic. Additionally make the setter private so it can only be set using the method.
Could look like this
public int GrossSalary { get; private set; }

public void TrySetGrossSalary(int grossSalary)
{
   //Validation and setting property
}

Comment: "because a property setter should not contain logic" - well that right there is a bold statement; it probably shouldn't have side-effects, but: *validation* logic is normal and expected in a setter


What does it mean to say that a theory is more expressive than another?

Question: Mathematicians sometimes say, "ZFC set theory is more expressive than Peano Arithmetic". But what does this mean, rigorously? After all, ZFC set theory has only one binary relation symbol $\in$ besides equality, while Peano Arithmetic has the constants $0$ and $1$, the unary operation $S$ of successor, and the binary operations $+$ and $\cdot$. So, on the face of it, it would seem that Peano Arithmetic is more expressive than ZFC. Anyway, what is the real definition of a theory being more expressive than another?
Comment: You're mixing a language and theory. Take the language with infinitely many function symbols, $n$-ary relations for any $n$, and constant symbols. But no axioms. Can you prove anything about anything?
Answer: First of all, note that we have an obvious way to "translate" a sentence $\sigma$ in the language of arithmetic into a sentence $\hat{\sigma}$ in the language of set theory ("replace $\mathbb{N}$ with $\omega$," essentially). We then have the following:

Whenever $\mathsf{PA}\vdash\sigma$ we have $\mathsf{ZFC}\vdash\hat{\sigma}$ but  not conversely.

But of course this is contingent on the specific translation used. The real power of $\mathsf{ZFC}$ over $\mathsf{PA}$ is seen when we consider all possible translations of an appropriately "structurally meaningful" type: these are the interpretations. The idea of interpreting one theory $T$ inside another theory $S$ is an extremely important one. The definition of an interpretation is a bit tedious, but basically an interpretation of $T$ in $S$ consists of

a "domain formula" $\delta(x_1,...,x_n)$;

an "equivalence formula" $\eta(x_1,...,x_{2n})$; and

for each $k$-ary relation symbol $R$ in the language of $T$, a $kn$-ary formula $\varphi_R(x_1,...,x_{kn})$ (WLOG the language of $T$ is relational),

such that

$S$ proves that $\eta$ defines an equivalence relation on (the set picked out by) $\delta$ and each $\varphi_R$ is well-defined up to $\eta$, and

$S$ proves the translation of $T$ into $S$ provided by the tuple of formulas above (replace each "$\forall x$" with "$\forall x_1,...,x_n\in\delta$," each "$=$" with "$\eta$," and each "$R$" with "$\varphi_R$" appropriately).

For example, the usual "implementation" of the rationals as equivalence classes of ordered pairs of integers with second coordinate nonzero corresponds to an interpretation of $Th(\mathbb{Q};+,\times)$ into $Th(\mathbb{Z};+,\times)$ with domain formula $\delta(x_1,x_2)\equiv \neg x_2=0$ and equivalence formula $\eta(x_1,x_2,x_3,x_4)\equiv x_1\times x_4=x_3\times x_2$.
(Note that there's also a notion of a single structure being interpretable in another structure; I'm guilty of this usage here. Additionally, the word "interpretation" gets used to describe the assignment of relations/functions to symbols in the definition of a structure. Logic has serious terminology problems.)
The connection to your question is the following:

$\mathsf{PA}$ is interpretable in $\mathsf{ZFC}$ but not conversely.

The map $\sigma\rightarrow\hat{\sigma}$ does in fact come from an interpretation (namely the usual interpretation of $\mathbb{N}$ as $\omega$), so this point strictly refines the previous one. Of course at a very coarse level $\mathsf{PA}$ and $\mathsf{ZFC}$ are computationally equivalent, in the sense that the deductive closure of each has Turing degree ${\bf 0'}$, but this is so coarse as to be basically useless; by contrast, interpretability strength is extremely interesting and well-studied.
Comment: Why did you use the wavy version of the arrow in your last paragraph? What does it mean?
Comment: @Alex No reason, fixed.


Como substituir um espaço por ponto e vírgula entre duas palavras com o gsub()

Question: Tenho um problema para resolver e não consigo escrever a regex correta. Quero acrescentar o ponto e vírgula entre dois emails:
ex <- "firstname.lastname@example.com email@example.com"

#resultado esperado:
[1] "email@example.com;firstname.lastname@example.com"

Agradeço pela ajuda!
Answer: Aqui vai:
ex <- "email@example.com firstname.lastname@example.com"

# Com o gsub()
gsub(pattern = "[[:blank:]]",
     replacement = ";",
     x =  ex)

# Com str_replace_all(), que eu prefiro
library(stringr)
str_replace_all(string = ex,
                pattern = "[[:blank:]]",
                replacement = ";")

Você também poderia fazer isso:
str_replace_all(string = ex,
                pattern = "[ ]",
                replacement = ";")

Ou então isso:
str_replace_all(string = ex,
                pattern = "[[:space:] ]",
                replacement = ";")

[[:blank:]] funciona para eliminar todo tipo de espaço em branco, inclusive tabs, etc. Com [ ] (um espaço entre colchetes) você só remove o espaço comum mesmo. E com [[:space:]] é possível eliminar espaços, tabs e também quebras de linha.
Comment: eu estava escrevendo o [[:blank:]] errado e não estava dando certo. Obrigada!


Unable to disable write-caching on Azure Data Disk

Question: We have a DSv2 azure VM with Windows Server 2012 R2, with a 1TB premium storage virtual disk added.  This will be hosting a marklogic database where it is normally required the write-caching be disabled.  The operating system reports that this can not be done
Is there any way to do it?  Does write caching on this type of virtual disk not pose a problem for databases for some reason? The link that says "how can I change the write-caching setting for this devices" does not function.
Comment: http://www.virtualizationadmin.com/articles-tutorials/microsoft-hyper-v-articles/management/hyper-v-optimization-tips-part1.html
Comment: Looks like that answers my question well. Happy to give you answer credit if you post it as an answer.
Answer: I found this link helpful, will be glad if it will help you.
http://hyper-v.nu/archives/hvredevoort/2013/07/keeping-your-virtual-active-directory-domain-controllers-safe/


Void Pointer within Class - Casting

Question: I have a c++ class as below. I am attempting to setup a thread as such below, where my callback (the void pointer function) is within the class. This throws an error on the pthread_create function where it says
cannot convert from type void*(Ball::)(void*) to type void*()(void)
class Ball
{
    private: struct BallMsg ballMsg;
    private: pthread_t ballThread;

    public: Ball(int id)
    {
        ballMsg.id = id;
        ballMsg.r = 7;
        ballMsg.x = 60 + (455/2) - 30;
        ballMsg.y = 60 + 10 + 5 + ballMsg.r;
        ballMsg.c = 0xFFFF0000;
        ballMsg.vel = 5.0;
        ballMsg.ang = 45.0;

        int ret;
        ret = pthread_create(&ballThread, NULL, this->ball_thread, NULL);
        if (ret !=0)
        {
            xil_printf("Error launching thread 1\r\n");
        }
    }

    public: void *ball_thread(void *arg)
    {
        int i = 0;
        while(1)
        {
            //unsigned int tval = sys_time(NULL);
            //xil_printf("%d : Time is: %d\r\n", i++, tval);
        }
    }

    public: ~Ball()
    {

    }
};

Comment: Wow..unbelievable. I just got banned from stack overflow because you marked this as duplicate. Any way around this?
Answer: pthread_create expects a pointer to a non-member function, but void *ball_thread is a member of Ball. That means it needs a Ball object to be called on an so has a fundamentally different structure to a non-member.
You can use std::thread instead, which makes it easy to bind an object to a member function.
Alternatively, you can the ball_thread function a non-member, and pass a Ball* first parameter if required.
Comment: unfortunately this is for an embedded platform which doesn't support std::thread. What option do i have now? I have to make it static?
Comment: @raaj Yes, you do. But you could use the thread argument (`arg`) to pass the object pointer.
Comment: how can i do that? just pass in "this"? If so how can i cast and get my object back?
Comment: @raaj do you know how casts and void* work?
Comment: i think so. passing this in is passing the current object's address into the thread to reference. from there i did this. Ball *ball = static_cast(arg);

Void Pointer within Class - Casting


Callbacks in Ruby on Rails

Question: Using the 'oauth2' gem and a Heroku server, I have managed to create a client object and redirect the user to the login site:
client = OAuth2::Client.new(
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
:authorize_url => "/oauth/authorize",
:token_url => "/oauth/token",
:site => "https://connect.xxxxxxxxxx.com")

redirect_to(client.auth_code.authorize_url(:redirect_uri => 'https://xxxxx.herokuapp.com/callback'))

The browser afterwards redirects itself to the callback link as intended, something like:
https://xxxxx.herokuapp.com/callback?code=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

I need to access the authorization code to then send a post request for the access token and refresh token, but being totally new to Ruby and Ruby on Rails, I am not sure how to get the callback and parse the code out.  All of the dozen tutorials/documentation I've researched just mention that the authorization code should be 'magically obtained,' but I'm not sure how exactly that works explicitly.  I tried creating a 'callback' controller and view to no avail - is there something missing in the routes files possibly? Help is much appreciated!
Answer: Your CallbackController will start to look like this maybe:
class CallbackController < ApplicationController
  def index
    access_token = client.auth_code.get_token(params[:code], redirect_uri: 'https://xxxxx.herokuapp.com/callback')
    # Now you have an OAuth2::AccessToken object that you can either use to:
    # - make direct requests to the API
    # - or access access_token.token, access_token.refresh_token, access_token.expires_at, access_token.expires_in and store those
    #   somewhere for later use
    # http://www.rubydoc.info/github/intridea/oauth2/OAuth2/AccessToken
  end

  private

  def client
    @client ||= OAuth2::Client.new(
      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      authorize_url: "/oauth/authorize",
      token_url: "/oauth/token",
      site: "https://connect.xxxxxxxxxx.com"
    )
  end
end

Callbacks in Ruby on Rails


Every 7th character of the line has to be a +

Question: The problem is the following:
I have a document called brain.txt with lines of characters like this:
++++++++++[>++++++++>++++++>+<<<-]>+++.>+++++.<-.+.>>. word

The word at the end can really be any word.
How can i filter the lines from the document where every 7th character is a plus?
example: +......+......+......+..... word
I wrote the following command:
egrep '^\+(.{6}\+)+.{,6}\s' brain.txt

But it does not seem to work, can anyone explain me what is incorrect about this command please?
Comment: @antak no I didn't fix it. the backslashes were just not displayed due to a lack of code formatting. the problem is still there and a different one
Comment: The regex you've listed [will correctly capture](http://rubular.com/r/pxBsVORD2G) the input line you've given. What is the problem?
Comment: This question no longer makes sense because what was wrong with it was *fixed* in an edit..
Comment: @ean5533 It just does not return any of the lines listed in the file.
Comment: @ean5533 the problem is regex flavor specific, so unfortunately, your argument is invalid ;)
Comment: @m.buettner oic, I thought the answer you deleted was spot on, but didn't know it was just a thing with SO.  Thanks for the insight.
Comment: @antak, no I just fell victim to the same mistake ;). I first posted the answer, then reformatted the question, but did not see that the backslashes were actually there. but luckily the mistake could now be found anyway ;)
Answer: The problem is the shorthand notation {,6} which does not seem to work with the given regex flavor. Simply write it out:
egrep '^\+(.{6}\+)+.{0,6}\s' brain.txt

Note that this requires at least 2 +s. The single \+ at the beginning, and another one in the subpattern (because it is repeated at least once). If +.... word would be a valid line for you, use:
egrep '^\+(.{6}\+)*.{0,6}\s' brain.txt

Comment: @user1790040 ah okay, couldn't have known that ;)


Using class objects in functions

Question: I'm new to C++ and I'm trying to make a program to do conversions between two objects. I have Class1, Class2 and Convert. I want a function that takes in a Class1 object, converts it to a Class2 object and returns the Class2 object. Right now my convert class is basically:
Convert.h
#ifndef Convert_H
#define Convert_H
#include "Class1.h"
#include "Class2.h"

class Convert
{
public:
    Convert();
    Class1 c1;
    Class2 c2;
    Class2 C1ToC2(Class1);

};
#endif // Convert_H

Convert.cpp
#include "Convert.h""
#include "Class1.h"
#include "Class2.h"

Convert::Convert()

Class2 Convert::C1ToC2(Class1 c1)
{
    //conversions

    return c2;
}

I have a few questions about this. I don't want to have the convert functions in the other classes which is why I created a separate class.

Is this a good way to use functions that I don't want to be apart of the other classes
When I compile this class it fails saying "expected initializer before Class2 but since I want to return a Class2 object isn't that how I have to define the function?

Once again I am new to C++, I do have a few books that I'm trying to learn from but they don't really tell how to use objects like this so I apologize if this is a stupid question and I'm doing it completely wrong.
Answer: In C++, you can simply use a function directly, you don't need a class Convert.
In Convert.h:
#ifndef Convert_H
#define Convert_H

#include "Class1.h"
#include "Class2.h"

// declare the function
Class2 convert( const Class1& input );

#endif

and in Convert.cpp:
#include "Convert.h"

// define the function
Class2 convert( const Class1& input )
{
    Class2 result;
    // do conversion
    return result;
}

Note that this is just the basics, it can be improved in several aspects but it should help you to get started and experiment on your own.
Comment: Where would I define this function? Do I just create a blank file?
Comment: @rsay3 I edited the answer to show how your files should look like, I think that's easier than explaining in a comment.
Comment: Thank you! One last question, with the variables do I still include those in the header or can I just initiate them in the .cpp functions?
Comment: @rsay3 Which variables? You need *just* the above, what I have shown is complete.
Comment: Well I'm going to have multiple functions such as `Class2` convert to `Class1` and I will have variables common amongst both of them, should I just define them in each function or can they be global variables?
Comment: @rsay3 It's hard to tell, since you seem to be doing some things that an experienced developer can't even imagine. No offense intended, that's a normal thing. It's just that from your description I still have no idea what exactly you are doing and *how* you are doing that. Maybe create another example (preferably a [SSCCE](http://sscce.org)) and ask another question?
Answer: With regards to your second question, the reason the code doesn't compile is because you forgot the curly braces after Convert::Convert(). (Or maybe a semicolon. But I assume you wanted to define the ctor)
Comment: `Convert::Convert();` wouldn't be legal either.  A declaration of a member outside the class must actually define it.

Using class objects in functions


How to set ActionBar logo to Text (TextView)?

Question: I've been trying to make the ActionBar logo, or the Up button, a text instead of an image. actionbar.setLogo(); accepts only a drawable resource. Inflating a layout with a TextView didn't do the trick.
Basically, what I'm trying to accomplish is this:

The first one is from the new DeskClock app from Android 4.2 and the second is from the Contacts app. I checked the code in GitHub but I couldn't find anything.
Comment: [Styled Action Bar](http://code.google.com/p/styled-action-bar/)
Answer: Off the cuff:
Option #1: Draw your text (TextView or directly) on a Bitmap-backed Canvas, and then supply a BitmapDrawable to setLogo().
Option #2: Hide the icon and logo and use setCustomView() to have your caret image and your text.
Comment: I think option #2 has the disadvantage that you can't display a title, because the title is to the left of the custom view. But option #1 is perfect, see my answer.
Comment: @matthias: Your custom view is welcome to contain a title `TextView`, along with the caret and other text. That being said, I am glad that you have something working to your satisfaction.
Answer: Here is an implementation of @CommonsWare's option #1, works perfectly.
TextView upTextView = (TextView) getLayoutInflater().inflate(
        R.layout.up_text, null);
upTextView.setText("CITIES");
upTextView.measure(0, 0);
upTextView.layout(0, 0, upTextView.getMeasuredWidth(),
        upTextView.getMeasuredHeight());
Bitmap bitmap = Bitmap.createBitmap(upTextView.getMeasuredWidth(),
        upTextView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
upTextView.draw(canvas);
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), bitmap);

R.layout.up_text:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="4dp"
    android:paddingRight="4dp"
    android:textColor="#f00"
    android:textSize="20sp"
    android:textStyle="bold" />


Thread refuses to quit

Question: Source: https://mega.co.nz/#!xUMiSRYC!Y8Sxz2fEFb6yEIrnKiGx9n2zeK4YTUwUrCByaAkcOPI
I'm experiencing a problem with QThread::currentThread()->quit();
If you open up my myobject.cpp and go to line 13, the quit() call is supposed to exit. But it seems the quit() call isn't working and it just skips it. Can't see the problem. :(
main.cpp:
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    QObject::connect(&a, SIGNAL(aboutToQuit()),
                     &w, SLOT(cleanUp()));

    return a.exec();
}

mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "myobject.h"
#include <QMessageBox>

MyObject* cObject;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setFixedSize(this->size());

    cThread = new QThread(this);
    cObject = new MyObject();
    cObject->moveToThread(cThread);

    QObject::connect(ui->pushButton_2, SIGNAL(clicked()),
                     this, SLOT(close()));

    QObject::connect(cThread, SIGNAL(started()),
                     cObject, SLOT(doWork()));

    QObject::connect(ui->pushButton, SIGNAL(clicked()),
                     this, SLOT(runThreadSlot()));

    QObject::connect(cThread, SIGNAL(finished()),
                     cThread, SLOT(deleteLater()));

    QObject::connect(cThread, SIGNAL(finished()),
                     cObject, SLOT(deleteLater()));

    QObject::connect(cObject, SIGNAL(setStatusBarSignal(QString)),
                     this, SLOT(setStatusBarSlot(QString)));

    ui->lineEdit->setValidator(new QIntValidator(this));
    ui->lineEdit->setFocus(Qt::OtherFocusReason);
    ui->statusBar->showMessage("Waiting for input...");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::runThreadSlot()
{
    cThread->start();
    // I've trimmed some code here.
}

void MainWindow::setStatusBarSlot(QString text)
{
    ui->statusBar->showMessage(text);
}

void MainWindow::cleanUp()
{
    qDebug() << "Cleaning up!";
    cObject->stage = 0;
    cThread->wait();
}

myobject.cpp:
#include "myobject.h"
#include <QPixmap>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

MyObject::MyObject(QObject *parent) :
    QObject(parent)
{
}

void MyObject::doWork()
{
    QThread::currentThread()->quit(); // It doesn't stop here. This is my issue.
    // I've trimmed the code here.
}

mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void runThreadSlot();
    void setStatusBarSlot(QString);
    void cleanUp();

private:
    Ui::MainWindow *ui;
    QThread* cThread;
};

#endif // MAINWINDOW_H

myobject.h:
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include <QtCore>

class MyObject : public QObject
{
    Q_OBJECT
public:
    explicit MyObject(QObject *parent = 0);
    QFile path;
    qint32 waitSecs;
    int stage;

signals:
    void setStatusBarSignal(QString);

public slots:
    void doWork();

};

#endif // MYOBJECT_H

Comment: you should post your code, not provide a link to download it
Comment: @ashley: It requires files though for resources.
Comment: You should post the _relevant_ part of your code here, or better yet an [SSCCE](http://sscce.org/). No-one here is going to go through that blind link and download from that fishy source.
Comment: Maybe I should just start a new project, try to replicate this issue, and repost this question?
Comment: Yes, trying to isolate the issue and posting a _minimal_ piece of code that reproduces it is exactly what you should be doing. Edit your question so that includes only that minimal test-case once you manage that.
Answer: QThread::quit() is asynchronous. You shoul add QThread::currentThread()->wait() right after quit.

Thread refuses to quit


SSH: Configure ssh_config to use specific key file for a specific server fingerprint

Question: I have a key based login for a server. The IP and DNS of the server can change, because it is hosted on Amazon.
Is there a way to configure the ssh client config to use the specific key file for this server only, when the fingerprint of the server matches?
In other words: Normaly servers are matched by IP or DNS in the ssh client config. I want to do this by fingerprint, becaus IP and DNS can change.
Answer: You can use wildcards in a Host section in ~/.ssh/config. If you use EC2's hostname to connect to your instances the following should work:
Host *.compute-1.amazonaws.com
    IdentityFile ~/.ssh/id_rsa.aws
    # If you don't want to verify host fingerprints because they change all the time
    CheckHostIP no
    StrictHostKeyChecking no
    UserKnownHostsFile /dev/null

If you use the IP addresses you'll have to find the right IP ranges and add appropriate wildcard entries to match those.
Answer: Try if this works for you: add to ~/.ssh/config file the following:
Host alias_for_host_you_want_to_connect
HostName real_name_for_host_you_want_to_connect
CheckHostIP no
IdentityFile /path/to/your/keyfile
#StrictHostKeyChecking no

(comment out the last line if everything else fails)


"list" plugin does not exist after upgrading from Drupal 8.3.x to 8.4.2

Question: How can I tell exactly what is missing and from which module? (I assume it's draggableviews)
How can I remedy this error - or is it in the hands of a contrib module developer or where can I go to see how to contribute the missing plugin?
This is the output of drush @badev updb.
 ---------------- --------------------------------- --------------- -------------------------------------------------------------------------
  Module           Update ID                         Type            Description
 ---------------- --------------------------------- --------------- -------------------------------------------------------------------------
  draggableviews   8104                              hook_update_n   Implements hook_update().
  comment          enable_comment_admin_view         post-update     Enable the comment admin view.
  dblog            convert_recent_messages_to_view   post-update     Replace 'Recent log messages' with a view.
  field            remove_handler_submit_setting     post-update     Remove the stale 'handler_submit' setting for entity_reference fields.
  node             configure_status_field_widget     post-update     Load all form displays for nodes, add status with these settings, save.
  system           classy_message_library            post-update     Clear caches to ensure Classy's message library is always added.
  system           field_type_plugins                post-update     Force field type plugin definitions to be cleared.   @see
                                                                     https:www.drupal.orgnode2403703
  views            revision_metadata_fields          post-update     Fix table names for revision metadata fields.
 ---------------- --------------------------------- --------------- -------------------------------------------------------------------------

 Do you wish to run the specified pending updates? (yes/no) [yes]:
 > yes

 [notice] Executing draggableviews_update_8104
 [error]  The "list" plugin does not exist.
 [ok] Performing draggableviews_update_8104
Array   Array
 [success] Cache rebuild complete.
 [success] Finished performing updates.
Connection to drupal8vm.dev closed.

Answer: This is solved now. I think that there was a mismatch between the PHP/ Drush / Drupal 8.4.3 versions.
This confused me so I include a table below of what is now working for me. I used it as a checklist to ensure that I had both a dev Drupal 8.3.7 and a dev Drupal 8.4.3 running in parallel.
Despite what the documentation says I think Drush 8.1.15 is not suitable for Drupal 8.4.3 and yes, there are some Drush 9.0.0-rc1 commands that don't work as expected  - like dumping SQL and redirecting SQL files to drush sqlc -  but it is workable.
Bits and pieces in each of existing and future Drupal
               iMac               MacBook
PHP VM         7.1.12             7.1.12
PHP Host       7.1.12             7.1.12
Drush VM       8.1.16-dev         ~9.0
Drush Host     8.1.15             ~9.0
Drupal Core    8.3.7              8.4.3
MySQL          5.7.20             5.7.20   (Required MySQL 5.5.3/MariaDB 5.5.20)


How to sort Hashmultimap based on value?

Question: I am using HashMultiMap in my code. My HashMultiMap structure is like,
HashMultimap<String, Integer> map = HashMultimap.create();

map.put("a", 3);
map.put("m", 5);
map.put("l", 1);

System.out.println(map);

actual output:{a=[3], l=[1], m=[5]}
now, i want to sort it based on value:
target output:{m=[5], a=[3], l=[1]}
Comment: can  you do like `map.getValues()`?
Comment: yes, i can use this function:

    public Set get(K k)
Comment: @AhmadAlKhazraji Why are you using the `HashMultimap`class since a simple `HashMap`can do the job ?
Comment: @Zakaria becasue keys in my case can be repeated..
Comment: [similar issue](http://stackoverflow.com/a/17200728/3835388)
Comment: I'm not sure this makes sense: what if you have {m = [5, 2], a = [3], l = [1]}?  Do you want to sort the entries by...what, the highest value they have?  Before you work out _how_ to do what you want, you should make sure you fully understand what it is you want...
Comment: @LouisWasserman thank you for your advise..
i think solution is swapping the role of the keys and the values..
Comment: @LouisWasserman
my problem is:
the key is username, the value is user's score. i want to return top n users with highest scores.

but in a map, we should sort by key not by value, so the key should be score, the value should be user name, the data structure should be sorted multi-value map: there can be multiple values for a same key, and it's sorted by key.
Comment: Since you're now twisting keys and values, I suggest you take a look at [this earlier similar question](http://stackoverflow.com/questions/5501468/having-a-multimap-sorted-on-keys-only-in-java).
Answer: If you actually do want to sort on values the solution would be to extend ForwardingSortedSetMultimap and delegate to TreeMultimap.
The example below expects the Keys and Values to implement Comparable but the class can easily be modified to support supplied Key and Value Comparators.
public class SortedValueTreeMultimap<K extends Comparable<K>, V extends Comparable<V>> extends
        ForwardingSortedSetMultimap<K, V> {

    private final Ordering<Map.Entry<K, Collection<V>>> mapEntryOrdering = new Ordering<Map.Entry<K, Collection<V>>>() {

        @Override
        public int compare(final Entry<K, Collection<V>> left, final Entry<K, Collection<V>> right) {

            // Safe as we cannot have nulls or empties
            return ComparisonChain.start()
                .compare(left.getValue()
                    .iterator()
                    .next(), right.getValue()
                    .iterator()
                    .next())
                .compare(left.getKey(), right.getKey())
                .result();

        }
    };

    public final Ordering<Entry<K, V>> entryOrdering = new Ordering<Map.Entry<K, V>>() {

        @Override
        public int compare(final Entry<K, V> left, final Entry<K, V> right) {

            return ComparisonChain.start()
                    .compare(left.getValue(), right.getValue())
                    .compare(left.getKey(), right.getKey())
                    .result();
        }

    };

    public final Comparator<Entry<K, V>> entryOrderingReverse = Collections.reverseOrder(this.entryOrdering);

    private final SortedSetMultimap<K, V> delegate = TreeMultimap.create();

    @Override
    protected SortedSetMultimap<K, V> delegate() {

        return this.delegate;
    }

    @Override
    public Set<Entry<K, V>> entries() {
        return FluentIterable.from(super.entries())
            .toSortedSet(this.entryOrdering);

    }

    public Set<Entry<K, V>> reverseEntries() {
        return FluentIterable.from(super.entries())
                .toSortedSet(this.entryOrderingReverse);
    }

    @Override
    public String toString() {
        return FluentIterable.from(this.asMap()
            .entrySet())
            .toSortedSet(this.mapEntryOrdering)
            .toString();

    }

    public static void main(final String... args) {

        final SortedValueTreeMultimap<String, Integer> sortedMap = new SortedValueTreeMultimap<String, Integer>();

        sortedMap.put("a", 7);
        sortedMap.put("a", 3);
        sortedMap.put("a", 7);
        sortedMap.put("m", 5);
        sortedMap.put("m", 4);
        sortedMap.put("m", 4);
        sortedMap.put("k", 1);
        sortedMap.put("j", 1);

        // [j=[1], k=[1], m=[4, 5], a=[7]]
        System.out.println(sortedMap);

        // [j=1, k=1, a=3, m=4, m=5, a=7]
        System.out.println(sortedMap.entries());

        // [a=7, m=5, m=4, a=3, k=1, j=1]
        System.out.println(sortedMap.reverseEntries());
    }
}