Tables are not creating with hook_schema

Question: I need to create a module to save data of term page visits.
<code><?php

function term_count_schema() {
  $schema['term_search'] = array(
  'description' => 'Stores timestamp range..',
'fields' => array(
  'tid' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Taxonomy ID.',
   ),
  'vid' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Vocabulary ID.',
    ),
  'timestamp' => array(
    'type' => 'int',
    'not null' => FALSE,
    'description' => 'UNIX timestamp.',
   ),
 ),
 'primary key' => array('tid'),

  );

  $schema['term_count'] = array(
'description' => 'Total views.',
'fields' => array(
  'tid' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Taxonomay ID.',
  ),
  'vid' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Vocabulary ID.',
  ),
  'totalviews' => array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'size' => 'tiny',
    'description' => 'Total number of views which increments on every page load.',
  ),
),
'primary key' => array('tid'),
  );
  return $schema;
}
</code>
This is not creating tables term_search & term_count ind DB. Any thing wrong in my code.
Answer: <code>    <?php
/**
 * @file
 * Contains install and update functions for Views.
 */

/**
 * Implements hook_install().
 */
function mid_components_install(){

}

/**
 * Implements hook_schema().
 *
 */
function mid_components_schema(){
    $schemas = array();
    $schemas['mid_components'] = array(
        'description' => 'The mid_components data.',
        'fields' => array(
            'cid' => array(
                'description' => 'Primary key',
                'type' => 'serial',
                'unsigned' => TRUE,
                'not null' => TRUE,
            ),
            'title' => array(
                'description' => 'Human readable name of the component.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
            ),
            'machine_name' => array(
                'description' => 'Unique machine name of the component',
                'type' => 'varchar',
                'length' => 255,
                'not null' => TRUE,
            ),
            'description' => array(
                'description' => 'Description of the component.',
                'type' => 'varchar',
                'length' => 255,
                'not null' => FALSE,
            ),
            'options' => array(
                'description' => 'A serialized array of options for this display; it contains options that are generally only pertinent to that component.',
                'type' => 'blob',
                'size' => 'big',
                'not null' => FALSE,
            ),
            'status' => array(
                'description' => 'Status of the component',
                'type' => 'int',
                'not null' => TRUE,
                'default' => 0,
                'unsigned' => TRUE,
            ),
            'created' => array(
                'type' => 'int',
                'description' => 'The Unix timestamp when the item is created',
                'not null' => TRUE,
                'default' => 0,
            ),
            'changed' => array(
                'type' => 'int',
                'description' => 'The Unix timestamp when the item is modified.',
                'not null' => TRUE,
                'default' => 0,
            ),
        ),
        'primary key' => array('cid'),
        'unique key' => array('machine_name' => array('machine_name')),
    );
    return $schemas;
}

/**
 * Implements hook_uninstall().
 */
function mid_components_uninstall(){

}
</code>
Follow this method. And Make sure after doing any chnagings to your .install file, uninstall your module and reinstall it again.
Comment: Thanks Suagndh Khanna. It works for single table. I need one more table in DB. How i can create one more table within one hook_schema()
Comment: You can have multiple schemas under single hook_schema. For better understanding try exploring Drupal contrib modules - .install file.


In what coordinates do the Christoffel symbols of this flat connection vanish?

Question: Let $M$ be a submanifold of a pseudo-Riemannian manifold $N$ such that the Levi-Civita connection of $N$ is flat. For simplicity, since this seems to already include the general case, let us restrict in this question to the case of $M = S^{d - 1}$ embedded the usual way in $\mathbb R^d$. For $d \geq 3$, the Levi-Civita connection on $TM$ is obviously not flat, but we can embed $TM$ in the bundle $V := TM \oplus NM = M \times \mathbb R^d$. The natural connection $D$ on $V$ is defined by $D_v X = \nabla_v X$, i.e. it is the restriction of the Levi-Civita connection on $\mathbb R^d$. Thus for vector fields $v, w$ tangent to $M$ we have
$$[D_v, D_w] = [\nabla_v, \nabla_w] = [v, w]$$
i.e. $D$ is flat. So there exists a coordinate frame on $M$ such that all the Christoffel symbols of $M$ vanish.
However, it's not clear to me what that coordinate frame should be. Some candidates are the coordinates you get by thinking of the half-spheres as graphs (i.e. just forget about the $d$ coordinate and let $x^i$ be the $i$th coordinate on $\mathbb R^d$, $i = 1, \dots, d - 1$), and the projection of any set of $d-1$ basis vectors of $\mathbb R^d$ onto the tangent space.
When I try to write out the connection in such coordinates and go through the manipulations, I mostly manage to give myself a headache rather than get a computation that seems to "go somewhere" and tell me what the Christoffel symbols are. But it seems like there should be some general theorem which tells me what coordinate frame to use to kill the Christoffel symbols, allowing me to avoid such tedious computations. Is there such a theorem?
Comment: Where are you getting $D_vX = \nabla_vX$?
Comment: It's the definition of the connection.
Comment: No, the connection on the $M$ is defined by projecting the flat ambient connection back to $TM$.
Comment: But this question wasn't about a connection for $TM$, it was about a question about the natural flat connection on $TM \oplus NM$.
Answer: It might be useful to review the definition of the Christoffel symbols of a connection on an arbitrary vector bundle. If $M$ is an $n$-dimensional manifold, $V\to M$ a rank $r$ vector bundle and $D$ is a connection on $V$, the connection can be locally described by a $1$-form.
Fix a local frame $\mathbf{s}=(s_1,\dots,s_r)$ for $V\to M$, i.e. a basis of local sections of $V$ over some open set $U\subseteq M$. Differentiating the $s_\alpha$ we obtain $$Ds_\alpha=:A^\beta_\alpha\otimes s_\beta$$
for a matrix $A=\left(A^\beta_\alpha\right)_{1\leq\alpha,\beta\leq r}$ of $1$-forms on $U$. Fixing a system of coordinates $\mathbf{x}=(x^1,\dots,x^n)$ for $M$ defined on $U$, each of the $1$-forms $A^\beta_\alpha$ can be written as $$A^\beta_\alpha=A^\beta_{\alpha\,a}\mathrm{d}x^a.$$ Notice that we are using greek indices $\alpha,\beta,\dots$ for the sections of $V$, and latin indices $a,b,\dots$ for the coordinates on $M$.
What usually happens in the Riemannian context is that you consider a particular connection on $V=TM$, and after having fixed a system of local coordinates $\mathbf{x}$ for $M$ you get the local frame of $M$ defined by $\partial_{x^1},\dots,\partial_{x^n}$, so the connections can locally be written as $$\nabla\partial_{x^a}=A^b_{ac}\mathrm{d}x^c\otimes\partial_{x^b}.$$ In this context we are allowed, to some extent, to confuse the local system of coordinates with the local frame for $V$. What we usually call Christoffel symbols are just the components $A^b_{ac}$.
Now, after this long introduction, let's get to the question. My point is that the right question is not "what are the flat coordinates on $M$", but rather "what is the flat frame for $V$". The first question really makes sense only for a connection on $TM$, while the second one can be asked of any flat connection on any vector bundle. In your case, we are considering a trivial vector bundle $M\times\mathbb{R}^d\to M$, and as such we have a global frame $s_1,\dots,s_d$ defined by $$s_\alpha(p)=(p,e_d),$$ where $e_1,\dots,e_d$ is a basis for the vector space $\mathbb{R}^d$. It seems to me that for the connection you have defined, this is the flat frame for $V$. Let me know if you find this useful!
Comment: I think I got a little mixed up, because I always had some kind of isomorphism or another to the tangent bundle or one of its tensor powers in mind, and so was always conflating "flat frame" with "flat coordinates" even though I knew in principle that they should not be the same. Thank you for the correction!
Answer: What you're looking for are perhaps geodesic normal coordinates. For example, reference here: Wikipedia.
Comment: Maybe I'm a little sleepy tonight but I don't see why the Christoffel symbols of the tangent bundle vanishing at one point implies that the Christoffel symbols of this larger bundle vanish everywhere.
Comment: What motivated my response is the second equation under explicit formulae on the Wikipedia: the Christoffel symbols vary at leading order with the Riemann tensor around the point where they vanish. That's where the flat connection comes in, no?
Comment: Good point, that might actually work. I'll have to think about it tomorrow.


Equation for a sphere after a projective transformation?

Question: I was wondering if there is a general equation for a sphere that has undergone a projective transformation (i.e, the sphere has been multiplied by a 4x4 homography matrix)?
I attempted to multiple the elements of the homography through the sphere equation, but it became really messy rather quickly and didn't look like something I could use.
My goal is to do a least square fit of such an object to some points, but I can't seem to find an equation (or even the terminology) for such an object.
Answer: I believe that a sphere that's undergone a projective transformation is called a conic (or the equivalent in 3D...right... it's a "quadric surface"). Suppose that you have the sphere defined by
$$
\newcommand{\xvec}{\mathbf x}\newcommand{\Imat}{\mathbf I}\newcommand{\Mmat}{\mathbf M}\newcommand{\yvec}{\mathbf y}\newcommand{\Amat}{\mathbf A}
\xvec^t \Imat \xvec = 1
$$
where $\xvec$ is the vector $(x, y, z, 1)^t$, and $\Imat$ is the 4x4 identity.
Now suppose that $\yvec = \Mmat \xvec$, where $\Mmat$ represents a nice invertible projective map. Let's say that $\Amat$ is the inverse matrix. Then you have
\begin{align}
\xvec^t \Imat \xvec & = 1 \\
(\Amat\yvec)^t \Imat (\Amat\yvec) & = 1 \\
\yvec^t \Amat^t \Imat \Amat\yvec & = 1 \\
\yvec^t (\Amat^t \Amat) \yvec & = 1
\end{align}
In other words, $\yvec$ satisfies an equation defined by the symmetric matrix $\Amat^t \Amat$. That's basically ends up being a quadratic expression in the entries of $\yvec$ being set equal to 1. So you get an ellipsoid, hyperboloid of one or two sheets, a sphere, or a paraboloid. I think that's the whole list.
Comment: Thank you! That's very informative.


Change parent window URL from iFrame

Question: I'm having a parent site at myurl.com from which I load an iFrame in a an overlay/modal layer. In the iFrame I have different tabs with steps 1-5 containing different form elements - in other words it's a kind of checkout flow. Each tab is located within a div with eg. the id "tab1".
I use the easytabs jQuery plugin (http://os.alfajango.com/easytabs/) which uses jQuery hash change in order to change the URL when you click on a tab so the URL would say eg. myurl.com#tab1. However, this doesn't work when the tabs are placed inside the iFrame. This is a problem because when you click the browsers back button you will leave the entire flow and possibly lose a lot of inputted data which means baaaaad UX.
So, my question is: Any ideas how to change the URL on the parent site from actions you make in the iFrame?
Thank you in advance!
Basically my code in the parent window "myurl.com" looks like this:

And the tabs in the iframe.html looks simply like this:

Go to tab1

Go to tab2

Answer: Try this

Also read more about top in HTML

_top
  loads content in the top-level frameset (in effect, the whole browser
  window), no matter how many nested levels down the current frame is
  located
Comment: If I use the above my URL looks like this: myurl.com/iframe.html#tab1 - the page refreshes and I only see the iframe.html content and not the parent site. The page should not refresh - it should only add the ID of the tab to the parent URL so it should look like this myurl.com#tab1
Comment: This works on the parent site - but not on the iframe. `       $('#tab1').click(function(e) {
           window.location.hash = $(this).attr('id');
           e.preventDefault();
       });
`
Comment: @McAsh , you marked this as the accepted answer, but your comments suggest no one could tell you how to change parent URL without refreshing -- did you find an answer? Maybe I'm mistaken. Thanks
Answer: One way to do it is using window.postMessage:
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
Answer: If you simply want to do it without using javascript, you could give:

By just mentioning the target as parent it will work even for cross domain iframes.
Answer: You can also do this if you're loading the iframe's url from the parent frame.

Comment: This doesn't do the trick either. I end up with the same URL as with the above suggestion and the page refreshes. It should only add the tab's ID at the end of the parent's URL.

Change parent window URL from iFrame


Showing that this triangle is a right triangle using vector algebra

Question: Given this polygon inscribed in a square, I must show that the triangle indicated in blue is right triangle and have side lenghts in proportion $3:4:5$:

I used the two sides from the left bottom corner as vectors $u$ and $v$ and I'm trying to write the vectors representing the sides of the triangle in terms of $u$ and $v$. Let $x$, $y$ and $z$ be these vectors, with $z$ being the (supposed) hypotenuse of the triangle. So
$$z = v + \frac{1}{2}u,$$
but I'm stuck trying to write $x$ and $y$ in terms of $u$ and $v$. Is this approach correct?
Comment: I believe the intent is to show that the triangle is a right triangle.
Comment: @user, you don't need to calculate any lengths if all you want to do is to show there's a right angle. You just need to calculate the slope of the line joining $(0,0)$ to $(1,2)$, and the slope of the line joining $(0,1)$ to $(2,0)$, and to see that those two slopes are negative reciprocals of each other. To finish the problem, to show it's a 3-4-5 triangle, for that, yes, more work is needed. But I reckon it's good to check it's a right angle first, so you don't waste any time on a wild goose chase if it isn't.
Comment: Unclear what the phrase *vector algebra* represents.  Anyway, denote the lower left and upper right Cartesian coordinates as $(0,0)$ and $(2,2)$ respectively.  Then all three vertices of the triangle are unambiguously defined.  For example, the vertices of the hypotenuse are $(2,0)$ and $(1,2)$.  So, all that you have to do is compute the coordinates of the *missing* vertex as the intersection of two well defined lines.  Then, you will know the coordinates of all three vertices of the triangle, and therefore can calculate the length of each leg of the triangle.
Comment: One leg has slope $2$, the other, $-1/2$, so they are perpendicular, so it's a right-angled triangle.
Comment: How can a triangle be a rectangle?
Comment: Re previous comment, the two pertinent line segments will have endpoints of $[(0,1)--(2,0)]$ and $[(0,0)--(1,2)]$.
Comment: @GerryMyerson unclear whether your comment  redundant, since *superficially*, you still need to calculate the length of the two legs.  Then, once these legs are calculated, you independently have $a^2 + b^2 = c^2$ (et al).
Comment: @GerryMyerson What I am hinting at is that I am weak at Geometry.  Instead of using my crude method, one might use your method as a starting point.  Then, instead of crudely solving for the coordinates of the 3rd vertex, one might (**somehow**) show that the two legs are in proportion of $(3::4)$.  If this is Geometrically demonstrable, then that coupled with your insight, would represent a Geometric solution to the problem.
Answer: let $\mathbf u = (-1,2), \mathbf v = (-2,1), \mathbf w = (1,2)$
These vectors are the hypotenuse and the extension of the legs of the triangle.
First, the triangle in question is right as the vectors v,w are orthogonal, or $v\cdot w = 0$
We need the projection of $\mathbf u$ onto $\mathbf v: \frac {u\cdot v}{v\cdot v} \mathbf v = \frac {4}{5} \mathbf v$
And the projection of $\mathbf u$ onto $\mathbf w: \frac {u\cdot w}{w\cdot w} \mathbf w = \frac {3}{5} \mathbf w$
And finally the magnitudes of $\bf {u,v, w}$ are all the same.  So, magnitude of these projections and the magnitude of u suggest the required $3:4:5$ ratio.


What's the best way to add a title to a grid/row in MDL

Question: I'm wondering what the recommended way is to add title to a row in material design lite. Below I have a row (ie: a grid) with two columns in it. Suppose I want to add a title/heading to it. When you run the below code, you will see that the title is hugging the left of the document (and doesn't have the same indentation level as the content).

<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

My Title

    Content 1

    Content 2

I could easily add some CSS to add some padding/margin to left of the
 but this feels a little hacky to me and doesn't feel like I'm using MDL properly if I were to do that.
I also tried moving the
 inside the row/grid div, but this causes things to become unaligned...

<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

My Title

    Content 1

    Content 2

The only way I can think of is by wrapping the
 in its own mdl-grid. This works but it adds unwanted padding above and below the title (due to it being in a grid).

<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

My Title

    Content 1

    Content 2

Is there anyway to simply add a title to a row using mdl?
Answer: Like that ?:

<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

My Title

    Content 1

    Content 2

I change first mdl-grid to mdl-layout__title
Comment: [Here](https://getmdl.io/components/index.html#layout-section/grid) - All grid possible ;)
Comment: Ah, I didn't know about `mdl-layout__title`, this seems to be exactly what I'm after. Thank you :)


Save large result set to multiple XML files

Question: I have a stored procedure that returns a large result set (nearly 20 million records). I need to save this result to multiple XML files. I am currently using ADO.Net to fill a dataset, but it quickly throws System.OutOfMemoryException. What other methods that I can use to accomplish this?
Comment: use an xml library that can stream. e.g. spit out xml without needing the entire data structure to be in memory/available. read a record, spit out an xml of that record, repeat.
Comment: Rather than filling a `DataSet`,  can you get an appropriate [`DataReader`](https://msdn.microsoft.com/en-us/library/haa3afyz.aspx) and stream from that to a file using an `XmlWriter`?
Comment: I would use sqlcmd.exe that comes with SQL Server : https://msdn.microsoft.com/en-us/library/ms162773.aspx.  20M is not a very large output from SQL and can be very quick or can take up to an hour depending on the size of the SQL database and how the data is stored.  When processing the command through c# can increase processing time 10x.I don't know how long your query takes, but if it is a long time I would recommend sqlcmd.exe.I have an application that was done in a c# form and the application froze.I ended up creating a backgroundworker that spawn a process calling sqlcmd.exe.  Have code.
Comment: Do I understand this correctly: Your SP returns millions of rows. You want to write the result in many separate XML files? Correct? What is the grouping decision? How are the files separated (kind of *one per customer*...)?
Comment: @TL, is there a decent criterium to separate your groups? I just imaging something like *per month* or *per customer* or *per product* or similar... In this case you might add an indexed column with your group distinguisher and load the data group by group? The simplest was a running number and load ranges... In any case you should not do  a *load all and prepare the XML files* approach... You might use a table valued function better than a stored procedure, that depends... From SS2012 you might read about `OFFSET FETCH`
Comment: @Marc: I'm not quite following your idea. Do you have an example? I'm trying "For XML PATH" right now and it puts the result to a big huge XML. I'm looking for a way to split this to multiple XML records which I can write to XML files.
Comment: My SQL query takes around 15 minutes. Follow this post http://stackoverflow.com/questions/13982871/tsql-one-row-per-element-with-for-xml, I am able to break these records to a few hundred records of XML which I can write to XML files. However, when calling the stored procedure from c#, I still get timeout exception even though I set connection timeout = 60000.
Comment: Thanks @Shnugo. The data is separated by Vendor/Customer as you said. I was doing the SQL For XML PATH to get a list of about 100 XML rows. One per Vendor/Customer. Even so, I still get OutOfMemoryException when I try to retrieve the XML data to write to a file. I think I will try option /3Gb next.
Answer: Assuming you are using SQL Server - you can use paging in your stored procedure. ROW_NUMBER is an option. SQL Server 2012 and above support OFFSET and FETCH.
Also, how many DataTables are you filling? There are row limits for DataTables.

The maximum number of rows that a DataTable can store is 16,777,216

https://msdn.microsoft.com/en-us/library/system.data.datatable.aspx
Answer: Are you using sql server ?
in this case there is a sql instruction to automatically convert the result of a query into a xml structure, you would then get it as a string in the application.
Options :

you split the string into several ones and save them to files (in the app)
modify PS to split result into several xml objects then get them as different strings / row (1 row => 1 object) and save each of them into a file.
write a new PS that calls the original PS, split result into X xml objects, then returns X xml strings that you just have to save in the application

Not using sql server ?
do the XML formatting in the PS or write a new one that does it
Anyway, if think it will be easier to do the xml formatting server side


how to assign variable in shell script

Question: I have below shell script code which is working fine.
#!/bin/sh

run() {
  cd /tmp/in/current
  java \
    -Dlog4j.configurationFile=/tmp/in/logging/log4j2_Importer.xml \
    -Djava.security.egd=file:///dev/urandom \
    -classpath /tmp/in/runner/lib/*:/tmp/in/lib/* \
    baag.runner.Application \
    --config /tmp/in/config/import.dev.properties.TODO \
    --workflow import \
    --inputDir "$1"
}

dev_path="/data/etl-dev/in/eurex"
simu_path="/data/etl-simu/in/eurex"

mode=$1

case "$mode" in
    "$dev_path" | "$simu_path" )
        run "$mode"
        ;;
    *)  echo "error: invalid mode" >&2
        exit 1
        ;;
esac

But currently i can run this code only on dev database as you can see in run function script the import.dev.properties.TODO is set as dev. I want to make this flexible such that if the path is "/tmp/in/simu" for simu_path variable then the properties should be import.simu.properties.TODO and for dev_path it should be import.dev.properties.TODO so that it will run on the respective database.
I am not sure if its possible to set parametarized variable here. For example something like this import.${varaible_here_dev_or_simu}.properties.TODO
I want to keep the dev_path and simu_path as it is as it can be changed
 as i am passing this in argument
Comment: It would make your `run` function a lot easier to read if you put each statement on a separate line.
Comment: `import.$(basename "$1").properties.TODO`?
Comment: @TomFenech sure i did this..@kamil i will try with import.$(basename "$1").properties.TODO
Comment: If it's one long command, don't forget to escape the newlines with `\ ` (I edited to do that)
Answer: Change import.dev.properties.TODO to import."$2".properties.TODO in run function. And use it like this.
run "$mode" "$whatever_you_name_it"

And we could ref this a bit
#!/bin/sh

path="${1:-/tmp/in}" # set /tmp/in as default path
mode="${2:-dev}"     # set dev as default mode
# or switch them if mode needs to be changed more recent
#path="${2:-/tmp/in}"
#mode="${1:-dev}"

run() {
    cd "$path"/current
    java -classpath "$path"/runner/lib/*:"$path"/lib/* baag.runner.Application \
         -Dlog4j.configurationFile="$path"/logging/log4j2_Importer.xml \
         --config "$path"/config/import.$1.properties.TODO" \
         -Djava.security.egd=file:///dev/urandom \
         --inputDir "$path/$1" \
         --workflow import
}

case "$mode" in
    "dev|simu") run "$mode" ;;
    *         ) echo "error: invalid mode" >&2; exit 1;;
esac

Comment: Whatever you want in place of `$2` in `import."$2".properties.TODO`
Comment: i dont understand "$whatever_you_name_it" what should i put here ...can you please explain ?
Comment: i think in this case should i use if condition instead of case beacause i am putting case condition togethere "$dev_path" | "$simu_path" so not understood
Comment: i think this syntax needs to changed in case condition dev|simu ? and also what argument should i pass while running the script ? previous i was running like  like ./script.sh "/tmp/in" and the main problem is i dont want to change dev_path or simu path as this path i am pasiing in argument while running and it can be little bit different
Comment: i have updated my answer ..as i said what if my dev_path and simu_path are like this then i think this will not work..
Comment: sorry its not working...one question can we just simply put simu or dev wherever in mode and pass it the same during running the script..for example ./script.sh "dev" or ./script.sh "simu"   then it will put the dev or simu variable value wherever necessary in script ?  because right now my dev_path and simu_path are not fixed
Answer: As far as I know, bash unfortunately does not support constructs like associative arrays, which could be a possible solution, prior version 4.
If the paths for the environments all look like the same, you could write it like this.
#!/bin/sh

base_path="/tmp/in"

dev_env="dev"
simu_env="simu"

run() {
cd /tmp/in/current; java -Dlog4j.configurationFile=/tmp/in/logging/log4j2_Importer.xml -Djava.security.egd=file:///dev/urandom -classpath /tmp/in/runner/lib/*:/tmp/in/lib/* baag.runner.Application --config /tmp/in/config/import.$1.properties.TODO --workflow import --inputDir "$base_path/$1"
}

mode=$1

case "$mode" in
    "$dev_env" | "$simu_env" )
        run "$mode"
        ;;
    *)  echo "error: invalid mode" >&2
        exit 1
        ;;
esac

Note: In this implementation you would have to pass dev or simu to the script instead of the whole path. If you need to pass the complete path you have to change the "$dev_env" | "$simu_env" ) to "$base_path/$dev_env" | "$base_path/$simu_env" )
UPDATE
Assuming the path structure and the environments are fixed, you can extract the environment with a simple regex and pass it to the function as the seconds parameter, like so:
#!/bin/sh

dev_path="/data/etl-dev/in/eurex"
simu_path="/data/etl-simu/in/eurex"
prod_path="/data/etl-prod/in/eurex"

environments="(dev|simu|prod)"

run() {
    cd /tmp/in/current; java -Dlog4j.configurationFile=/tmp/in/logging/log4j2_Importer.xml -Djava.security.egd=file:///dev/urandom -classpath /tmp/in/runner/lib/*:/tmp/in/lib/* baag.runner.Application --config /tmp/in/config/import.$2.properties.TODO --workflow import --inputDir "$1"
}

mode=$1

case "$mode" in
    "$dev_path" | "$simu_path" )
        environment=$(echo $mode | sed -E "s/.*${environments}.*/\\1/")
        run "$mode" $environment
        ;;
    *)  echo "error: invalid mode" >&2
        exit 1
        ;;
esac

Comment: I updated my post. Simply spoken, you can extract the environment with a line like this: `environment=$(echo $mode | sed -E "s/.*(dev|simu).*/\\1/")`
Comment: the main problem is i dont want to change dev_path or simu path as this path i am pasiing in argument while running and it can be little bit different.. i have mentioned this in question
Comment: Okay understood. Another option would be to put create two arrays. One with the paths and a second with the corresponding environments. You would need a function to determine the index in the paths array and use it to get the correct value from the environments array. Seems a bit ugly but would work.
Comment: can we just simply put simu or dev wherever in mode and pass it the same during running the script..for example ./script.sh "dev" or ./script.sh "simu" then it will put the dev or simu variable value wherever necessary in script ? because right now my dev_path and simu_path are not fixed
Comment: As long as there is a specific naming scheme in your paths, you could extract the value. Otherwise you need to bring the path and environment together somehow.
Comment: yes there is specific naming scheme in the path ...for example /data/etl-dev/in/eurex  where i am reading the file and import.dev.properties.TODO where database properties are set in both place you can see dev keyword is present and same for simu...so now we need to make this flexible for identification
Comment: Great, then I would probably simply strip the prefix `/data/etl-` and suffix `/in/eurex` from the path, or, if the set of environments are fixed a simple regex to extract `(dev|simu)` from the path.
Comment: this works fine as expected :) just small updated if i need to check for simu and prod then i will change the dev_path to prod_path="/data/etl-prod/in/eurex"
but in this case what change i neeed to do in environment=$(echo $mode | sed -E "s/.*(dev|simu).*/\\1/")  ?
Comment: You would just have to add the new environment within the brackets. Like so: `(dev|simu|prod)`. Or you define this part as an own variable, as shown above in my post. I updated the post, so it contains the code. Just make sure, the path is correct.

how to assign variable in shell script


Closed form Shift

Question: I am trying to turn a generating function to a closed form for $a_n$. I computed the first part of the closed form to be 5 choose n. However, the whole sequence needs to be shifted three spaces to the right so the first three terms are 0, 0, 0 and then 5 choose n begins.
For generating functions I know this is represented by x^3. How would you represent a shift all in terms of n?
Answer: Assuming your first term is when $n=0$, one possible way would be to replace $\binom{5}{n}$ with
$$\binom{5}{8-n}$$
which would equal zero for $n=0,1,2$; after that, when $n=3$ you'd have $\binom{5}{5} = \binom{5}{0}$, when $n=4$ you'd have $\binom{5}{4} = \binom{5}{1}$, etc.
Note that this was obtained by simply replacing $n$ with $n-3$, the standard technique to shift right by $3$ units; however that would initially yield $\binom{5}{n-3}$, so it was rewritten as the above to avoid having a lower index that was negative.
Addendum: extending to multiset coefficients can be done in a similar fashion.
$$\left( \kern-.3em \binom{5}{n-3} \kern-.3em \right) = \left( \kern-.3em \binom{n-2}{4} \kern-.3em \right)$$
Personally, though, I dislike having even the upper index being negative, so I would use
$$\binom{n+1}{4}$$
instead.

Closed form Shift


Fatal Error with Smarty - Unknown tag 'math'

Question: I am using PHP 8 and Smarty 4.0.0 version.
I have used math equation in my .tpl file.

{assign var=total value=0}
{section name=i start=0 loop=$serial_list|@count}
{math assign="total" equation="a" a=$serial_list|@count}

{$smarty.section.i.index+1}
{$serial_list[i].serial_no}
{$serial_list[i].prod_ord_no}
{$serial_list[i].mat_code}
{$serial_list[i].batch_no}
{$serial_list[i].gp_batch_no}
{$serial_list[i].mat_size}
 {$serial_list[i].mat_desc}
 {$serial_list[i].insp_lot_no}
 {$serial_list[i].mfg_date}
 {$serial_list[i].exp_date}

{/section}

But smarty errors:

>Fatal error: Uncaught --> Smarty Compiler: Syntax error in template >"file:C:\xampp8\htdocs\test\smarty\templates\reports\get_gp_data_from_sap.tpl" on line 110 "{math >equation="x + y" x='5' y='5'}" unknown tag 'math' C:\xampp8\htdocs\test\smarty\libs\sysplugins\smarty_internal_templatecompilerbase.php on line 110

How can I solve this?
Answer: Check file exists:
/smarty4/plugins/function.math.php


Jquery Select all things in an element with a certain name and replace

Question: Currently I have a table form I am using for submit.  This is a small excerpt from the chunk of code I am working with.

    <input name="recipe_ingredients[ing][1][ri_id]" data-thmr="thmr_141" type="hidden">

      Quantity
      <input class="form-item-recipe-ingredients-quantity form-text" id="edit-recipe-ingredients-ing-1-quantity" name="recipe_ingredients[ing][1][quantity]" value="" size="8" maxlength="8" data-thmr="thmr_142" type="text">

      Unit
      <select class="form-item-recipe-ingredients-unit-key form-select" id="edit-recipe-ingredients-ing-1-unit-key" name="recipe_ingredients[ing][1][unit_key]" data-thmr="thmr_145">

Now the problem is, each row has a unique 1, 2, 3, 4, 5 identifier in the name of certain attributes. When clicking a button, I want it to add the next row, which would need to change a name like
edit-recipe-ingredients-ing-1-unit-key

to
edit-recipe-ingredients-ing-2-unit-key

Is there a way that I can select and change all attributes in an element that match a string and replace each of those occurrences with my new names?   I plan to add new rows by using the jquery clone command.
Thank you for any help!
Comment: a JSfiddle displaying what you have so far would aid in answering this question
Comment: This will help you http://stackoverflow.com/questions/3598042/how-can-i-replace-a-regex-substring-match-in-javascript
Answer: You could clone your row, then change it inner HTML with RegExp.
But in fact you should have some kind of template here. Please, consider using Handlebars, or something like this.


How to rigorously show that the maximum variance of an hermitian matrix is $\left( \frac{h_{max}-h_{min}}{2} \right) ^2$?

Question: Suppose we have an hermitian matrix $H$ with eigenvalues $h_i$, and I want to get the minimum value of its variance, i.e. $\vec{v}^{\dagger}H^2\vec{v}-\left( \vec{v}^{\dagger}H\vec{v} \right) ^2$. How can we rigorously show this?
I tried Lagrange's multiplier method which I think nearly succeed. By spectral decomposition, we can write $H$ as $H=\sum_i\lambda_i|i\rangle\langle i|$(let me use $|i\rangle$ to stand for column vectors while $\langle i|\equiv|i\rangle^\dagger$). Then the problem changes into minimize $$\sum_i{{h_i}^2}\langle v|i\rangle \langle i|v\rangle -\left( \sum_i{h_i}\langle v|i\rangle \langle i|v\rangle \right) ^2.$$
over unit vectors $|v\rangle$.
By replace $\langle v|i\rangle \langle i|v\rangle $ with $p_i$, we finally state the problem as
$$
\underset{p_i}{minimize}\sum_i{{h_i}^2}p_i-\left( \sum_i{h_i}p_i \right) ^2
\\
s.t. \sum_i{p_i=1}
$$
Now we can start Lagrange's multiplier method. By introduce $\lambda$, we have the Lagrangian is $\sum_i{{h_i}^2}p_i-\left( \sum_i{h_i}p_i \right) ^2+\lambda \left( \sum_i{p_i}-1 \right) $, by derivative w.r.t. $p_i$ we have the linear equation:
$$
{h_k}^2-2\left( \sum_i{h_ip_i} \right) h_k=\lambda ,\forall k
\\
\sum_i{p_i}=1
$$
We then solve those equations and maybe it might have some easier results by noticing that $\lambda$ only has one value which does not change with different $h_k$.
For example, if we have $p_1$ to $p_3$, we can solve this by writing it in matrix form:
$$
\left( \begin{matrix}
 1&  1&  1&  0\\
 2h_1h_1&  2h_2h_1&  2h_3h_1&  1\\
 2h_1h_2&  2h_2h_2&  2h_2h_3&  1\\
 2h_1h_3&  2h_2h_3&  2h_3h_3&  1\\
\end{matrix} \right) \left( \begin{array}{c}
 p_1\\
 p_2\\
 p_3\\
 \lambda\\
\end{array} \right) =\left( \begin{array}{c}
 1\\
 {h_1}^2\\
 {h_2}^2\\
 {h_3}^2\\
\end{array} \right)
$$
Is there some easier way to solve it? I can't directly see the answer and using Gaussian elimination seems too complicated for more variables.
Answer: We don't need to solve the linear equations totally but do mind one important truth: $\lambda$ only has one value while we have several restrictions. Keep this in mind and mind that ${h_k}^2-2\left( \sum_i{h_ip_i} \right) h_k=\lambda $ is parabola w.r.t. $h_i$, hence we can only allow two $p_i\neq0$, or only one. Then it's easy to show that the optimal case is when $p_{max}=p_{min}=\frac{1}{2}$.


Third order Taylor polynomial of $f:(0, \infty) \times \mathbb{R} \to \mathbb{R}$ given by $f(x,y) = x^y$

Question: Let $f:(0, \infty) \times \mathbb{R} \to \mathbb{R}$ be given by $f(x,y) = x^y$.
How can one determine the Taylor polynomial of the third order of the function $f(x,y)$ in the points $(1,0)$?
I have
$$f_x = yx^{y-1}$$
$$f_{xx} = (y-1)yx^{y-2}$$
$$f_{xxx} = (y-2)(y-1)yx^{y-3}$$
$$f_y = x^y \ln(x)$$
$$f_{yy} = x^y\ln^2(x)$$
$$f_{yyy} = x^y\ln^3(x)$$
Then we do
$$f(1,0) = 1^0 = 1$$
$$f_x(1,0) = 0\cdot 1^{0-1}0 $$
$$f_{xx}(1,0) = (0-1)\cdot0\cdot1^{0-2} = 0$$
$$f_{xxx}(1,0) = (0-2)\cdot(0-1)\cdot0\cdot1^{0-3} = 0$$
$$f_y(1,0) = 1^0\cdot \ln(1) = 0$$
$$f_{yy}(1,0) = 1^0 \cdot \ln^2(1) = 0$$
$$f_{yyy}(1,0)= 1^0 \cdot \ln^3(1) = 0$$
Since we have only zeros expect for $f(1,0)$, can I just say that
$$T_{(1,0),3}(x,y) = 1$$
or is that wrong?
Comment: I made a mistake ! I did it at $(0,1)$ !
Answer: Since we want the third order Taylor polynomial of $f(x,y):=x^y$ at the point $(1,0)$ we consider the auxiliary function
$$g(t):=f\bigl(1+t(x-1),t y\bigr)$$ and compute its third order Taylor polynomial with respect to $t$ at $t=0$. This gives
$$T_0^3g(t)=g(0)+ g'(0) t +{g''(0)\over2} t^2+{g'''(0)\over6}t^3\ .\tag{1}$$
Wecompute
$$g(0)=1,\quad g'(0)=0,\quad g''(0)=2(x-1)y,\quad g'''(0)=-3(x-1)^2 y\ .$$ Putting $t=1$ at the end in $(1)$ gives all terms of total degree $\leq3$ in $(x-1)$ and $y$, and leads to
$$T_{(1,0)}^3f(x,y)=1+(x-1)y-{1\over2}(x-1)^2 y\ .$$
When $x=1.1$ and $y=-0.1$ we obtain $0.9905$, while $1.1^{-0.1}=0.9905142582$.
Answer: I think that you forgot to take into account the cross derivatives.
In my opinion, it should be something like
$$x+x \log (x)(y-1)+ \frac{1}{2}x \log ^2(x)(y-1)^2 +\frac{1}{6} x\log ^3(x)(y-1)^3
   +\cdots$$
Checking with $x=0.1$ and $y=0.9$, we get $0.125880$ while the exact value should be $0.125893$.
Edit
As @Christian Blatter pointed out, I misread the point around which has to be done the expansion and what I wrote was for $(0,1)$. Doing it around $(1,0)$ it becomes
$$1+(x-1) y+(x-1)^2
   \left(-\frac{y}{2}+\frac{y^2}{2}\right)+(x-1)^3
   \left(\frac{y}{3}-\frac{y^2}{2}+\frac{y^3}{6}\right)+\cdots $$ A small grid of values (all miising values are strictly equal to $1$)
$$\left(
\begin{array}{cccc}
x & y & \text{approximation} & \text{exact} \\
 0.8 & -0.2 & 1.0455040 & 1.0456396 \\
 0.8 & -0.1 & 1.0225080 & 1.0225652 \\
 0.8 & +0.1 & 0.9779720 & 0.9779328 \\
 0.8 & +0.2 & 0.9564160 & 0.9563525 \\
 0.9 & -0.2 & 1.0212880 & 1.0212957 \\
 0.9 & -0.1 & 1.0105885 & 1.0105918 \\
 0.9 & +0.1 & 0.9895215 & 0.9895193 \\
 0.9 & +0.2 & 0.9791520 & 0.9791484 \\
 1.1 & -0.2 & 0.9811120 & 0.9811185 \\
 1.1 & -0.1 & 0.9905115 & 0.9905143 \\
 1.1 & +0.1 & 1.0095785 & 1.0095766 \\
 1.1 & +0.2 & 1.0192480 & 1.0192449 \\
 1.2 & -0.2 & 0.9640960 & 0.9641925 \\
 1.2 & -0.1 & 0.9818920 & 0.9819330 \\
 1.2 & +0.1 & 1.0184280 & 1.0183994 \\
 1.2 & +0.2 & 1.0371840 & 1.0371373
\end{array}
\right)$$
Comment: @ChristianBlatter. I obviously misread the point !


ASP.NET dropdown list value name change

Question: Hello I have this code for user role section but I wanted to change display names on role.

    @Html.LabelFor(m => m.Roles, new { @class = "col-md-2 control-label" })

        @Html.DropDownList("ObjList", (IEnumerable<SelectListItem>)ViewBag.rolelist, new { id = "ddlLocations", @class = "form-control" })

So how can I show value of role 1 as ADMIN,
                           role2 as CLIENT
Answer: You should fill the ViewBag with SelectListItem in your controller like this :
   public ActionResult Index()
   {
       var ObjList = new List<SelectListItem>()
       {
           new SelectListItem { Text = "ADMIN", Value = "1" },
           new SelectListItem { Text = "CLIENT", Value = "2" },
       };

       ViewBag.rolelist= ObjList;

       return View();
    }

In View :
@Html.DropDownList("ObjList", (IEnumerable<SelectListItem>)ViewBag.rolelist, new { id = "ddlLocations", @class = "form-control" })

ASP.NET dropdown list value name change


Maintaining Old Drupal Versions

Question: Is there a list of best practices (or anything on drupal.org) for maintaining Drupal versions after end-of-life, specifically, when upgrading isn't an option? The best solution, of course, is to upgrade, but some organizations do not have the resources to make that happen.
I'd like to know some good practices here, especially when it deals with financial or private data.
The Drupal LTS project looks to be dead. I do my best to monitor info problems through things like CVE, but those sources seem to only mention exploits on the currently maintained branches.
Comment: I just saw this [post](http://drupal.stackexchange.com/questions/2642/what-are-the-best-ways-strategies-to-maintain-drupal-sites-a-over-period-of-10-1) which has a good suggestion of freezing the site to static HTML. This is a good solution but in some cases I've come across I've see D5 sites that are actively being administered day-to-day.
Answer: I assume you're aware that Drupal 6 has been announced to be end of life as of Feb 24, 2016, as detailed in Drupal 6 end-of-life announcement. That mean that D6 will soon be considered as "old" also, right?
So looking at your question in this D6-context , I think "a" practise that may fit for D6 ("when upgrading isn't an option", as in your question) is to Buy Drupal 6 Long-Term Support (LTS) from one of the "official" vendors (up to you to decide if it is a 'good' or 'best' practise of course).
Moreover, as a variation of that "Drupal LTS project" that you mentioned, there now seems to be the D6LTS project.
For more details, refer to "What to do about Drupal 6 End of Life?". Some more details (from this link):

What, specifically, will happen after February 24th?

All D6 modules will be marked as "unsupported" on Drupal.org - which will mean the 'update' module will start telling you that ALL your modules are out-of-date.
Also, the status information that the 'update' module uses could go away at any time - so, you'll no longer be able to rely on that in general.
The Drupal security team will no longer be making Security Advisories (or coordinating security releases)
In general, most module maintainers will no longer pay attention to Drupal 6 issues and will stop making new releases.

What should people with Drupal 6 sites do?

Archive the site, or
Plan upgrade.
Buy Drupal 6 Long-Term Support (LTS) from one of the "official" vendors.

What makes the "official" vendors special (vs. any other vendor)?

Get confidential information from Drupal security team.
Agree to follow security team processes and release all security patches publicly.
Vetted by the Drupal security team.

How will the Drupal 6 LTS work?

Same process as security team - but work done by vendors rather than security team.
Will publish patches on the D6LTS project.
Likely, but not 100% decided:

Announce new patches on the D6LTS issue queue.
Make new Pressflow 6 releases with the Drupal core patches.

Can the community get this without working with a vendor?

Yes!
But each vendor only supporting those modules their customers depend on
Question: And what about security issues that hackers find first?

Maintaining Old Drupal Versions


Issue with saving edited notes in modal form

Question: I'm currently facing an issue with saving edited notes in a modal form on my website. I have a modal that allows users to edit their notes, but when they click "Save changes," the updated note is not being saved correctly. It saves it as null. the note is then empty the desired edits did not save in the DB
Here's the structure of my modal:

Edit Notes

                                                <button type="button" class="close" data-dismiss="modal">×
                                                </button>

            <form id="editNoteForm" action="#" method="POST" >
                @csrf
                @method('PUT')

                <textarea name="note_content" id="noteContent" cols="30" rows="5" class="form-control bg-transparent" title="Please edit your note" required> </textarea>
            </form>

                                         <form id="saveEditsForm"  action="#" method="POST">
                                            @method('PUT')
                                            @csrf

                                                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                                <button type="submit" class="btn btn-primary">Save changes</button>

                                            </form>

here is the code in my controller
   // the following function is to edit a note
     public function editNote($note_id) {
    $note = notes::find($note_id);
    return response()->json([
        'noteContent' => $note->note
    ]);
}

  public function editNoteForm($note_id)
{
   $note = notes::find($note_id);

if (!$note) {
    // Handle the case when the note is not found
    return redirect()->back()->with('error', 'Note not found!');
}

return view('modal') -> with ('note',$note);
}

 public function saveEdits(Request $request, $note_id)
 {
    $noteContent = $request->input('note_content');

$note = notes::find($note_id);

if (!$note) {
    return redirect()->back()->with('error', 'Note not found!');
  }

     $note->note = $noteContent;
$note->save();

return redirect()->back()->with('success', 'Note updated successfully.');

my route
Route::get('edit-note/{note_id}', [NotesController::class, 'editNoteForm'])->name('edit-note-form');

 Route::put('save-edits/{note_id}', [NotesController::class, 'saveEdits']) -> name('saveEdits');

Answer: It is happening because your 'note_content[]' field is not inside the 'saveEditsForm' form.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: you have this:
@foreach ($notes as $note)
    <input type="hidden" name="note_content[]" value="{{ $note->note }}">
@endforeach
<form id="saveEditsForm"  action="{{ route('saveEdits', ['note_id' => $note->note_id]) }}" method="POST">
    @method('PUT')
    @csrf

    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Save changes</button>

 </form>

But your note info it´s out of form and you have other form higher. I don´t understan very well why you ar using hidden input to update notes. if you want that user edit this notes, maybe you can use:
<form id="saveEditsForm"  action="{{ route('saveEdits', ['note_id' => $note->note_id]) }}" method="POST">
    @method('PUT')
    @csrf

    <textarea id="w3review" name="w3review" rows="4" cols="50">
       @foreach ($notes as $note)
         {{ $note->note }}"
       @endforeach
    </textarea>

    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Save changes</button>

 </form>

Comment: I add more code to give a better idea.
 the i have two form on the modal because editnoteform is to pull the existing not from the db and display it on the textarea so you can make an fix and then a second form called savededits form is to save the updated not to the db with the same id


C# Google Calendar API - Credentials/Microsoft Account

Question: Well, my problem is that I have to register the calendar in my personal google account which isn't a problem but...
When creating a new event, my personal e-mail will display there as an Organizer and will put the event in my personal calendar as well.
In the company, we use Microsoft 365 accounts which would be the best to use. I mean, is there a way to solve this?
The best way to solve this is that when I create the event, I give it a string (which is a microsoft email) and that should be the organizer (in spite of the fact that it's not a google account). The main problem is that I have to pre register the ClientID in the application to run the whole process. I use the following right now with google account:
<code>public static CalendarService getCalendarService
{
   get
   {
      var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret },
      new[] { CalendarService.Scope.Calendar }, "user", CancellationToken.None).Result;
      return new CalendarService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Deadline calendar" });
    }
}
</code>
Answer: The problem you have is that the owner of an event is the one who created it.  The one who created it is the currently authenticated user.  Basically what ever account you logged in with and consented to the access and ran your application from.
You would need to covert the Microsoft 365 email account to a google account, then login with that account, create events with that account and then it will be the owner.
Comment: if you use a service account then it will be the owner and the name will be even worse.    option teach them google calendar or stop using Google calendar.    Even if you patch the owner of the event their account still needs to be a Google account
Comment: Yeah, but the creator should always be different. So we're talking about basic secretary who doesn't even know what Google Calendar API is, so I'd need a simple method so everyone can be a creator which is given by a string in the code. I'm trying to do your published method (with P12 key - with service account) but the keyFilePath is a problem to find. I mean, I included the .p12 file in the project, the same folder as the class which calls it but still can't find the file. Tried almost every single type of method to determine the path, but still nothing. I use X509Certificate2
Comment: The context is the following. Someone creates a project whith a custom email (mostly company email) and the responsible person of the current project will be the event organizer.


Desabilitar scroll do mouse

Question: Meu código.
Css:
td div{
 width:100%;
 height: 40px;
 overflow: hidden;
 padding-top: 9px;
}
 td div:hover{
  overflow: auto;
}

Html:

<?php echo $objProg->getagen(); ?>

Ao por o mouse encima da td gostaria que a opção para rolar com o scroll do mouse não funcionasse, para conseguir somente rolar o texto ao clicar nas setas.
Answer: Utilizando jQuery você pode fazer isso de algumas formas. Pode simplesmente desabilitar o scroll como deseja, ou forçar o scroll a funcionar somente na div em questão.
Ficaria assim os exemplos:

$('#good').bind('mousewheel DOMMouseScroll', function(e) {
    var scrollTo = null;

    if (e.type == 'mousewheel') {
        scrollTo = (e.originalEvent.wheelDelta * -1);
    }
    else if (e.type == 'DOMMouseScroll') {
        scrollTo = 40 * e.originalEvent.detail;
    }

    if (scrollTo) {
        e.preventDefault();
        $(this).scrollTop(scrollTo + $(this).scrollTop());
    }
});

$('#bad').hover(function() {
    $(document).bind('mousewheel DOMMouseScroll',function(){
        stopWheel();
    });
}, function() {
    $(document).unbind('mousewheel DOMMouseScroll');
});

function stopWheel(e){
    if(!e){ /* IE7, IE8, Chrome, Safari */
        e = window.event;
    }
    if(e.preventDefault) { /* Chrome, Safari, Firefox */
        e.preventDefault();
    }
    e.returnValue = false; /* IE7, IE8 */
}
body { min-height: 1200px; padding: 30px; }
p { height: 500px; }
div#bad {
    position: absolute;
    top: 70px;
    left: 330px;
    height: 200px;
    width: 200px;
    background-color: lightgray;
    overflow: scroll;
}

div#good {
    position: absolute;
    top: 70px;
    left: 30px;
    height: 200px;
    width: 200px;
    background-color: gray;
    overflow: scroll;
}

Scroll to bottom of each div

Scroll somente na div

    End of Div

Remove Scroll jQuery

    End of Div

Demais formas, você pode olhar nesta pergunta que usei como referência.
Answer: Uma forma muito facil de fazer, sem precisar de muitas linhas e muito simples:
use: onwheel="return false;"
Jsfiddle: https://jsfiddle.net/rapa09/jtxf10qm/1/
Comment: Só pra constar, se interessar tem o "Fiddle" do próprio site, que é o ícone da folha com < > na barra de ferramentas da resposta (mas é perfeitamente normal usar o JS Fiddle também)
Comment: Eu utilizei o do site, mas se eu clicar fora sem querer ele não salva os codigos, então prefiro usar o jsfiddle. mas vlw pela dica.
Comment: Única coisa que eu não achei muito interessante é que quando o mouse esta encima da `div` o scroll da página em si não rola também.

Desabilitar scroll do mouse


How to stop masking on svg?

Question: Ok, I have an svg I created in illustrator and opened in an editor so I could get the path. I then applied a filter:

#center {
  justify-content: center;
  width: 400px;
  position: relative;
  overflow: visible;
}

#inner {
  width: 400px;
  transition-timing-function: ease-in-out;
  transition: transform 0.4s;
  -webkit-transition: transform 0.4s;
  -moz-transition: transform 0.4s;
  -o-transition: transform 0.4s;
  overflow: visible;
}

#center #svgContainer {
  perspective: 20px;
  overflow: visible;
}

  <svg>
    <defs>
      <filter id="Blur"><feGaussianBlur stdDeviation="19" /></filter>
      <g id="Img"><path class="cls-1" d="M9.5,204.08q26.14-10,51.48-22,24.65-11.67,48.32-25.21,11.83-6.78,23.39-14c8.05-5,20.78-11.32,17.8-23-1.5-5.85-6.76-8.72-11.92-10.78-4.25-1.7-8.54-3.3-12.84-4.86q-13.14-4.74-26.54-8.69A490.14,490.14,0,0,0,44.6,83.09a22.13,22.13,0,0,1-4.66-1.25l1.79.76A12.55,12.55,0,0,1,40.56,82c-.28-.16-1.46-1-.27-.11s.12,0-.12-.24c.84,1.15,1.06,188.8.131.52a5.28,5.28,0,0,1-.27-.53l.75,1.79a7.3,7.3,0,0,1-.37-1.29l.27,2a7.1,7.1,0,0,1,0-1.22l-.27,2a8.33,8.33,0,0,1,.54-2L40.69,85a14,14,0,0,1,1.05-1.85c.55-.87-.32.27-.4.48a4.14,4.14,0,0,1,.68-.79c.8-.89,1.65-1.75,2.52-2.57s1.79-1.57,2.71-2.33c.65-.53-1.6,1.2-.47.38l.6-.45c.51-.36,1-.72,1.54-1.07a76.74,76.74,0,0,1,12.77-6.67l-1.79.76c8.91-3.76,18.29-6.5,27-10.77A17.82,17.82,0,0,0,94,53.87a11.27,11.27,0,0,0,.09-11.74c-1.71-2.82-4.56-4.46-7.27-6.17-2.11-1.34-4.19-2.73-6.2-4.23-.38-.28-1-.89.53.42-.31-.27-.64-.52-1-.78q-.8-.66-1.56-1.35a37.89,37.89,0,0,1-2.89-2.92l-.53-.63c-.19-.22-1-1.21-.19-.2s0-.05-.14-.23-.39-.57-.58-.86a23.21,23.21,0,0,1-1.83-3.45l.76,1.8A23.43,23.43,0,0,1,71.7,17.8l.27,2a19.79,19.79,0,0,1,0-5.1l-.27,2a17.15,17.15,0,0,1,1-3.79L72,14.68a14,14,0,0,1,.79-1.6c.34-.58,1.61-2.22.06-.27A8.13,8.13,0,0,0,75,7.51a7.66,7.66,0,0,0-2.2-5.31A7.54,7.54,0,0,0,67.54,0c-1.86.08-4.09.67-5.3,2.19a25.09,25.09,0,0,0-4,6.7,23.1,23.1,0,0,0-1.35,6.15,25.58,25.58,0,0,0,1.34,11.07c2.89,8.33,9,14.38,16,19.43,1.63,1.18,3.32,2.28,5,18.104.22.168,1.58,1,2.36,1.48a3.78,3.78,0,0,0,.6.41c-.18,0-1.36-1.22-.69-.18.104.22.168.188.8.131.52.47-1.07-1.61-.49-.52l-.76-1.79a4.85,4.85,0,0,1,.31,1l-.27-2a4.39,4.39,0,0,1,0,1l.27-2a5.9,5.9,0,0,1-.23.92l.75-1.79c-.17.4-.44.75-.63,1.15.67-1.42.92-1.12.25-.47l-.55.49c1-.74,1.25-1,.78-.61s-.72.48-1.1.7a42.55,42.55,0,0,1-4.8,2.22l1.79-.76c-9.76,4.09-19.95,7.15-29.4,12a61.8,61.8,0,0,0-13.38,9.09,31.65,31.65,0,0,0-6.17,7.15,13.68,13.68,0,0,0-.73,13.18c2.76,5.73,9.35,7.41,15.05,8.38q9.11,1.55,18.14,3.46,18.06,3.83,35.78,9.1a380,380,0,0,1,39,13.54l-1.79-.75a24.46,24.46,0,0,1,3,1.59c.7.41-1.25-1.11-.7-.220.127.116.11.220.127.116.11.72-.66-.7-.56-.73a5,5,0,0,1,.46.89l-.76-1.8a6.36,6.36,0,0,1,.34,1.35l-.27-2a6.1,6.1,0,0,1,0,1.35l.27-2a8,8,0,0,1-.37,1.29l.76-1.79a11,11,0,0,1-.56,1.08c0,.06-.31.37-.3.44s1.09-1.29.62-.8c-.67.69-1.32,1.34-2,2-.95.83,1.34-1,.31-.24l-1.08.73-2.88,1.85q-5.36,3.4-10.77,6.73-10.92,6.71-22.1,13-22.23,12.53-45.34,23.42Q39.3,175.79,26,181.41l1.79-.76q-11.07,4.66-22.29,9A8.16,8.16,0,0,0,1,193.06a7.68,7.68,0,0,0-.76,5.78c1.16,3.56,5.31,6.74,9.23,5.24Z"/>
      </g>
    </defs>
    <use style="fill:pink;" filter="url(#Blur)" xlink:href="#Img"
      transform="translate(0,0)"/>
    <use style="fill:white;" xlink:href="#Img"/>
    </svg>

This is great, except even with overflow:visible and changing div sizes, I get a masked svg:

What is wrong here?
updated:
<svg svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -70 800 1081">

Comment: What is the result you're wanting? Looks like your SVG is missing a `viewBox` attribute and has no explicit width or height specified.

Can you post in the exact SVG code you get when you export from Illustrator?
Comment: @DonkeyShame great catch - see the edit above. Found the viewbox and tried making it bigger, solved the problem somewhat but you can still see cutoff on the gaussian blur. Why does upping the last 2 values not have any further effect?
Comment: You need to set the height and width of your filter too.
Answer: It looks like what's happening is that your SVG is falling out the bottom of its container.
You'll want to export your SVG in a way that ensures this doesn't happen. One way to tackle this is with the viewBox attribute (see here).

viewBox = {min-x} {min-y} {width} {height}

In my hastily-contructed example file below, you'll see that my SVG's viewBox attribute is set to "0 0 417 376". Its width and height are set to the same dimensions, respectively.
As to why tweaking the 3rd and 4th numbers isn't getting the result you want, well...

The 'viewBox' attribute specifies a rectangle in user space which should be mapped to the bounds of the viewport established by the given element.

Quoted from here
In other words, as I understand it, the viewport established by your given element is too small to accommodate the spread of the blur; no matter how large you make the viewBox, it's still mapping that rectangular space into the size constraints of the parent element.
Or, perhaps something else...?  Who knows.
At any rate, you'll want to accommodate that blur radius inside the SVG you export from Illustrator. To do that, place the guts of your graphic inside a rectangle that is large enough to encapsulate the graphic and its blur spread. Remove the stroke/fill of that encapsulating rectangle and group the whole mess together. Export that group as an SVG.
I don't use Illustrator any more but something like that should get you going. Illustrator may have options you can tweak with regard the viewBox attribute, so watch for that when you're exporting.
Good luck!
Pro-tip: It doesn't matter how large your graphic is since it's vector based. You could export it at could 100px by 100px and that would be fine. You could subsequently control its display size by setting its width and height explicitly (or by sizing the SVG with CSS, or whatever).
Some good stuff here:
Perplexed by SVG viewBox, width, height, etc

    <svg width="417" height="376" viewBox="0 0 417 376" fill="none" xmlns="http://www.w3.org/2000/svg">
      <g filter="url(#filter0_df)">
        <path d="M198.5 70C193.667 77.8333 193.4 89 205 101C216.6 113 224.5 116.5 223.5 122.5C222.5 128.5 169.148 137.338 156 164.5C150.675 175.5 309 198.947 291 217C273 235.053 215.166 273.072 126 305.5" stroke="white" stroke-width="20" stroke-linecap="round" />
      </g>
      <path d="M198.5 70C193.667 77.8333 193.4 89 205 101C216.6 113 224.5 116.5 223.5 122.5C222.5 128.5 169.148 137.338 156 164.5C150.675 175.5 309 198.947 291 217C273 235.053 215.166 273.072 126 305.5" stroke="white" stroke-width="20" stroke-linecap="round" />
      <defs>
        <filter id="filter0_df" x="67.9971" y="11.9986" width="282.433" height="351.504" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
          <feFlood flood-opacity="0" result="BackgroundImageFix" />
          <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" />
          <feOffset />
          <feGaussianBlur stdDeviation="24" />
          <feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.2 0" />
          <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow" />
          <feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow" result="shape" />
          <feGaussianBlur stdDeviation="8" result="effect2_foregroundBlur" />
        </filter>
      </defs>
    </svg>

How to stop masking on svg?


Haskell "copy constructor" invocation

Question: I have a situation where multiple keys can point to the exact same value. Since the key domain is quite small, I am using the associative lists [(key, value)].
Does inserting multiple elements with different keys but equal values force GHC in any way to create copies of the values in question?
Taking the immutability of Haskell variables into account, I do not think so, but I just want to be sure.
Comment: Can you clarify what you mean by point to? Do you have something like `a = 4; b = [(1,a),(2,a)]`?
Comment: Yes, exactly like that :) My worries are, that if the `a` variable is large (think 10 megabytes), having copies of it is just bad for morale
Comment: This might help: http://stackoverflow.com/questions/20857165/move-or-copy-in-haskell-vs-c
Comment: @DanielLovasko If `a` is not a value, but a function call (like `f 3`), I think GHC can create several copies of a return value: `[(1,f 3),(2,f 3)]` (and this depends on the optimization level of GHC)
Answer: Technically, it depends on the Haskell implementation: the Haskell report does not mandate a copy to be made, or to be avoided, it just mandates that the result is the right one -- performance issues aside.
That being said, you should not expect GHC to optimize this
let value1 = "hello" ++ "world"
    value2 = "hell" ++ "oworld"
in [(1, value1), (2, value2)]

into this
let value = "helloworld"
in [(1, value), (2, value)]

Just because two values are equal, it does not mean they will share the same memory area.
In the latter example the string value will not be copied when put twice into the list, since there's no need to: two pairs will be constructed with a field pointing to the same string. So, only a pointer will be copied.
Saving copies is also the reason why sometimes we do not write
foo (x, "hello") = (x, "hello")
foo (x, y)       = (x, "foo:" ++ y)

but instead prefer
foo p@(x, "hello") = p
foo (x, y)         = (x, "foo:" ++ y)

The latter will output the same "pointer" to the input pair, rather than constructing a new one with identical value. (I am not sure if GHC sometimes does this optimization on its own)
Answer: You are right,
but the convincing point may not be imutability but laziness. Indeed, if you were to "copy" the value then it "would have" to be evaluated[1]. But this would break haskell laziness.
Also, reasoning about "size" can be treaky in Haskell: is foldr (+) [1..1000] the size of an Int ? Or the size of the function closure ?

1) Stricly speaking, you could imagine copying the thunk but it would not really make sense.

Haskell "copy constructor" invocation


Porque pode estar causando erro na hora de comparar duas datas no php

Question: tenho a seguinte linha de codigo:
if($dataexpira < $dataLocal){ echo "Expirou data!";}

o Que nelas esta armazenado as seguintes strings:
if("04/02/2019 18:18:48" < "16/01/2019 18:18:48"){echo "Expirou data!"}

porem ele ao comparar dessa forma, ele entende como data Expirada, pois esta comparando se é maior o dia e " nao seu todo"...
como comparar seu todo...
Comment: Use a classe [`DateTime`](http://php.net/manual/pt_BR/class.datetime.php). Comparar *string* só vai funcionar se tiver no formato `Y-m-d H:i:s`
Comment: Desculpe minha pergunta, mas eu consigo utilizar essas strings para transformar em DateTime ?
Answer: Isto forma abaixo irá transformar sua string em um objeto de datas, e assim você fará as comparações com mais segurança, comparando representações numéricas como timestamp.
<?php
// Objeto que representa a data expira.
$DataExpira = new DateTime();
$DataExpira->setTimestamp(strtotime("2019-02-16 18:18:48"));
// Objeto que representa a data local.
$DataLocal = new DateTime();
$DataLocal->setTimestamp(strtotime("2019-02-16 18:18:48"));
// Saí apenas para teste.
print "1 :: dataexpira :: " . $DataLocal->getTimestamp();
print "
";
print "2 :: dataLocal :: " . $DataExpira->getTimestamp();
print "
";
// Teste de datas.
if ($DataExpira->getTimestamp() < $DataLocal->getTimestamp()) {
    echo "Expirou data!";
} else {
    echo "NÃO Expirou data!";
}
?>

Fazendo assim ficará melhor a sua representação de datas.
Comment: Perfeito amigo ... isso ajudou muito !!!! obrigado....
Comment: Se no final você vai comparar o *timestamp*, nem precisa usar a classe `DateTime`, a função `strtotime` já retorna o valor, basta usá-lo.
Answer: Você não precisa fazer tudo isso que foi apresentado na outra resposta. Se fosse para comparar os timestamps apenas nem precisaria utilizar a classe DateTime.
$expira = strtotime("2019-02-16 18:18:48");
$local = strtotime("2019-02-16 18:18:48");

if ($expira < $local) {
    ...
}

Mas veja que o formato da data mudou nesse caso, pois a função strtotime não reconhece o padrão que você possui.
Se deseja usar DateTime, como o formato "16/01/2019 18:18:48" não é um formato reconhecido internacionalmente, você precisa especificar como a classe DateTime irá processar o valor informado; faça isso com o método DateTime::createFromFormat:
$expira = DateTime::createFromFormat("d/m/Y H:i:s", "04/02/2019 18:18:48");
$local = DateTime::createFromFormat("d/m/Y H:i:s", "16/01/2019 18:18:48");

Perceba que definimos o formato como "d/m/Y H:i:s" para o PHP saber o que é cada número. Neste caso, o formato é <dia>/<mês>/<ano com 4 dígitos> <hora no formato 24h>/<minutos>/<segundos>. O método é estático e retorna uma nova instância de DateTime.
Como DateTime é nativo do PHP (e escrito em C), ela possui a sobrecarga de operadores implementada. Isto é, você pode comparar dois objetos DateTime com os operadores >, <, etc, normalmente. Portanto, para saber se $expira é menor que $local, basta fazer:
if ($expira < $local) {

}

Assim, ficando:
$expira = DateTime::createFromFormat("d/m/Y H:i:s", "04/02/2019 18:18:48");
$local = DateTime::createFromFormat("d/m/Y H:i:s", "16/01/2019 18:18:48");

if ($expira < $local) {
    ...
}


Connect to active directory over peered VPC

Question: I have a VPC(VPC1) where my main instances are running, and I have another one (VPC2)specifically for directory service (AD Connector) and a MS AD server running. I have created a VPC peering (which is Active) and all the route tables of these VPC's are updated to talk to the other VPC instances. But here are the issues now:

An instance created in VPC 1, configured with domain join option gets launched successfully, but not joined to the domain. I am not sure any logs I can find, IAM role for this instance is also integrated while launching.
From the AD server (located in VPC2), I tried pinging this VPC1 server by its private IP address, which fails.

Is there anything else I need to configure.? As per my understanding, VPC peering in active state with route tables should properly route the requests. Any help would be appreciated
Answer: Obviously we'll need to ensure PING works before troubleshooting AD join issues, so I'll only comment on that.

Add a Windows firewall rule or disable it (can also test this by pinging from another host within the same subnet)
Do the hosts have more than one network adapter e.g. Public IP and Private IP?  If so, the ICMP response traffic might be routing out the default gateway to the Internet, which will never find your other host's private IP
Be sure you have a network ACL (NACL) rule allowing ICMP responses
Be sure you have a rule on both Security Groups (the ones for the private IP on each instance) allowing ICMP both inbound and outbound
From one of these servers, tracert (tracert ) might tell you if it's routing incorrectly
Try adding a route to Windows to test the route theory
Use Wireshark and/or VPC Flow Logs to determine whether the PING destination is ever receiving the packet
If you have multiple subnets and route tables, make sure the subnets of your instances are associated with the route table(s) you're changing
Check the subnet masks in your route tables and subnet groups in/out rules being used (e.g. using a /24, but should be /16, or vice-versa)


Erro em readImage utilizando Imagick()

Question: Estou tentando converter um pdf em imagem utilizando a biblioteca Imagick da seguinte forma:
<?
header('Content-type: image/jpeg');
$imagick = new Imagick();
// O myfile se encontra na mesma pasta do arquivo que estou executando
$imagick->readImage('myfile.pdf');
$imagick->writeImages('myfile.jpg', false);

Estou tendo o seguinte erro:

Fatal error: Uncaught exception 'ImagickException' with message
  'Unable to read the file: myfile.pdf' in /Users/myuser/teste.php:11
  Stack trace:
  0 /Users/myuser/teste.php(11): Imagick->readimage('myfile.pdf')
  1 {main}   thrown in /Users/myuser/teste.php on line 11

O que poderia ser?
Answer: Tente com o diretório completo para a imagem:
$image->readImage($_SERVER['DOCUMENT_ROOT'] . '/dir_da_imagem/myfile.pdf');
$imagick->writeImages($_SERVER['DOCUMENT_ROOT'] . '/dir_da_imagem/myfile.jpg', false);

Onde dir_da_imagem é o diretório relativo de myfile.pdf.
Fora isso, verifique as permissões do myfile.pdf e se o arquivo não está corrompido.
Comment: Obrigado pela resposta, fiz as alterações acima, dei permissão 777 para o arquivo também para garantir, testei com is_readable() para ter certeza de que o arquivo pode ser lido mais ainda não funcionou.
Comment: Você tem o Ghostscript (http://www.ghostscript.com/) instalado? Isso pode ser uma causa também. Aparentemente, o imagick utiliza o gs para converter PDFs.
Comment: Instalei usando:

**brew install php56-imagick --with-ghostscript**

reiniciei o apache também mas nada.

Erro em readImage utilizando Imagick()


Multistep user registration using profile2

Question: How can we create a multistep user registration form in drupal 7 using profile2 module.
Answer: You can try Field group

Fieldgroup will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.

Available group types

Fieldsets
Horizontal tabs
Vertical tabs
Accordions  Divs
Multipage steps: Note: This is only client side.

And i found a nice tut here


MYSQL generate consecutive numbers from range

Question: My Table
classRoom
id  class   no_of_seats start_seat_no   end_seat_no
1   A1      3           105             107
2   A2      2           108             109
3   A3      2           110             111

i want to insert data in the table
seat_records
like this
id  class   seat_no
1   A1      105
2   A1      106
3   A1      107
4   A2      108
5   A2      109
6   A3      110
7   A3      111
8   A3      112

tried doing everything given in previous questions, but failed.
SELECT 'A1' class, 105 start_seat_no, 107 end_seat_no
    UNION ALL
    SELECT 'A2',108,109
From classRoom

Comment: What have you tried, This seems to be fairly simple if your columns are nullable
Answer: You need a source of integers to do a join.  If you have enough rows, you can use the same table and variables:
insert into seat_records(class, seat_no)
    select class, cr.start_seat_no + n.n - 1
    from ClassRoom cr join
         (select @rn := @rn + 1 as n
          from ClassRoom cross join
               (select @rn := 0) vars
         ) n
         on cr.start_seat_no + n.n - 1 <= cr.end_seat_no;

You should add the id itself as an auto-incrementing column.  That way, it will be set on input.  If you really want to set it on input, you can also use variables:
insert into seat_records(id, class, seat_no)
    select @id := @id + 1, class, cr.start_seat_no + n.n - 1
    from ClassRoom cr join
         (select @rn := @rn + 1 as n
          from ClassRoom cross join
               (select @rn := 0) vars
         ) n
         on cr.start_seat_no + n.n - 1 <= cr.end_seat_no cross join
         (select @id := 0) vars

Comment: Works very well thanks!  But fails to where start_seat_no is varchar. How can this be sorted out.
Comment: If `end_seat_no-start_seat_no` is greater than the number of rows in `ClassRoom` will the inner `select @rn ...` generate enough numbers? (it seems to me it will not...)
Comment: I suppose you could add more cross joins against `ClassRoom` or some other table, but I wonder if you know a better way.


Fazer um Locate de um ClientDataSet é muito custoso?

Question: Fazer um locate de um dataset ligado ao banco, certamente é bastante custoso. Mas fazer um locate num dataset com dados apenas em memória, é uma boa prática? Ou seria melhor criar um array?
Grato.
Comment: Já cogitou a possibilidade de utilizar um `TDictionary` ?
Comment: @VictorZanella  Não, podes dar mais detalhes sobre o funcionamento de `TDictionary`?
Comment: só para confirmar, qual versão do Delphi você está utilizando ?
Comment: @VictorZanella Delphi XE7
Answer: Segue um exemplo simples de utilização do Dictionary.
unit Unit2;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
  System.Generics.Collections, Vcl.StdCtrls;

type

  TPessoa = class
    id: integer;
    nome: string;
    sobrenome: string;
    idade: integer;
    sexo: string;
  end;

  TListaPessoa = TObjectList<TPessoa>;

  TForm2 = class(TForm)
    btnBuscarPessoa: TButton;
    procedure FormCreate(Sender: TObject);
    procedure btnBuscarPessoaClick(Sender: TObject);

  private
    FListaPessoa: TListaPessoa;
    FDicionarioPessoa: TDictionary<integer, TPessoa>;

    procedure AdicionarPessoas;
    procedure AlimentarDicionario;

  end;

var
  Form2: TForm2;

implementation

uses
  StrUtils;

{$R *.dfm}

procedure TForm2.AdicionarPessoas;
var
  i: integer;
begin

  for i := 1 to 10000 do
  begin

    FListaPessoa.Add(TPessoa.Create);
    FListaPessoa.Last.id        := i;
    FListaPessoa.Last.nome      := 'Nome' + IntToStr(Random(1000));
    FListaPessoa.Last.sobrenome := 'Sobrenome' + IntToStr(Random(1000));
    FListaPessoa.Last.idade     := Random(80);
    FListaPessoa.Last.sexo      := IfThen(odd(FListaPessoa.Last.id + FListaPessoa.Last.idade), 'M', 'F');

  end;

end;

procedure TForm2.AlimentarDicionario;
var
  FPessoa: TPessoa;
begin
  for FPessoa in FListaPessoa do
    if (not(FDicionarioPessoa.ContainsKey(FPessoa.id))) then
      FDicionarioPessoa.Add(FPessoa.id, FPessoa);
end;

procedure TForm2.FormCreate(
  Sender:
  TObject);
begin
  FListaPessoa      := TListaPessoa.Create;
  FDicionarioPessoa := TDictionary<integer, TPessoa>.Create;

  AdicionarPessoas;
  AlimentarDicionario;

end;

procedure TForm2.btnBuscarPessoaClick(Sender: TObject);
var
  identificador: integer;
begin

  identificador := Random(10000);

  ShowMessage(
    'A pessoca com o id ' + IntToStr(identificador) + ' é ' + FDicionarioPessoa.Items[identificador].nome + ' ' + FDicionarioPessoa.Items[identificador].sobrenome +
    ' tem ' + IntToStr(FDicionarioPessoa.Items[identificador].idade) + ' anos de idade e é do sexo ' +
    IfThen(FDicionarioPessoa.Items[identificador].sexo = 'M', 'masculino', 'feminino')

    );

end;

end.

Note que os métodos legais do Dictionary são os ContainsKey ou ContainsValue.
Obs.: No teste que fiz, coloquei 7000000 registros, e a busca é instantânea.
Obs2.:A ordenação dos dados também é rápida com Dicionario de dados.
Comment: Muito obrigado e parabéns pelo exemplo, bem detalhado e prático! @Victor Zanella
Comment: aaah, esqueci de avisar, mas as classes poderiam ser interfaces. Nesse caso eu esqueci de liberar os objetos criados.
Answer:
É mais custoso em processamento. Principalmente porque a cada nova execução de locate, você teria que posicionar o registro no início do DataSet.
Uma opção melhor seria você utilizar o FindKey([]).
Para utilizá-lo, você precisa apenas configurar e utilizar um índice no DataSet e utilizar os campos no FindKey.
Ex:
cdsDataSet.IndexDefs.add('IDX_NOME','CAMPO1;CAMPO2;CAMPO3',[]);
cdsDataSet.IndexName := 'IDX_NOME';

// Observe que você não precisa passar todos os campos do índice
// Mas precisa seguir sempre a mesma ordem.

if cdsDataSet.FindKey([_valorCampo1, _valorCampo2]) then
  showMessage('Achei')
else
  ShowMessage('não achei');


How to reference XML root node generically

Question: I have some XML that looks like this;
<Root attr1="ABC">
    <Element1>
        <Element2>
             <Element3 />
        </Element2>
        <Element2>
             <Element3 />
        </Element2>
    <Element1>
</Root>

I have some XSLT that processes this, and for one reason or another it references the Root node as 'Root' (without quotes).
I am now in a position where I will have some identically structured XML, except the Root node is called  for example. I don't want two versions of my XSLT, so can I reference the root node in a more generic fashion.
As an example of what I mean...
<xsl:when  test="/Root/@attr1 = 'ABC'">

I need this to also work for
<xsl:when  test="/NewRoot/@attr1 = 'ABC'">

I have noted in my reading on the subject that care needs to be taken to ensure the reference is the root node, and not the Document element, that latter I assume is this part of the XML
<?xml version="1.0" encoding="UTF-8"?>

Any help is as ever appreciated.
Thanks
Answer:
can I reference the root node in a more generic fashion ?

Just use:
/*/@attr1 = 'ABC'

this produces true() exactly when the top element (regardless of its name) of the XML document has an attribute named attr1, whose string value is the string: "ABC".
Here we are using the fact that a well-formed XML document must have exactly one top element -- therefore we don't need to write: /*[1]
Answer: I would suggest to use e.g.
<xsl:template match="/Root | /NewRoot">
  <xsl:if test="@attr1 = 'ABC'">...</xsl:if>
</xsl:template>

or perhaps it might even be better to put the attribute check into a template match pattern as well e.g.
    <xsl:template match="/Root | /NewRoot">
      <xsl:apply-templates select="@*"/>
    </xsl:template>

<xsl:template match="/Root/@attr1[. = 'ABC'] | /NewRoot/@attr1[. = 'ABC']">

</xsl:template>

If you really need to use an xsl:when test with a full path then use test="/Root/@attr1 = 'ABC' or /NewRoot/@attr1 = 'ABC'".
Comment: Yep, this did it. Thanks
I take it then there isn't a 'generic' way to refer to the root node?
Comment: `name(/*)` will return you the name of the root node, but unless you are using XSLT 2.0 or above, it's non-trivial to use that in an XPath expression.


Pthread_join não está funcionando como deveria para popular um array em C

Question: Eu tenho o seguinte código:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <locale.h>
#include <time.h>

//declaração das variáveis globais
float *x;
float *y;
float *z;
pthread_mutex_t *mutexes;

typedef struct
{
    float* vetor;
    unsigned int posInicial;
    unsigned int posFinal;
    unsigned int contMutexThread;
} Thread_preenche;

typedef struct
{
    float* x;
    float* y;
    float* z;
    unsigned int posInicial;
    unsigned int posFinal;
    unsigned int contMutexThread;
} Thread_soma;

void *preencheVetores(void *argPtr){
    Thread_preenche *thread_p = (Thread_preenche*)argPtr;
    unsigned int inicio = thread_p->posInicial;
    unsigned int final = thread_p->posFinal;

    for(;inicio <= final; inicio++){
        pthread_mutex_lock(&mutexes[thread_p->contMutexThread]);
        thread_p->vetor[inicio] = (float)rand()/(float)(RAND_MAX/1.0);
        printf("x[%u] e o valor é: %f \n", inicio, x[inicio]);
        pthread_mutex_unlock(&mutexes[thread_p->contMutexThread]);
    }
    pthread_exit(0);
}

int main() {
    setlocale(LC_ALL, "Portuguese");

    //obtendo o tamanho do vetor e o número de threads que o usuário deseja
    int tamanho_vetor;
    int n;
    while (1){
        printf("Digite o tamanho do vetor: ");
        scanf("%d", &tamanho_vetor);
        printf("Digite o número de threads: ");
        scanf("%d", &n);
        if (tamanho_vetor % n != 0){
              printf("O número de threads deve ser múltiplo do tamanho do vetor. \n");
        }else{
            break;
        }
    }

    //inicialização dos vetores
    x =(float*) malloc(sizeof(float)*tamanho_vetor);
    y =(float*) malloc(sizeof(float)*tamanho_vetor);
    z =(float*) malloc(sizeof(float)*tamanho_vetor);
    mutexes = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t)*n);
    int divisao_vetor[n+1];
    for (int i = 0; i <= n; i++){
        divisao_vetor[i] = ((tamanho_vetor/n)*(i));
    }
    pthread_t thread[n];
    for (int i = 0; i < n; ++i){
        pthread_mutex_init(&mutexes[i],NULL);
        Thread_preenche thread_preenche = {
            .vetor = &x[0],
            .posInicial = (divisao_vetor[i]),
            .posFinal = divisao_vetor[i+1]-1,
            .contMutexThread = i
        };
        pthread_create(&thread[i], NULL, preencheVetores, &(thread_preenche));
        //jeito errado, o join logo em seguida do create da thread.
        //pthread_join(thread[i], NULL);
    }
    //Assim seria o jeito certo de fazer, o join sendo depois
    //mas não está funcionando.
    for (int i = 0; i < n; i++){
        pthread_join(thread[i], NULL);
    }

    free(x);
    free(y);
    free(z);
    free(mutexes);

    #ifdef _WIN32
        system("pause");
    #else __linux__
        system("read -p 'Press Enter to continue...\n' key");
    #endif

   return 0;
}

void *somaVetores(void* argPtr);

Crio várias threads, cada uma para popular uma parte do vetor.
Se eu fizer do jeito errado que é fazer o join logo depois do create das threads dentro de um for, desse jeito:
pthread_create(&thread[i], NULL, preencheVetores, &(thread_preenche));
pthread_join(thread[i], NULL);

Eu tenho o resultado esperado, com todos os campos populados. Mas, foi removida toda concorrência das threads, oque não é desejado.
Se eu aplico o join nas threads depois que todas elas foram criadas, desssa forma:
//abstraindo o for que cria as threads.
pthread_create(&thread[i], NULL, preencheVetores, &(thread_preenche));

for (int i = 0; i < n; i++){
    pthread_join(thread[i], NULL);
}

Eu não tenho o resultado desejado, são populado apenas os últimos elementos do array, como base na divisão que fiz de acordo com o número de threads, é como se todas as threads estivessem populando o mesmo range do array, embora tivesse definido ranges diferentes para cada thread popular o array. Porque isso está acontecendo ? Onde estou errado ?
Como exemplo, eu tenho o seguinte resultado (x é o array que estou populando):
Digite o tamanho do vetor: 32
Digite o número de threads: 4
x[24] e o valor é: 0.840188
x[25] e o valor é: 0.394383
x[26] e o valor é: 0.783099
x[27] e o valor é: 0.798440
x[28] e o valor é: 0.911647
x[29] e o valor é: 0.197551
x[30] e o valor é: 0.335223
x[31] e o valor é: 0.768230
x[24] e o valor é: 0.277775
x[25] e o valor é: 0.553970
x[26] e o valor é: 0.477397
x[27] e o valor é: 0.628871
x[28] e o valor é: 0.364784
x[29] e o valor é: 0.513401
x[30] e o valor é: 0.952230
x[31] e o valor é: 0.916195
x[24] e o valor é: 0.635712
x[25] e o valor é: 0.717297
x[26] e o valor é: 0.141603
x[27] e o valor é: 0.606969
x[28] e o valor é: 0.016301
x[29] e o valor é: 0.242887
x[30] e o valor é: 0.137232
x[31] e o valor é: 0.804177
x[24] e o valor é: 0.156679
x[25] e o valor é: 0.400944
x[26] e o valor é: 0.129790
x[27] e o valor é: 0.108809
x[28] e o valor é: 0.998924
x[29] e o valor é: 0.218257
x[30] e o valor é: 0.512932
x[31] e o valor é: 0.839112

Comment: Vale mencionar que o mesmo problema acontece se eu simplismente não utilizar pthread_join() nenhum.
Answer: Existem alguns problemas no programa, mas o principal deles que causa este
comportamento é a delcaração e inicialização da struct Thread_preenche
dentro do looping.
Apesar da estrutura estar declarada dentro do looping, o compilador não aloca
memória para uma nova estrutura a cada iteração, portanto ela é tratada como
se fosse declarada apenas uma vez fora do looping.
Com isso, todas as threads são inicializadas com o último valor colocado
na struct, gerando a saída apenas com "os últimos valores".
A solução para este problema é declarar um array de estruturas
Thread_preenche e inicializar cada thread com a sua própria estrutura:
Thread_preenche thread_preenche[n];
...
for (int i = 0; i < n; ++i){
    thread_preenche[i].vetor = &x[0];
    thread_preenche[i].posInicial = (divisao_vetor[i]);
    thread_preenche[i].posFinal = divisao_vetor[i+1]-1;
    thread_preenche[i].contMutexThread = i;

    pthread_mutex_init(&mutexes[i],NULL);
    pthread_create(&thread[i], NULL, preencheVetores, &(thread_preenche[i]));
...

Outras melhorias que podem ser feitas, dependendo do objetivo do programa:

Não faz sentido declarar uma trava mutex para cada thread. O
objetivo da trava é bloquear as demais threads durante o acesso a um
recurso compartilhado (ex: um arquivo, um dispositivo, memória compartilhada,
etc.), portanto a trava precisa ser única por recurso e todas elas,
compartilhadas entre as threads. No caso do seu programa, se o objetivo for
atualizar apenas a memória, como já há uma divisão do vetor para cada
thread, a trava não é necessária, entretanto, o printf acessa um
dispositivo de I/O e, neste caso, talvez faça sentido utilizar uma
trava para acessá-lo.

Pode não ser necessário pré-calcular a divisão do vetor no array
divisao_vetor, pois ele pode ser calculado diretamente dentro do looping
que cria as threads. Porém, se o programa for apenas um exemplo de um
sistema mais complexo, este armazenamento pode fazer sentido.

Segue uma versão otimizada e comentada do programa da pergunta,
apenas como exemplo:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <locale.h>
#include <time.h>

//declaração das variáveis globais
float *x;
float *y;
float *z;

// AQUI => Cria apenas um mutex, compartilhado entre as threads
static pthread_mutex_t mutex;

typedef struct
{
    float* vetor;
    unsigned int posInicial;
    unsigned int posFinal;
    unsigned int contMutexThread;
} Thread_preenche;

typedef struct
{
    float* x;
    float* y;
    float* z;
    unsigned int posInicial;
    unsigned int posFinal;
    unsigned int contMutexThread;
} Thread_soma;

void *preencheVetores(void *argPtr){
    Thread_preenche *thread_p = (Thread_preenche*)argPtr;
    unsigned int inicio = thread_p->posInicial;
    unsigned int final = thread_p->posFinal;

    for(;inicio <= final; inicio++){
        pthread_mutex_lock(&mutex);
        thread_p->vetor[inicio] = (float)rand()/(float)(RAND_MAX/1.0);
        printf("x[%u] e o valor é: %f \n", inicio, x[inicio]);
        pthread_mutex_unlock(&mutex);
    }

    pthread_exit(0);
}

int main() {
    setlocale(LC_ALL, "Portuguese");

    //obtendo o tamanho do vetor e o número de threads que o usuário deseja
    int tamanho_vetor;
    int n;
    while (1){
        printf("Digite o tamanho do vetor: ");
        scanf("%d", &tamanho_vetor);
        printf("Digite o número de threads: ");
        scanf("%d", &n);
        if (tamanho_vetor % n != 0){
            printf("O número de threads deve ser múltiplo do tamanho do vetor. \n");
        }else{
            break;
        }
    }

    //inicialização dos vetores
    x =(float*) malloc(sizeof(float)*tamanho_vetor);
    y =(float*) malloc(sizeof(float)*tamanho_vetor);
    z =(float*) malloc(sizeof(float)*tamanho_vetor);

    // AQUI => Excluído a declaração do vetor de travas e divisão
    //
    //    mutexes = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t)*n);
    //    int divisao_vetor[n+1];
    //    for (int i = 0; i <= n; i++){
    //        divisao_vetor[i] = ((tamanho_vetor/n)*(i));
    //    }
    //
    // AQUI => Calcula o tamanho do job de cada thread
    int num_job = tamanho_vetor / n;

    // AQUI => precisa declarar um parâmetro para cada thread para
    //         não sobrescrever os valores
    Thread_preenche thread_preenche[n];

    // AQUI => Inicializa apenas um MUTEX
    pthread_mutex_init(&mutex, NULL);

    pthread_t thread[n];

    for (int i = 0; i < n; ++i){
        // AQUI => Inicializa cada parâmetro separadamente e já
        // calcula o job de cada thread
        thread_preenche[i].vetor = &x[0];
        thread_preenche[i].posInicial = i*num_job;
        thread_preenche[i].posFinal = i*num_job+num_job-1;
        thread_preenche[i].contMutexThread = i;

        pthread_create(&thread[i], NULL, preencheVetores, &thread_preenche[i]);
    }

    //Assim seria o jeito certo de fazer, o join sendo depois
    //mas não está funcionando.
    for (int i = 0; i < n; i++){
        pthread_join(thread[i], NULL);
    }

    free(x);
    free(y);
    free(z);
    //free(mutexes);
    pthread_mutex_destroy(&mutex);

#ifdef _WIN32
    system("pause");
#else
    system("read -p 'Press Enter to continue...\n' key");
#endif
    return 0;
}

void *somaVetores(void* argPtr);


Proper maintenance for classic guitars?

Question: I have had my classic for about two years, and don't do anything to it other than wiping dust off the guitar and replacing the strings when needed(about every month or so).
I've had a sponge type of "thing", they called it fret cleaner. I normally wiped it over the strings gently and wiped the excess off with a cloth that came with. That did not do much for the fretboard itself, but the strings appeared to last longer against corrosion.
The fretboard only became like slippery, and my slides tended to go further what I expected - so I dropped that all-together.
I want to know what would the best chemicals would be to clean an classic guitar. The fretboard, being made of a plastic substance, doesn't absorb oils, and it only makes it more
"slippery" as I said above.
Currently I use normal wood oil for the body, and don't do anything to the fretboard apart from wiping it with a damp cloth every week.
Is there anything else I need to do in order to perform better maintenance on my classical?
Comment: I've never heard of a plastic fretboard (except on a rock band controller type guitar).
Comment: I am curious - why do you need to replace the strings every month or so?
Comment: @talonx See this question: http://music.stackexchange.com/questions/1538/how-often-should-i-replace-the-strings-on-my-guitar
Comment: @talonx: I have a nylon-string guitar which I've had for three years, and have only changed the strings twice.  It still sounds fantastic.  My dad has a 12-string fender which he has had for 30 years, and I don't think he's ever changed the strings on it *(at least, not in the last 25 years that I've been alive :) )*.  It still sounds beautiful, and the strings are surprisingly (to me, at least) not rusting at all.  So, your mileage on these things may vary.
Answer: Here's the link to Frets.com, a site run by a pro repairman of many years experience:
http://www.frets.com/FRETSPages/pagelist.html#Musician
Check out the "general maintenance" section.   Hell, read the whole thing.  It's a gold mine of information.
Not much in the way of general daily maintenance is required.  Wipe the instrument down with a soft cloth, strings likewise.  Clean the fretboard periodically with extra-fine steel wool and perhaps a bit of lemon oil...
Comment: I used to visit Gryphon every time I passed through Palo Alto. Frank is a very solid dude.
Comment: Thats about all I do to maintain my classical guitars. Just wipe them down with a soft polishing cloth every time I play, and once a year or even once every two years just put a very tiny amount of lemon oil on the fretboard to prevent it drying out and keep it looking dark.

Proper maintenance for classic guitars?


How to share a Single Domain SSL certificate across 2 ip addresses

Question: I have a wordpress website example.com. I have a single domain SSL certificate that can be used across multiple servers.
When a user visits example.com, or any subfolder expect forum , they access server1 which is running apache.
When a user vists example.com/forum they are redirected to server2 which runs nginx. How would I set such that both ip addresses are mapped under example.com such that the redirects are only internal and the domain remains example.com at all times
In my site apache vhost, I am using
Redirect permanent /forum http://server2ip

to redirect to server2
EDIT ACCORDING TO LUCA'S ANSWER TO SET server1 as PROXY to SERVER2
Here is my apache vhost config for the setup
VirtualHost *:80>
   RewriteEngine on
   ServerName example.com
   ServerAdmin email@example.com

   DocumentRoot /var/www/example

   #Redirect all HTTP requests to HTTPS
   # RewriteCond %{SERVER_PORT} 80
   # RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

   ProxyPass /forum https://server2ip/

   <Location /forum>
     ProxyPass https://server2ip/
     ProxyPassReverse https://server2ip/
   </Location>

   <Proxy *>
       Order allow,deny
       Allow from all
   </Proxy>

   ProxyHTMLEnable On
   ProxyHTMLURLMap https://server2ip/ /forum
</VirtualHost>

Answer: You are actually redirecting the client to a different server. Assuming you configured DNS to point to server1, you want to mask the presence of server2. To do this configure apache as a reverse proxy and proxy /forum requests to server2. You do not need to configure SSL on server2.
Comment: @Luna Corti How would I go about Setting apache as a reverse proxy to server2..so that server2 runs on example.com/forum?
Comment: http://www.microhowto.info/howto/configure_apache_as_a_reverse_proxy.html
Comment: ...I have updated my answer with my vhost config...i have never worked with a proxy before so excuse my noobiness
Comment: Is the proxying working? Are you getting any errors/have any issues with that setup?


OpenTSDB metrics using data from sar, vmstat and iostat logs

Question: I recently started exploring OpenTSDB for monitoring a cluster that we have in our development environment. As a newbie, I have not delved deep into it, but was wondering if anyone successfully used OpenTSDB to monitor those.
Any pointers is helpful.
Comment: tcollector seems to have some iostat hooks in it, I will explore that and try to mimic similarly for ohter metrics http://opentsdb.net/tcollector.html
Answer: OpenTSDB has a child project to help collect system data from Linux servers and report it to OpenTSDB, called tcollector.
It's a simple data collection system written in Python, and it comes with a dozen+ collectors out of the box, including collectors for vmstat and iostat data.  On a standard Linux server you'll get over a hundred system metrics.
Answer: OpenTSDB is basically built to handle very large amounts of monitoring data, so it is really only applicable if you monitor hundreds over servers, and you want to keep data in full fidelity indefinitely.
If not, you should really look into stuff like CollectD or Graphite.


Dúvida referente ao optional chaining

Question: Dando uma olhada em alguns códigos pela web me deparei com o seguinte trecho:

let userAdmin = {
  admin() {
    alert("I am admin");
  }
};

let userGuest = {};

userAdmin.admin?.(); // I am admin

userGuest.admin?.(); // nothing happens (no such method)

Entendi o por quê só foi disparado o alert com a mensagem I am admin, pois em userGuest foi declarado um objeto vazio. Mas me surgiram duas indagações:

1ª - Por que depois de admin? foi dado um ponto e depois os parênteses, seria a sintaxe para poder fazer a utilização do optional chaining no método ou é outra coisa?

2ª - No caso da declaração userGuest.admin?.() me parece um desperdício de recurso, não seria melhor verificar se o objeto possui algo dentro primeiro, algo como if (userGuest !== {})?

Espero que as dúvidas tenham ficadas claras!  Os exemplos foram retirados deste link.
Comment: Por que acha que em (2) o *optional chaining* seria um desperdício de recurso?
Comment: Opa Woss, então é o que acho mas não tenho certeza não :). Pq pela lógica agente está tentando executar algo dentro de uma coisa que está vazia, não seria mais viável testar se algo está vazio primeiro? Tipo como comentei `if (userGuest !== {})` ou com um próprio optional chaining `userGuest?.admin`?
Comment: Só pra constar, `userGuest !== {}` sempre será `true`, pois a comparação verifica se os objetos são o mesmo (e nunca serão, porque `{}` cria um novo objeto)
Answer: Para mais informações, ler: O que significa uma interrogação "?." no acesso às propriedades de um objeto?

1ª - Por que depois de admin? foi dado um ponto e depois os parênteses, seria a sintaxe para poder fazer a utilização do optional chaining no método ou é outra coisa?

Simplesmente porque a sintaxe do operador de encadeamento opcional é o ?., não existe o ? sozinho. Por mais besta que possa parecer, seria o mesmo que questionar porque foi feito x++ para utilizar o operador de auto incremento.

2ª - No caso da declaração userGuest.admin?.() me parece um desperdício de recurso, não seria melhor verificar se o objeto possui algo dentro primeiro, algo como if (userGuest !== {})?

O operador de encadeamento opcional é justamente para isso. Ao ler na documentação e na resposta citada verá que o JS interrompe a avaliação daquela expressão quando o operando que o antecede é undefined ou null, retornando undefined independente do que está a direita dele.
Em outras palavras, fazer algo como user?.admin?.() seria o equivalente a:
if (user === undefined) {
  return undefined;
}

if (user.admin === undefined) {
  return undefined;
}

return user.admin();

Mas perceba que ele só valida se o operando é diferente de undefined ou null, não validando se o atributo é chamável ou não. Se o campo existir e ser uma string, por exemplo, ainda dará erro TypeError, mesmo usando o operador de encadeamento opcional.

let userAdmin = {
  admin: 'sou uma string'
};

userAdmin.admin?.();
Comment: Blza man, obrigado pela resposta.

Dúvida referente ao optional chaining