Having trouble inserting a row in a DB table when running a stored procedure which is using the same table in another transaction

Question: Let me explain my problem. I have data warehouse stored procedure which used link server to connect to 3 different database and get data. But when warehouse import is running which is under a transaction then it blocks 3 tables in those 3 database. So as the import run for at least 3 hours the main sites gets blocked.
Now when the import is running, people trying to access the site gets stuck as one of the action was to insert a entry in the history table which is getting blocked. But should it block insert operation when there is a select query in another SQL Server?
Answer: If you use WITH(NOLOCK) option during the retrieval, SQL Server wont block other users from inserting data


Can't get Apache 2.2.21 to compile with OpenSSL support

Question: Alright -- having a bad couple days here compiling Apache 2.2.21 on CentOS 5.7 with the following configure commands:
./configure --enable-ssl=shared --with-ssl=/usr/local/openssl

I've compiled from source OpenSSL 1.0.0e from source:
./config --prefix=/usr/local --openssldir=/usr/local/openssl shared zlib-dynamic

I attempt to start Apache and it returns:
httpd: Syntax error on line 54 of /usr/local/apache2/conf/httpd.conf: Cannot load /usr/local/apache2/modules/mod_ssl.so into server: /usr/local/apache2/modules/mod_ssl.so: undefined symbol: SSL_get_servername
If I look at how the libraries are linked, this is what I get:
[root@web1 modules]# ldd mod_ssl.so
libssl.so.6 => /lib64/libssl.so.6 (0x00002aaaaace4000)
libcrypto.so.6 => /lib64/libcrypto.so.6 (0x00002aaaaaf30000)
libdl.so.2 => /lib64/libdl.so.2 (0x00002aaaab281000)
libz.so.1 => /lib64/libz.so.1 (0x00002aaaab486000)
libpthread.so.0 => /lib64/libpthread.so.0 (0x00002aaaab69a000)
libc.so.6 => /lib64/libc.so.6 (0x00002aaaab8b5000)
libgssapi_krb5.so.2 => /usr/lib64/libgssapi_krb5.so.2 (0x00002aaaabc0e000)
libkrb5.so.3 => /usr/lib64/libkrb5.so.3 (0x00002aaaabe3c000)
libcom_err.so.2 => /lib64/libcom_err.so.2 (0x00002aaaac0d1000)
libk5crypto.so.3 => /usr/lib64/libk5crypto.so.3 (0x00002aaaac2d4000)
/lib64/ld-linux-x86-64.so.2 (0x0000555555554000)
libkrb5support.so.0 => /usr/lib64/libkrb5support.so.0 (0x00002aaaac4f9000)
libkeyutils.so.1 => /lib64/libkeyutils.so.1 (0x00002aaaac702000)
libresolv.so.2 => /lib64/libresolv.so.2 (0x00002aaaac904000)
libselinux.so.1 => /lib64/libselinux.so.1 (0x00002aaaacb19000)
libsepol.so.1 => /lib64/libsepol.so.1 (0x00002aaaacd32000)
Basically, I've tired compiling from source OpenSSL (both 0.9.8r and 1e), having yum reinstall from the repos, done a make clean and remade both OpenSSL and Apache numerous times -- but I can't get it to compile into the apache base or dynamically as a shared object file.
What am I doing wrong here?
Update 1:
After doing a make clean and make distclean, I've reconfigured with the same parameters as above without any effect.
The config.log is at Pastebin.
Update 2:
Modifying the LD_LIBRARY_PATH had no effect on the lib-deps of mod_ssl.so.
UPDATE 3:
I've compiled and recompiled many times, and verified with ldconfig that the OpenSSL libs dir is in my path, and included in ld.so.conf.  Still cannot get httpd/mod_ssl to load the library at runtime.
Comment: I'm not the OP, but I'm interested - please do post an answer!
Comment: Is this still an open question you are interested in? If so, I can provide detailes steps since I did this recently on my CentOS 6.3. I was enabling FIPS on OpenSSL and Apache.
Answer: When you compiled Apache you should have "--enable-so". I think you must have because the so module is trying to load.
Also after compiling openssl ensure the system can find the shared library with
"/sbin/ldconfig -v /usr/local/openssl/lib"
and I also like to edit /etc/ld.so.conf.d/local.conf to add a line for /usr/local/openssl/lib
Comment: That's correct.  I've tried with `--enable-so` and without (and then compiling it into httpd).  Either way do it, it will not load the libssl.so.* files no matter where they are when they're in the library path, and everything in between, trying builds of apache from 2.2.19-2.2.21 and openssl.0.9.8.r-1.0.0e.
Comment: Fresh install of ScientificLinux 5.5 without openssl-devel.openssl 1.0.0e./Configure --prefix=/usr/local/openssl100e linux-elf shared; make installcd /usr/local; ln -s openssl100e ssl/sbin/ldconfig -v /usr/local/ssl/libApache 2.2.21:--prefix=/usr/local/apache --enable-so --enable-ssl --with-ssl=/usr/local/ssl and others.bin/apachectl -M | grep ssl says "ssl_module (shared)"Copied a generic server.crt and server.key into the conf directory, uncommented conf/extra/httpd-ssl.conf/usr/local/servers/bin/apachectl start worked and nmap shows 80 and 443 open.
Comment: Had the same problem it was resolved when doing the "/sbin/ldconfig -v /usr/local/openssl/lib" command. Although i had to use "sudo" and i had not compiled it in "/usr/local/openssl".
Answer: I recall that openssl doesn't make shared libraries by default.
I do this:
./Configure --prefix=/usr/local/openssl linux-elf shared
Then you still have to do ldconfig as above. And tell apache where to find ssl libs.
Comment: Correct, and OpenSSL has been compiled this way.  Apache will not link the library to the libraries installed from compiling OpenSSL nor through yum and the CentOS repos.
Answer: Had the same problem few minutes again, so I add:
LDFLAGS=-L/usr/local/ssl/lib

and the parameter for ./configure (Apache) modified from:
--with-ssl=/usr/local/ssl

to
--with-ssl=/usr/local/ssl/lib

and no its ok.
Answer:
ldd mod_ssl.so libssl.so.6 => /lib64/libssl.so.

would indicate that you're not linking against the openssl in /usr/local. do a "make clean && makedistclean" for both your apache/openssl builds, then rebuild/install openssl. ./configure [your options] apache, and check its config.log to make sure that it's linking against the correct openssl lib.
alternatively, please provide the output of your existing config.log
Comment: No change with `make clean` and `make distclean`, but I have tried them before.  config.log link is above.
Comment: export LD_LIBRARY_PATH=/usr/local/openssl/lib:$LD_LIBRARY_PATH, then recheck ldd.
Comment: basically, it looks like Apache's finding the right libraries at compile-time, but not at run-time. adjusting LD_LIBRARY_PATH will give your openssl libs precedence in the search path.
Comment: After modifying the LD_LIBRARY_PATH var, the results are the same.
Answer: It is definitely linking to the wrong OpenSSL install as pointed out previously. You should have /usr/local/ssl/lib in ld.so.conf, but try it with the following Apache configure command:
LDFLAGS=-L/usr/local/ssl/lib \
./configure \
--enable-ssl \
--enable-mods-shared=all \
--with-ssl=/usr/local/ssl

Also, are you sure OpenSSL itself is compiling as intended? Could it be failing to make shared libraries itself and falling back to static but still compiling successfully?
Comment: It is compiling the `mod_ssl.so` file in `modules/`.  I'm still executing `./configure --with-ssl=the/right/dir`, and configure sees this at configure-time.  Once it compiles, and we come to runtime, it doesn't link properly to the library dictated at compile time.
Comment: You could try removing openssl-devel from your system and then try again. If you are compiling your own version of SSL, you likely don't need that. As a last resort, you can manually tell mod_ssl.so which library to use with this: http://nixos.org/patchelf.html
Answer: Check the SELinux logs. You have to tag the binaries with the proper SELinux attribute.
Comment: SELinux is disabled.


Dovecot + Postfix: How to automatically send a e-mail back when requested e-mail adress is not found

Question: I currently have a e-mail server set up with dovecot and postfix, getting users from a mysql database, on an ubuntu server. I would like to know how to automatically send an e-mail to the sender if he sends an e-mail to an adress that doesn't exist.
Thank you!
Comment: That's the default behaviour of postfix.
Answer: This is how it works when Postfix is trying to deliver the message to another MTA, but fails.
If Postfix already knows during the SMTP connection that the mail cannot be delivered (domain is handled locally and mailbox doesn't exists, relay is not permitted etc.) it will give an SMTP error, instead. This is how it should work and you should not try to change this.


Help needed in proving a theorem on a permutation that is the product of dis. cycles of prime length.

Question: So we were given the following proof to do:
Let $ p $ and $ q $ be distinct primes. Suppose $ \alpha $ is a permutation of $ S_n $ and suppose  $ \alpha = \gamma_1 \gamma_2 $ where $ \gamma_1 $ and $ \gamma_2 $ are disjoint cycles of length $ p $ and $ q $, respectively. Prove that if $ \alpha^m $ is a cycle of length $ t $ and gcd$(m, p) = 1$, then $ p $ divides $ t $.
I think I have come up with one that works, but I don't use a part of the hypothesis so I'm concerned I'm missing something.
If anyone could help me correct my proof it would be much appreciated:
$ i. $ As $ \gamma_1 $ is a cycle of length $ p $, it is likewise a cycle of order $ p $. Therefore, because the gcd$(m,p)=1$, the order and length of $ \gamma_1^m $ must also be $ p $.
$ ii. $ $ \alpha^m $ may be written as a product of the disjoint cycles $ \gamma_1^m $ and $ \gamma_2^m $ as $ \alpha^m = (\gamma_1 \gamma_2)^m = \gamma_1^m \gamma_2^m $. So the order of $ \alpha^m $ is the least common multiple of the lengths of $ \gamma_1^m $ and $ \gamma_2^m $. From $i.$ we know that the length of $ \gamma_1^m $ is $ p $, and so the least common multiple of $ \gamma_1^m $ and $ \gamma_2^m $ must be divisible by $ p $.
If $ \alpha^m $ is a cycle of length $ t $, then it is a cycle of order $ t $, and so $ t = $ lcm($ \gamma_1^m $, $ \gamma_2^m $).
Therefore $ t $ is divisible by $ p $.
Comment: Thanks for letting me know. I didn't know we were supposed to.
Answer: Your proof is correct, but a bit repetitive.  I'll throw in my version:

We are given that the $p$- and $q$-cycles are disjoint in $\alpha$, so $\alpha^m=(\alpha_p\alpha_q)^m=\alpha_p^m\alpha_q^m$.  Since $p$ is prime, $\alpha_p^m=1$ if and only if $p$ divides $m$.  In particular, $\alpha_p^m$ is a $p$-cycle whenever $p$ does not divide $m$, whence $\alpha^m=\alpha_p^m\alpha_q^m$ has order divisible by $p$.


Limit text field to specific length

Question: In my custom content type, I want restricted the length of text entered in a text field. I want to check whether a user entered e.g. thousands of words. For this I tried this one but unable to achieve.
$my_field = field_get_items('node',node_load($nid, NULL, TRUE), 'my_field');
$my_field = substr($my_field,0,100).'...';
print $my_field[0]['value'];

Is there any way to do this in drupal 7 context?
Answer: If you're really trying to restrict the character count at the point of entry you need to set the field in your form to have a #maxlength in your form definition.
Comment: I want to restrict the text on one page but when clicked on `more link` or `read more` then the detail text should be displayed on next page.
Comment: Oh!  That's quite different to restricting the length of a field at the point of input. Take a look at the `Manage Display` tab for that content type and set the Teaser display to `trimmed` or similar.  There's a very good module called [Smart Trim](https://www.drupal.org/project/smart_trim) which can help customise the snippet too.
Comment: Thanku @Darvanen, I did it using php `strlen()` and `substr()`.
Answer: There is basically two modules that come to my mind regarding this functionality. The second one (Maxlength) is probably a bit more promissing:

Webform Countdown "Provides a textarea component for Drupal webforms with a configurable, twitter-style dynamic word or character count."

Maxlength "When the maximum length is enforced for a field, while editing content of that type some Java Script will countdown how many characters are left, also if the Javascript is turned off, it falls back to form API validation."

[EDIT] If you instead want to limit the text length shown in a teaser view, you can do that through the basic display settings of your content type:
structure > content types > my_content_type > display > teaser
There you can set the format to "Trimmed" or "Summary or trimmed" and then  limit the lenght for example to 600: "Trim length: 600". Afaik this setting can be adjusted in every view.
Comment: Thanku @tillinberlin, actually I want to restrict the text on one page but when clicked on `more link` or `read more` then the detail text should be displayed on next page.
Comment: ok, i see – I edited my answer accordingly

Limit text field to specific length


Fullscreen absolute child positioning

Question: I've been at this for a while, but I can't seem to figure out a proper way of doing this. Within my application I have a modal view inwhich there is a component that needs to take up the fullscreen. The problem I'm having is that the element is placed relative to their parent. While I need the positioning relative to the html body. Is there any way I can do this? I've made a simple fiddle showing the problem more clearly.
HTML

    test

.modal {
  height: 100px;
  width: 100px;
  background: red;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.fullscreen {
  background: rgba(231, 29, 91, 0.5);
  position: absolute;
  width: 100vw;
  height: 100vh;
  top: 0;
  left: 0;
}

Fiddle
The only solution I've so far been able to find myself is the following;
.fullscreen {
  background: rgba(231, 29, 91, 0.5);
  position: absolute;
  width: 100vw;
  height: 100vh;
  top: calc(-50vh + 50%);
  left: calc(-50vw + 50%);
}

But this isn't very pretty.
Comment: @AStombaugh actually using flexbox instead for centering the modal seems do the trick together with `fixed` positioning! Cheers
Comment: If the component in the modal needs to be full screen, why not just make the modal full screen and then position the component inside of it?
Comment: Absolute positioning always takes the closest positioned ancestor as reference point, and only if there is none all the way up to the root element, the reference point becomes the viewport. Perhaps switching to fixed would help? You'd need to remove the `transform` then, but there are other ways to center an absolute positioned element. https://jsfiddle.net/ecyLram0/1/
Comment: @AStombaugh the component that needs to go fullscreen is a carousel image slider, and the fullscreen mode enlarges the slider and places it on top of all the content so it the user can view an image fullscreen. Fullscreening the modal won't really do for me.
Comment: @CBroe this does seem to work nicely, only centering via `margin: auto` is stretching my modal to no longer wrap around the content.
Comment: @MartijnEbbens if your content is images, you might need to look into `object-fit` to keep them from stretching if you're using some fixed sizing like your example has. https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit
Comment: Check out the dialog html element it might be just what you need
Answer: Please feel free to use the version of the modal provided here:
JS Fiddle Link for Working Modal

// Get the modal
var modal = document.getElementById("myModal");

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btn.onclick = function() {
  modal.style.display = "block";
}

// When the user clicks on  (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
  background-color: #fefefe;
  margin: 15% auto; /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

<button id="myBtn">Open Modal</button>

    ×

Some text in the Modal..

I got that code from w3schools (it uses JavaScript in addition to CSS and HTML). All you would need to do is hit the button that's located in the top left corner of the results screen to show the modal.
However, if you really want to speed things up, you can look into using the bootstrap UI framework to build your frontend.
Answer: You can fix this issue by changing code to following.

.modal-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
}

.modal {
  width: 100px;
  height: 100px;
  background-color: red;
}

.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: yellow;
}

      Test

Have a read on to this mdn article it explains why your earlier solution didn't work.
https://developer.mozilla.org/en-US/docs/Web/CSS/position

Fullscreen absolute child positioning


Will component re-render even if we do not pass props to it?

Question: I was learning React and wanted to ask if, be it a functional or class component, re-render even if we do not pass props to it at all. For simplicity sake, let's imagine <Counter><Input/></Counter>. So we have counter component and inside of which we have input component. The question is when we change state in counter component will input component rerender EVEN IF we do not pass any props to input?
}
Answer: Technically, Input is a child or Counter component and is passed on as children prop to Counter.
Input component will not re-render if the state within the Counter is updated and counter re-renders.
However If the component that renders Counter and Input component re-renders, both of these components will get rerendered unless you implement them as a PureComponent
Attaching a small demo for proof of concept.

class App extends React.Component {
  state = {
     toggle: false
  }
  render() {
     return (

          <Counter><Input /></Counter>

<button type="button" onClick={() => this.setState(prev=> ({toggle: !prev.toggle}))}>Toggle App state</button>

     )
  }
}

class Counter extends React.Component {
   state = {
      count: 0
   }

   componentDidMount() {
     this.timer = setInterval(() => {
        this.setState(prev => ({count: prev.count + 1}));
     }, 1000)
   }

   render() {
    console.log('counter render');
    return (
      <React.Fragment>

Counter: {this.state.count}

        {this.props.children}
      </React.Fragment>
    )
   }
}

const Input = () => {
   console.log('Input render');
   return (
    <input type="text" placeholder="Enter text" />
   )
}

ReactDOM.render(<App />, document.getElementById('app'));

Comment: hi Shubham, so you mean if state inside Counter gets changed then Input component which is a child of Counter will NOT rerender Right?


Mailchimp API: Send campaign to users with tags

Question: I'm trying to send a campaing to a segment based on Tags (That is to list members with a specific tag) using API calls with mailchimp3 for Django, but I can't quite find what should be the right json structure to make it, this is what I've got so far:
<code>        campaign_creation = {
        "type": "regular",
        "recipients": {
            "list_id": LIST_ID,
            "segment_opts": {
                "match": "any",
                "conditions": [{
                    "condition_type": "StaticSegment",
                    "op": "contains",
                    "field": "Tags",
                    "value": ["foo"]
                }]
            }
        },
        "settings": {
            "subject_line": campaign_label,
            "title": campaign_label,
            "from_name": FROM_NAME,
            "reply_to": REPLY_TO,
        },
    }
</code>
But with that I get the error:
mailchimp3.mailchimpclient.MailChimpError: {'type': 'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/', 'title': 'Invalid Resource', 'status': 400, 'detail': "The resource submitted could not be validated. For field-specific details, see the 'errors' array.", 'instance': '88679b18-6e55-4463-9c62-06d47b825f77', 'errors': [{'field': 'recipients.segment_opts.conditions.item:0', 'message': 'Data did not match any of the schemas described in anyOf.'}]}
Worth to mention that the routine to create and send campaign to the whole list is working perfect, just fails because I've added the segment_opts part
Anyone may have any idea how to make it work? Thanks in advance!
Answer: It may be old question, but here's the answer - your StaticSegment object may be wrong. It works like that in my case, however if you want to use multiple tags, then maybe the correct way to do it is by adding another StaticSegment for each tag. Also, you pass foo and I assume you know this should be the tag id.
<code>'conditions' => [
    [
      'condition_type' => 'StaticSegment',
      'field' => 'static_segment',
      'op' => 'static_is',
      'value' => $tagId
    ]
 ]
</code>


Is there a Python library where I can import a gradient descent function/method?

Question: One way to do gradient descent in Python is to code it myself. However, given how popular a concept it is in machine learning, I was wondering if there is a Python library that I can import that gives me a gradient descent method (preferably mini-batch gradient descent since it's generally better than batch and stochastic gradient descent, but correct me if I'm wrong).
I checked NumPy and SciPy but couldn't find anything. I have no experience with TensorFlow but looked through their online API. I found tf.train.GradientDescentOptimizer, but there is no parameter that lets me choose a batch size, so I'm rather fuzzy on what it actually is.
Sorry if I sound naive. I'm self-learning a lot of this stuff.
Comment: Look at that example. https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/4_convolutions.ipynb
Comment: In the graph X is a placeholder of batch_size, and in training the full data is divided into batches at every step
Comment: First, I advise you to choose Adam Optimizer instead of GradientDescent (concerning Stochastic Gradient descent, this can be "hand-wavily" seen as a mini-batch gradient descent with mini-batch size equals to `1`). As for TensforFlow, even if you cannot chose the mini-batch size, you can still code yourself that part and use the GradientDescentOptimizer on these minibatches.
Answer: To state the obvious, gradient descent is optimizing a function. When you use some implementation of gradient descent from some library, you need to specify the function using this library's constructs. For example, functions are represented as computation graphs in TensorFlow. You cannot just take some pure python function and ask TensorFlow's gradient descent optimizer to optimize it.
If your use case allows you to use TensorFlow computation graphs (and all the associated machinery - how to run the function, compute its gradient, ), tf.train.*Optimizer would be an obvious choice. Else, it is unusable.
If you need something light, https://github.com/HIPS/autograd is probably the best option of all the popular libraries. Its optimizers can be found here: https://github.com/HIPS/autograd/blob/master/autograd/misc/optimizers.py


Prove that the open ball $B(0,1) \in \mathbb{C}$ is connected.

Question: Using the theorem, An open set $G \subset \mathbb{C}$ is connected iff for any two points $a,b$ in $G$ there is a polygon from $a$ to $b$ lying entirely in $G$.
I know an open ball is indeed an open set. I'm having trouble formulating the proof that if I have two points $a$ and $b$. I can form a polygon from $0$ to $a$ and another polygon from $0$ to $b$. Since both polygons share an endpoint, $0$, then they form one polygon.
How would I go about starting this proof?
Comment: I still think it's easier to work with paths than polygons. It also generalises better to non-open sets.
Comment: Do you mean "path" when you say "polygon"?
Comment: My text defines "A polygon from $a$ to $b$ is a set $P = \cup_{k=1}^n[z_k, w_k]$ where $z_1 = a$, $w_n = b$ and $w_k = z_{k+1}$ for $1 \leq k \leq n-1$ or $P = [a, z_2, ..., z_n, b]$
Answer: Why don't you simply join $a$ and $b$ with a segment?
Let $a,b\in B(0,1)$ the $t\to ta+(1-t)b$ for $t\in [0,1]$ is a parametrization of the segment that joins $a$ and $b$. All the points along this segment are inside $B(0,1)$ because for all $t\in [0,1]$,
$$|ta+(1-t)b|\leq  t|a|+(1-t)|b|< t\cdot 1+(1-t)\cdot 1=1.$$
Comment: @Zed1 Any further doubt?
Comment: Not at all. I knew that there was a way to connect the two points without going through the centre, but I wasn't sure how to go about it. Thank you.


Scheduling a native alarm/timer

Question: I'm using Ionic Framework to build an Android/iPhone cookbook app with Angular.
One of the features should be alarms/timers for each ingredient/step.
Ionic is based on a wrapper around Apache Cordova, I guess. So I've tried using a Cordova plugin, from an answer below... but it's older and it's not specifically for Ionic, and I've tried a few times but it just hasn't worked for me.  I haven't found any alternatives.
  doSomething() {

    let successCallback = () => window.confirm('success');
    let errorCallback = () => window.confirm('fail');

    // set wakeup timer
    (<any>window).plugins.wakeuptimer.wakeup(successCallback,
      errorCallback,
      // a list of alarms to set
      {
          alarms : [{
              type : 'onetime',
              time : { seconds  : 5 },
              extra : { message : 'json containing app-specific information to be posted when alarm triggers' },
              message : 'Alarm has expired!'
          }]
      }
    );
  }

Local notifications are kind of an option, but it's just a notification. It doesn't work like a native alarm clock. (It's like getting a text, but you miss it so your burgers burn.)
Can anyone give an example of an alarm or timer in a modern Ionic app? Maybe I'm just missing something to get the plugin to work?
Or is there any kind of alternative I'm missing?
I'm getting bummed that the app is almost done but I've been stuck on this. :(
Comment: it's too broad. Which framework are you working on? Any codes?
Comment: edited to clarify. sorry, the framework was in the tags.
Comment: can you take a look on https://bitbucket.org/aspiringapps/home-alarm-and-security/src/master/
Answer: You need an alarm plugin. this one can work:
https://github.com/Haggus/cordova-plugin-wakeuptimer
to set an alarm :
// set wakeup timer
window.wakeuptimer.wakeup( successCallback,
   errorCallback,
   // a list of alarms to set
   {
        alarms : [{
            type : 'onetime',
            time : { hour : 14, minute : 30 },
            extra : { message : 'json containing app-specific information to be posted when alarm triggers' },
            message : 'Alarm has expired!'
       }]
   }
);

Comment: Looks useful, thanks, but I haven't been able to get it to work with Ionic... I've updated the question
Answer: The plugin you are attempting to use is almost 5 years old. Older than Ionic 2
if you using Ionic v3 and you try to install the plugin will return this erore

so the best solution for you use Local Notifications
Good luck.
Answer: As Younes Zaidi already mentioned in his answer, the cordova-plugin-wakeuptimer (originally from wnyc, Haggus just did a fork) is old, no longer actively maintained and fails to install.
I managed to get it to work though (for Android only! - I haven't tried iOS at all - maybe it works maybe it doesn't), so if you still want this, continue reading ;-)
The install error is partially due to the lack of a package.json in the repository and partially to some general problems that cordova seems to have with installing packages directly from GitHub.
There has been a lot of ranting on several sites about this - see for example https://github.com/Telerik-Verified-Plugins/ImagePicker/issues/55 <- The comments there also include some suggestions on how to solve this & references to the respective cordova versions.
I myself have solved it by using scripts that manipulate my app's package.json and config.xml. (This "solution" is available as a docker-compose project if you want to see it work before going into the trouble. Just go to https://github.com/lentschi/expiry_sync & there follow the "Building app & server with docker" part - or, if you don't want to execute it, view the two aforementioned files and see what I do here: setup/app/build_scripts/build-android-dev.sh)
However: This only worked until Android 10 came out - this now requires a special permission granted by the user. See the details @android.com.
So I created a fork of the original cordova-plugin-wakeuptimer supporting this, which I will not maintain - see the README there on how to request the required permissions:
https://github.com/lentschi/cordova-plugin-wakeuptimer

Scheduling a native alarm/timer


How to log an index of an array in JavaScript?

Question: This question is more of a why does this particular code work this way than a how can I make this code work this way.
Im going through the codecademy tutorials for JavaScript and I came across a lesson that I conceptually can make use of in my own code because I can see the pattern of this particular code - but it doesn't make sense why this code works this way.
Below is an example:
let myArray = ['First','Second','Third'];
var last = myArray[myArray.length - 1];
console.log(last);

The console displays "Third" when running the above code. I know the JavaScript language is a "zero indexed" language and I know that "first" in this array would be position "0" counting from left to right but my question is even if we start at "0" and count every item; 0 then 1 then 2; shouldn't the console log "Second"
instead of "Third"? Or does the method of "length" in JavaScript ignore the "0" based indexing system and actually start counting at "1"; in witch case the answer should STILL be "Second" and not "Third"... No matter how my brain adds this up I keep getting "Second" instead of "Third" in my mind even though the output is "third" on the console...
Can anyone explain what I'm missing?
Comment: knowing that `myArray.length - 1 == 2` ... now what do you think ... the length is the length, which is 3 ... not 2, because there are 3 elements ... the index is zero based, the length is ... well, the length
Comment: index : `0, 1, 2` still has length of `3`
Answer: Try this code out and it will help. This stuff was tricky for me too. It's just using a variable and calculating it at the same time.
let myArray = ['First','Second','Third'];
var last = myArray[myArray.length - 1];
console.log(last);

First, we have to note that myArray.length is 3 because there are 3 items in it.
Second, now we can re-analyze this but exchange myArray.length with 3:
myArray[3 - 1]

Now, you can see it is simply calculating 3-1, which is 2, so the code is identical to:
myArray[2] // which returns the item at position 2 (starting from 0), [0, 1, 2]

Comment: It's also tricky sometimes to see object properties similar to this. You might see `object.name`, or you might see `object['name']` and where it gets tricky is sometimes you see variables in there, like `object[something1 + something2]` which is "concatenating" (ie: smashing two things together), so it's actually `object.something1something2`. Those typically show up as `object['something' + i]` (where `i` is an iterator number that goes up).
Comment: Note you can also use `myArray.indexOf('Third')` to find the position of the thing you want.
Comment: ok I see, yes that makes perfect sense, I think my problem was i was conceptually trying to get an answer without first breaking it into two separate steps (like your example), Now i see it clearly. THANKYOU
Answer: array.length is a number of items in it, there are 3 items. But array indexes starts from 0 and the last index will be 2, not 3. So if you want to get array element using array.length, you need to decrease this length by 1 if you want to get the last element, by 2 if you want to get the previous one and so on.
Answer: Array.length returns the number of items in an array. It has no bearing on the index.
Length - 1 will always be the final index in array though, simply because arrays are 0 indexed in practice.


Why was Le Concert Spirituel playing out of tune at Proms 2012?

Question: I know it sounds like an odd question, but I was listening to a recording of Handel's music for the Royal Fireworks (available here on Youtube), and there are sections where the horn players are playing noticeably out of tune, such as here, especially at 7:15.
I notice that they are also using either very old instruments or replicas of such: is the missed intonation a consequence of the instruments not having the same capacities for intonation as modern instruments?
The performance is supposed to be by Le Concert Spirituel at Proms 2012, which is a prestigious enough event and orchestra that I very highly doubt that it's simply a lack of practice.
Answer: You are right, it is because they are using very old horns known as natural horns which had no valves or holes. They had known limitations and were quite difficult to play. You can see and hear a natural horn here:

Here is an excerpt from a review of the show which mentions it:

However, because they were playing on historical "natural" horns (i.e. with no valves or holes), the tuning was often at odds with the string section, which came as a bit of a shock to modern ears. In the second suite, the antiphonal effect of the trumpets and horns was spectacular despite some ensemble problems – nine horns or nine trumpets playing completely in unison is difficult even on modern instruments – of course, one may argue that this was a part of the historical charm.

Source: Bachtrack
Here is an excerpt from the Wikipedia page on natural trumpets which gives interesting information about the decline of natural instruments:

Baroque composers—such as Antonio Vivaldi, Georg Philipp Telemann, George Frideric Handel and Johann Sebastian Bach—made frequent use of trumpets in sacred, orchestral, and even solo works. Many of these trumpet parts are technically quite difficult to play on a natural instrument, and were often written with a specific virtuoso performer in mind, such as Gottfried Reiche (Bach's chief trumpeter and the subject of a famous painting of the era) or Valentine Snow, for whom Handel composed some of his more noted trumpet parts. Indeed, highly skilled trumpeters were a prized commodity in the era, held in high esteem and avidly sought after by musical patrons.
The vast majority of baroque trumpet parts were written for a natural instrument pitched in C or D, although there were occasional exceptions. J.S. Bach, for example, calls for a trumpet in B♭ in his Cantatas Nos. 5 and 90, trumpets in E♭ in the first version of his Magnificat and, most famously, the solo trumpet in high F in his Brandenburg Concerto No. 2. In the 18th century various attempts were made to overcome the limitations in the notes available to natural trumpets. As early as the time of Bach, crooks (additional lengths of tubing) were introduced between the mouthpiece and the body which lowered the pitch of the instrument and allowed it to be used in a variety of keys. In the latter part of the 18th century side holes covered with keys and a sliding mechanism were tried. Later Anton Weidinger, court trumpeter in Vienna, invented a 5-key trumpet. These experiments were not completely successful, however, since side holes, which work well on instruments with a conical bore, such as cornets and bugles, cause a muffled sound in those with a cylindrical bore.
Natural trumpets continued to be used through the Classical era and even into the early Romantic period. But changing musical styles along with a growing dearth of sufficiently capable players spelled an end to the high, florid, complicated parts typical of baroque music. A few transitional composers, such as Michael Haydn, Leopold Mozart and Johann Molter wrote concerti for natural trumpets in the early Classical era. In fact, it could be argued that the concertos of Haydn and Molter represent the zenith of the natural trumpet in terms of technical demands, containing as they do some of the highest notes ever penned for the trumpet in symphonic works (in the case of Haydn, a G above high C - the 24th harmonic on a natural instrument).

Source: Wikipedia
Dr. John Ericson of Arizona State University wrote a book on the subject and made the video above. Here is an excerpt from an article he wrote on the technique involved in playing a natural horn, which can be observed in the video.

Modern brass instruments generally possess better intonation than comparable early instruments due both to their more efficient internal tapers and the avoidance, through the use of valves, of the most out of tune harmonics, which had to be used on the natural horn to obtain a complete scale.
Players discovered that by inserting the hand into the bell of the horn they could alter the pitch of the instrument for improved intonation and additional pitches, and that they could also make the tonal color darker and more mellow.

You can find the complete article here.
Answer: The passage in question has natural trumpet as well as horn which will make intonation more difficult or even impossible.
On a horn, the hand can be used to adjust the pitch, but you cannot do this on a natural trumpet. It is possible to adjust the pitch slightly with the lips, but this can only go so far. You can probably correct the B flat and D harmonics, but the written F will always be sharp on the natural trumpet. The passage in the clip uses this F quite a lot, thus highlighting the intonation problem.
A solution using vent holes that can be opened to correct the out of tune harmonics was developed and a lot of modern replicas have these, but the original instruments and truest period replicas may not.
If the F on the trumpet cannot be flattened the decision may be taken that the same note on the horn should also remain sharp so that the whole brass section tuning is consistent.
Answer: I agree with you about the horns being somewhat out of tune in places here. Not the best advert to turn people on to this genre of performance.  However, intonation on period instruments is a lot harder work than on modern ones and that's one of the reasons why they evolved as they did.


What are methods available for solving 3rd ODE directly without reducing to a 1st order system of IVP?

Question: I have came across the questions: 1, 2, 3.
In these questions you can see different third order ordinary differential equations (ODEs):
$$y'''=f( x, y, y', y''), y(a)=y_0, y'(a)=y_1, y''(a)=y_2.\text{ }(1)$$
As I know a third order equation is rare situation on practice.
I know the Abraham–Lorentz–Dirac–Langevin equation only.
Edit.
@Matt gives the link on the KdV equation.
I have found the 3rd ODE which arises in modeling draining or coating fluid flow problems.
Question
What are symbolic and numerical methods available for solving 3rd ODE directly? i.e. without reducing to a 1st order system of inital value problem (IVP)?
Currently, I have found the linearizing tangent transformation which leads the equation (1) into the linear second-order ODE.
Comment: There are lots of different numerical methods for solving any order ODE. Two that spring to mind are the finite difference approach and spectral methods.
Comment: You have changed the question so that Matt's response is no longer a  valid answer to the changed question. Please do not do this.
Answer: A very famous 3rd order equation is the KdV equation.
This equation describes shallow water waves.  If you look for traveling wave solutions (keeping the same shape and fixed velocity), then the PDE transforms to a 3rd order ODE.
Comment: thanks for the answer, I have updated the question.


Qual seria o formato dos dados trafegados por um web service SOAP?

Question: Em web services que usam a arquitetura REST, o formato dos dados que é trafegado pela rede é XML ou JSON, em alguns casos podem ser ambos. No entanto, eu não sei qual é o formato dos dados que são trafegados em um web service SOAP.
Sendo assim, eu gostaria de saber qual seria o formato dos dados trafegados pela rede através de um web service SOAP?
Comment: Alguma sugestão de melhoria na pergunta downvoter?
Comment: Segue uma [pergunta](https://pt.stackoverflow.com/questions/11183/quais-as-principais-diferen%C3%A7as-entre-soap-rest-xml) com conteúdos interessantes a sua dúvida.
Answer: Um web service SOAP trafega XML
Mais info aqui: https://www.w3schools.com/xml/xml_soap.asp

A SOAP message MUST be encoded using XML

Ou seja, as mensagens SOAP trafegam sempre em XML

A SOAP message is an ordinary XML document

Ou seja, sempre um documento XML.
Aqui, o esqueleto básico de uma mensagem SOAP e seu formato:
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope/" soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">
  <soap:Header>
     ...
  </soap:Header>

  <soap:Body>
     ... Aqui vai o corpo da mensagem em XML
    <soap:Fault>
       ...
    </soap:Fault>
  </soap:Body>
</soap:Envelope>

Comment: A especificação do protocolo realmente fala que a mensagem deve ser no formato XML. Porém só para colocar lenha da fogueira: https://en.m.wikipedia.org/wiki/SOAPjr  (Ok até dá para argumentar que SOAPjr não é SOAP). Já vi algumas coisas absurdas também, do tipo um corpo "XML" com um único campo CDATA e algum outro formato completamente louco (e.g., arquivo posicional) como conteúdo. Novamente dá para argumentar que isso é XML válido, mas...
Comment: Só a referência que não é confiável. `w3schools` é considerada uma ótima piada, onde você tentava contar quantos erros existiam em uma página aleatória que você abria
Comment: Ah, também não é qualquer xml que pode ser trafegado. Dentro do xml, tem um formato específico
Comment: @hugocsl a parte mais relevante do link foi incluída na resposta *"A SOAP message MUST be encoded using XML"*
Comment: Apena fiz a Revisão, mas já removi, considerando a sua Edição da resposta.


Traduzindo plugin wordpress

Question: Estou tentando traduzir uma frase no Plugin UT Portfolio, fui na pasta do arquivo e tem somente um arquivo .txt avisando que a tradução deve ser feita pleo plugin codestyling localization, porém já ao abrir ele apresenta este erro de permissão, como proceder?
Minha hospedagem é umbler.
Answer: Esse plugin funciona reescrevendo os arquivos .po e .mo que contém as traduções. Muitos servidores não permitem escrever arquivos pelo CMS pelos riscos de segurança.
Você pode alterar esses arquivos diretamente usando um editor como o PoEdit.
Procure na pasta do plugin uma pasta "languages" ou "lang" e os arquivos .po ou .pot. Baixe para o seu computador, abra nesse programa e altere as traduções que quiser, depois salve para gerar novos arquivos e suba para a mesma pasta no servidor.
Comment: Possui uma pasta chamada lang dentro do plugin, porém não contem nenhum arquivo .po ou .pot, apenas um readme.txt mandando baixar o plugin de tradução que citei no tópico =/

Efetuei o download do programa e tentei traduzir o .po original do wordpress, imaginei que talvez eles teriam alterado ou algo assim.. porém estava 100% traduzido...
Comment: Não me lembor bem o nome do comando, mas o PoEdit tem uma função de ler o codigo do plugin e criar o arquivo `.pot`, ai a partir dele você poderia traduzir.

Traduzindo plugin wordpress


Switch site language after IP to locale redirect

Question: I have a Multilingual Drupal 7 website. using i18. I redirect my visitors based on IP address with IP to locale module. Now e.g. visitors from Holland (Dutch IP) are redirected to http://landberg.at/nl
But now I am not able to select another language, with my language switcher? E.g an English person who lives in Holland must be able to switch to the English version. http://landberg.at/en
How do I have to achieve this? Is this anyway possible with language redirect based on IP?
(currently on my site I switched IP 2 locale OFF)
Comment: Is this for D6 or D7? Consider editing your question to clarify that ...
Comment: A Drupal 7 website.
Answer: You have tried Language Switcher module but you are not getting any result. Once try to use Language Switcher Dropdown module.

Language Switcher Dropdown is a very simple module that exposes a new
  block, similar to the default Language Switcher block provided by
  Locale module. The new block allows site visitors to switch languages
  using a drop-down select list instead of using hyperlinks.
Comment: i just tested it but it doesn't make a difference. Still after redirect your not able to switch language. You can test it [here](http://landberg.at/).
Comment: I have just check, Default English is showing. When I click on German, it redirect to English but when I select Dutch it redirect to Nederland & page url is change to 'http://landberg.at/nl'. I think your language selection configuration inside `Configuration -> Languages -> detection and selection` is wrong. Please check.
Comment: Thanks i have now inside `Configuration -> Languages -> detection and selection: -URL -Standaard` But if i enable: `-URL -User -Standaard` I get in my browser an error: ERR_TOO_MANY_REDIRECTS –
Answer: Consider a special patch
Your issue seems fairly similar to what is described in Patch for language switcher to override ip2locale. It is for D6 though (not sure what this question is for D6 or D7 ... I think D7). Not sure if you want to consider exprimenting with the patch attached to it (attention: status of the issue is "needs review").
Check language detection
It seems to me that you should check your configuration at Configuration -> Languages -> detection and selection: the order specified there could be what explains the current behaviour in your site.
You'd have to experiment a bit with what the exact order in your case should be. In my experience, I often get these kind of issues to work by using an order like 'URL, Default, User', and not something like 'Default, URL, User'. It could well be that that is all that's needed here ... So try to experiment a bit with the various combinations in this order to see if it helps.
Curious to hear what the result of checking this will be ...
Comment: Thanks i have now:
-URL
-Standaard

But if i enable:
-URL
-User
-Standaard

I get in my browser an error:
ERR_TOO_MANY_REDIRECTS


Mysterious "Page not found" on every page load for authenticated users

Question: I recently migrated my site to a new server, and restructured the urls, etc... so naturally there are quite a few 404's out there from other sites linking to old content. So far, so normal.
But among the page not founds, I'm getting something really bizarre: as far as I can tell, every single page load of the site by authenticated users is generating one particular "page not found" error for a file at location sites/default/files/stripes54-navywhite.jpg.

Every page load for every authenticated user.

Now this file does not exist. Nor are there any links on the site to it (the file name is familiar: we may have had a file at that location at some point in the past, on the old site).
I have searched page source, I have searched through the contents of all my site files, I have searched my complete db using phpmyadmin. There is no reference to this file anywhere, as far as I can tell.
So what could possibly be causing this? Where is this file mysteriously being referenced? Watchdog is giving me no help here.
My only clue at the moment is that this page not found seems to ONLY be triggered by authenticated users: not seeing any anonymous users triggering it.
Does anyone have any earthly idea what might be going on here? A big thanks to anyone who can help!
I'm even getting this error generated by admin pages, which use a separate admin theme. For example, when browsing my database log.

There is one entry in the file_managed table where origname is stripes54-navywhite.jpg. Unfortunately, this doesn't really shed much light on the problem.
Comment: When you are searching for content search by parts, search for navywhite only you might get something in content.
Comment: Okay, there is one entry in file_managed db table where origname = stripes54-navywhite.jpg (see [phpmyadmin entry](http://i.imgur.com/9Zo4p.png). Unfortunately I don't think this sheds much light on anything...
Comment: Ok that pic was uploaded from content/user profile perhaps. To debug : shortest way : 1 : upload a dummy pic of same name, see if pic comes up in front, dig deeper to check the module/content assosciated with it : 2 : Check corresponding file_id check node/content tables for that file_id. EDIT : Saw the image now, does that value in URI column ring any bells ?
Comment: Checked fid, current uri, nid, etc... still nothing. That node exists, and that file exists, but there's still nothing at sites/default/files/stripes54-navywhite.jpg, and still nothing linking there...
Comment: Did you try uploading a pic with same name ? Try this if it comes up in front end then you can debug further.
Comment: What do you mean by "comes up in front"? Thanks for your help.
Answer: After further investigation, this appears to be an issue with CloudFlare. Disabled it, and the problem went away... re-enabled it, and the problem returned, but with a different image url!
Yet further investigation shows Cloudflare's Website preloader to be the culprit. So nothing to do with Drupal.


Best system to store sheet music when in use

Question: I need a system that I can use to store sheet music that I am currently learning and/or performing. To clear up, I need some sort of folder or display book that will let me store multiple pages of sheet music at once whilst still being able to read and make notes on. This system can be solely for sheet music or another type of folder or be another type of folder that will store A4 sheets. I don't care if I have to buy a folder as well as tabs, I just need to be able to read the sheets clearly and edit them when need being.
I need to use the folder at home while learning or playing a song and on stage.
Comment: An ordinary ring binder does the job. Questions about equipment recommendations are usually not allowed here.
Comment: Questions seeking recommendations for equipment are considered off topic here. You can reword your question to ask about what features you should look for or other related things. Asking about the "best" on is not on topic though.
Comment: Note that looking for opinions specifically is normally not on-topic either. Looking for general advice and facts about storing sheet music **is** definitely on topic, although I think that might be a duplicate.
Comment: For writing on... ring binders are good as Tim suggests. On my digi piano I need something lighter so I use a couple of plastic office clipboards which slot in the top - good for writing on too. Sheet changes are clumsy with these though unless you have spares.
Comment: What's wrong with using the original sheet musiccopy and a soft pencil?
Comment: By the way I thought this was a question not for recommendations, but looking for opinions on how in general to handle loose sheets while practicing, performing or writing. Agree it probably needs an edit by the questioner to make it clear and get the question on topic.
Comment: @ToddWilcox I think "opinions" comprise a majority of the content on this site.  Hopefully educated opinions from folks who are very knowledgeable.   The "rules" seek to avoid questions which can't be answered on a factual basis and are ONLY going to generate opinions and end up looking like a debate with no definitive answer - and perhaps much disagreement. There are thousands of questions (many very highly rated) that solicit "opinions".  "Best system" in the heading 4 this question is the 'best' way to define the question which is really "What systems have been used to ... and will also..?"
Comment: @ToddWilcox Your right - it seems like there was a very similar question recently - only without the expressed desire for an ability to make notes at will on the music.
Comment: @RockinCowboy Yes, it is a slightly different question: http://music.stackexchange.com/questions/34711/best-ways-of-storing-sheet-music
Answer: I have always used a good old-fashioned 3 ring binder and that does the trick. Easy to store, transport and keep music organized. I organize by composer last name, then by song name to keep it easy. In a 3 ring binder, it's also easy to make a quick notation on the music, which isn't as easy if you have them in a plastic protector or on some sort of tablet. Good luck!
Answer: Apart from obvious solutions, it may be possible to use scanner together with tablet. Scan the sheet music and keep the content on the tablet. A single tablet uses up very little space, is easy to put on then note holder and can contain lots of scanned material.
The negative side is that it is more difficult to read from the tablet and only one page is visible at time. Hence it is more suited to store something you already know well and just need a slight reminder on how the notes go.
Also, buying scanner and tablet just for this purpose looks expensive and may have some learning curve (how to scan, how to transfer to the tablet, etc).


Mudar cor de cardview e text de uma listview

Question: Tenho uma listview com uma card view e dentro da card view tenho dois text, eu sei como ativar o contextual action bar quando der long press na list view e como alterar a cor do text e do cardview, porém não sei como alterar a cor do cardview e text especificadamente no item da listview que foi pressionado... Como detectar o item exato que foi pressionado e alterar somente os widgets que estão dentro deste item da listview?
Eu tentei no adapter, mas ele altera a cor de outros itens...
@Override
        public void bindView(View view, Context context, Cursor cursor) {
            TextView textClipper = (TextView) view.findViewById(R.id.clipperTextView);
            TextView textDate = (TextView) view.findViewById(R.id.dateTextView);

            cardView = (CardView) view.findViewById(R.id.clipperListCard);
            cardView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if(cardView.isSelected()){
                        cardView.setSelected(false);
                        cardView.setCardBackgroundColor(Color.WHITE);
                        Log.i("CARD VIEW", "Esta selecionada!");
                    }else{
                        cardView.setSelected(true);
                        cardView.setCardBackgroundColor(Color.BLUE);
                        Log.i("CARD VIEW", "Não está selecionada!");
                    }

                    return false;
                }
            });

Eu tentei usar selector do xml para alterar a cor quando pressionado, porém não funciona para o Card, pesquisando vi que é um bug que existe desde 2014 e até hoje me parece que não foi resolvido... Ele simplesmente ignora para o Card, mas para outros widgets funcionam...
Edit:
Não estou conseguindo fazer aqui... Alterei algumas coisas mas ele não responde ao OnItemLongClickListener.
XML que é jogado na listview:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="@dimen/clipper_listview">

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/clipperListCard"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="4dp"
        android:layout_margin="@dimen/cardview_listitem_margin">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:id="@+id/cardListLinear"
                android:layout_margin="@dimen/cardview_content_margin">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="Clipper text"
                android:id="@+id/clipperTextView" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Data - hora"
                android:id="@+id/dateTextView"/>

            </LinearLayout>

            <CheckBox
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true"
                android:layout_centerInParent="true"
                android:id="@+id/checkBox2" />

        </RelativeLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

Activity ta tab onde tem o listview:
public void gerarListView(View view){
        clipperListView = (ListView) view.findViewById(R.id.clipperListView);
        TClipper tClipper = new TClipper(view.getContext());
        Cursor cursorClipper = tClipper.getClipperAllLimit();
        final ClipperAdapter clipperAdapter = new ClipperAdapter(view.getContext(), cursorClipper, 0);
        clipperListView.setAdapter(clipperAdapter);
        clipperListView.setDivider(null);
        clipperListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        clipperListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
            //chamado cada vez que um item for selecionado
            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
                int qtItemSelected = clipperListView.getCheckedItemCount();
                mode.setTitle(getResources().getQuantityString(R.plurals.selected_items, qtItemSelected, qtItemSelected));
            }

            //chamado a primeira vez que o action for criado
            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                MenuInflater menuInflater = mode.getMenuInflater();
                menuInflater.inflate(R.menu.menu_tab1_contextual, menu);
                return true;
            }

            //é chamado quando a action é invalidate()
            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            //quando algum item da action for clicado
            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {

                switch (item.getItemId()) {
                    case R.id.action_card_remove:
                        Log.i("ACTION", "Menu clicado remove");
                        break;

                }
                mode.finish(); //fechar a action
                return true;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {

            }
        });
        clipperListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                CardView cardView = (CardView) view.findViewById(R.id.clipperListCard);
                if(cardView.isSelected()){
                    cardView.setSelected(false);
                    cardView.setCardBackgroundColor(Color.WHITE);
                    Log.i("CARD VIEW", "Esta selecionada!");
                }else{
                    cardView.setSelected(true);
                    cardView.setCardBackgroundColor(Color.BLUE);
                    Log.i("CARD VIEW", "Não está selecionada!");
                }
                clipperListView.setItemChecked(position, true);
                Log.i("LIST VIEW", "LONG CLICK");
                return false;
            }
        });
    }

Adapter:
private class ClipperAdapter extends CursorAdapter {

        public ClipperAdapter(Context context, Cursor c, int flags) {
            super(context, c, flags);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            return LayoutInflater.from(context).inflate(R.layout.clipper_main_listview, parent, false);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            //if(view==null) {
                TextView textClipper = (TextView) view.findViewById(R.id.clipperTextView);
                TextView textDate = (TextView) view.findViewById(R.id.dateTextView);
                CardView cardView = (CardView) view.findViewById(R.id.clipperListCard);
            //}

            textClipper.setText(cursor.getString(cursor.getColumnIndexOrThrow(ClipperDbContract.ClipperTable.TABELA_COLUNA_TEXT)));
            textDate.setText(
                    cursor.getString(cursor.getColumnIndexOrThrow(ClipperDbContract.ClipperTable.TABELA_COLUNA_DATA)) + " - " +
                            cursor.getString(cursor.getColumnIndexOrThrow(ClipperDbContract.ClipperTable.TABELA_COLUNA_HORA))
            );
        }
    }

Answer: Felipe
A idéia inicial que tive não vai funcionar pois você está usando o list view no mode multiple_modal.
Então, vamos fazer o seguinte:
Na Activity:
Remover o clipperListView.setOnItemLongClickListener()
O Long Click não funcionar por aqui pois você está usando multiple mode modal.
No Adapter:
Eu adicionei mais lógica para atingir o seu objetivo.
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ClipperAdapter extends CursorAdapter {

    private ListView mListViewParent;

    public ClipperAdapter(Context context, Cursor c, int flags) {
        super(context, c, flags);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        if(mListViewParent == null)
            mListViewParent = (ListView) parent;
        return LayoutInflater.from(context).inflate(R.layout.list_view_row, null);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        final int position = cursor.getPosition();

        TextView textClipper = (TextView) view.findViewById(R.id.clipperTextView);
        TextView textDate = (TextView) view.findViewById(R.id.dateTextView);
        CardView cardView = (CardView) view.findViewById(R.id.clipperListCard);

        /*
            SET TEXT AND COLORS AND TAG FOR LATER USE
         */
        cardView.setTag(position);
        if (( mListViewParent).isItemChecked(position)) {
            setSelectState(cardView, true);
            ( mListViewParent).setItemChecked(position, true);
        } else {
            setSelectState(cardView, false);
            ( mListViewParent).setItemChecked(position, false);
        }

        textClipper.setText(cursor.getString(cursor.getColumnIndexOrThrow(ClipperDbContract.ClipperTable.TABELA_COLUNA_TEXT)));
        textDate.setText(
                cursor.getString(cursor.getColumnIndexOrThrow(ClipperDbContract.ClipperTable.TABELA_COLUNA_DATA)) + " - " +
                        cursor.getString(cursor.getColumnIndexOrThrow(ClipperDbContract.ClipperTable.TABELA_COLUNA_HORA))
        );

        /*
            SET CLICK LISTENER
         */
        cardView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                int position = (int) view.getTag();
                if ((mListViewParent).isItemChecked(position)) {
                    setSelectState(view, false);
                    ( mListViewParent).setItemChecked(position, false);
                } else {
                    setSelectState(view, true); // Creating view. If selected, keep it selected
                    ( mListViewParent).setItemChecked(position, true);
                }
                return true;
            }
        });
    }

    private void setSelectState(View cardview, boolean select) {
        if (select) {
            cardview.setSelected(true);
            ((CardView) cardview).setCardBackgroundColor(Color.BLUE);
        } else {
            cardview.setSelected(false);
            ((CardView) cardview).setCardBackgroundColor(Color.WHITE);
        }
    }
}

Comment: mas no caso estou usando CursorAdapter, e ele não tem getView, no lugar é bindView, o bindView não tem position
Comment: @felipe.rce Com um CursorAdapter você terá de ter um campo na tabela que indique se está ou não seleccionado. No `bindView()` mude a cor do CardView em função dele.
Comment: @felipe.rce Compartilhe o seu adapter, a sua activity e xml que é inflado pelo adapter.. Dai, eu atualizo a respotas baseado no seu código fonte... Compartilha só o que for necessário e tal... não precisa compartilhar o código todo
Comment: @GuilhermeP editei a pergunta e coloquei as novas edições que fiz... Apenas removi o código da cardview que estava no bindView e mandei para o OnItemLongClickListener, mas ele nem entra no OnItemLongClickListener... Tentei por apenas o Log.i para testar, e ele não entra...
Comment: Tenta colocar isso no xml do listview: android:longClickable="true" e mantenha o log na função... pra vc ter certeza que foi chamada
Comment: Tem um outro porem no seu código. Na list view, as views são reutilizadas. Então, vc não pode usar elas para determinar se aquela posição já está seleciona ou não... Vc precisa manter essa info separada... vou atualizar o código para vc entender a idéia
Comment: @GuilhermeP coloquei android:longClickable="true" e deu no mesmo, não está entrando no longclick
Comment: @felipe.rce acho que seu o motivo. Como você está usando um listview com multiple mode, dessa forma, acho que o long click não vai funcionar... Vou trabalhar aqui de novo e compartilho algo depois


IE9 is ignoring X-UA-Compatible flag for UserAgent

Question: I've an internet Application, so the IE9 is per default in the Compatibility View. I use the X-UA-Compatible flag.
I sent it in the HTTP Header and as Meta-Tag.
IE9 seems to accept it and use the IE9 rendering engine. But its still always sending the IE-7 UserAgent string.
Is there any way to avoid it, or to identify this IE9 as a not IE7 browser?
I really dont want to use a whitelist of browsers, but a blacklist of not-supported browsers (IE 5, 6, 7 & 8).
My example:
I'm opening the page so the IE9 is sending an an GET request:
GET http://myserver/mypage/ HTTP/1.1
Accept: application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg,     application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Accept-Language: de-CH
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3; .NET4.0E)
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Host: myserver
Cookie: MAKEBROWSERTEST=true

Then, my server is answering:
HTTP/1.1 302 Found
Cache-Control: private, no-cache="Set-Cookie"
Content-Type: text/html; charset=utf-8
Location: /myserver/mypage/two
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
Set-Cookie: MAKEBROWSERTEST=true; path=/
X-UA-Compatible: IE=edge
Date: Tue, 11 Sep 2012 10:04:21 GMT
Content-Length: 152

<title>Object moved</title>

Object moved to here.

The IE9 is redirecting, but still sending the MSIE 7.0 User Agent:
GET http://myserver/mypage/two HTTP/1.1
Accept: application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Accept-Language: de-CH
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3; .NET4.0E)
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Host: myserver
Cookie: MAKEBROWSERTEST=true

Thanks
Comment: Actually IE renders the page according to the X-UA-Compatible setting. It just follow the order of its user by requestig an IE7 page but after receive the X-UA-Compatible it works as the tag asked. Jut try `JSON` in console (witch is not available in IE7 mode) and you will see that works.
Comment: Thats true! For the rendering it looks on the X-UA-Compatible setting, but not for the User-Agent String even when I sent the X-UA-compatible flag before. This does matter for me, because I want to make a 302 request depending on the Browser Version! Currently I see no way to do this!
Comment: Maybe you can make some assumptions based on the Trident version. Looks like it is consistent with the browser version.
Comment: If u have checked my question u would see that the user agent string is exactly the same before and after I sent the X-UA-Compatible flag! So also the trident version is identical!
Comment: If the site is already in compatibility view before you add the meta tag, then the user agent string CANNOT be forced out of compatibility view. The page will appear to be rendered in the modern browser, but in the background the agent string is still IE 7. [I blogged about this exact issue](http://frankcode.net/2013/10/17/a-guide-to-ie-compatibility-view-and-x-ua-compatible/).
Answer: I'm not trying to revive an old thread, but if anyone comes across this, they might find this interesting:
Internet Explorer 11's Many User-Agent Strings

If the user chooses to render a site in Compatibility View (click Tools > Compatibility View Settings) then IE will send a User-Agent string that mimics Internet Explorer 7's UA string:

Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; Trident/7.0; .NET4.0E; .NET4.0C)

By default, sites in the Intranet Zone render in Compatibility view, so this is the User-Agent string they'll see.
So I did a test with IE9:
In (normal mode) you get
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)

In compatibility mode you get
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)


Inapp browser cordova not opening

Question: Here is my code it's not complicated and it was working before, but now the app isn't loading the in app browser unless i tap on the button (it's in a ontouchstart) and then  exit the app (run in background) then open the app.
<code> var ref = cordova.InAppBrowser.open("https://www.google.com", "_blank", "location=yes");
</code>
What could cause this to happen? it only happens on ios
Cheers
Comment: Try to run your code after a period of time using JavaScript setTimeout , and make sure the code is after you reference of cordova.js file.
Comment: its well after all that i mean im in the middle of the app everything has loaded in.
Answer: InAppBrowser is currently having problems with IOSX as they have changed the CSP.
Solution is to add "content="default-src 'self' gap://ready" under your meta tag meta http-equiv="Content-Security-Policy" in index.html
More info:
https://github.com/driftyco/ionic/issues/6928

Inapp browser cordova not opening


D6 - Create a files table entry for a file

Question: I have to migrate some content and everything is fine except the images.
I'm getting the images using file_get_contents() and save the file in the drupal /files folder using the following code:
    $image = file_get_contents('http://www.someurl.com/xx/util/yy.jpg');
    $file = file_save_data($image, 'yy.jpg',FILE_EXISTS_REPLACE);
    print $file; // returns the path to the file ( /files/yy.jpg )

So the image is uploaded in the /files folder.
What I'm not able to understand is, how can I add the image to the files table so that I can be able later to use the file object?
I was looking through the files.inc functions for Drupal 6 but I wasn't able to find anything that could help.
Should I insert the data manually using db_query()?
Thanks.
Answer: It's just done manually, e.g.:
$file = new stdClass();
$file->filename = 'foo.bar';
$file->filepath = $file;
$file->filemime = file_get_mimetype($file->filename);
$file->uid = $user->uid;
$file->status = FILE_STATUS_TEMPORARY;
$file->timestamp = time();
drupal_write_record('files', $file);

See file_save_upload() for a much broader example, including validation.


Connected three sheeted covers of $S^1 \vee T^2$

Question: I'm interested in finding $3$ sheeted connected covers of $X =S^1 \vee T^2$ where $T^2$ is the torus. We need to look at transitive actions of $\pi_1(X)\cong \Bbb Z \ast\Bbb Z^2= <a,b,c  \ |\ bc=cb> $ on $S_3$ mod conjugation.
I've been told that there are $7$ of them, but I'm counting much higher. For instance, supposing that
$a \mapsto (123)$
the only restrictions on the image of $b$ and $c$ are that they commute (since $a$ already mixes everything.)  Since conjugation is determined by cycle type, we could have the following:
$b \mapsto (123), \; c \mapsto (123)$ (Since $(123)$ and $(231)$ commute)
$b \mapsto (123), \; c \mapsto e$
$b \mapsto (12), \; c \mapsto 0$
This is already six since we can switch the roles of $b$ and $c$ (or is this the reason for overcounting?), and there are quite a few more since we can still map $a$ to $(12)$ and $e$.
Edit:
If $a \mapsto (12)$, then we could have
$b \mapsto (123),\; c \mapsto (123)$
$b \mapsto (123), \; c \mapsto e$
$b \mapsto (13), \; c \mapsto (123)$
$b \mapsto (13), \; c \mapsto e$
Which makes at least $8$, up to switching $b$ and $c$.
Comment: I assume there are $7$ up to isomorphism, so interchanging $b,c$ doesn't give distinct covers in that sense.
Comment: @CheerfulParsnip I have included more, and there are at least $8$ up to switching $b$ and $c$. Thank you for pointing that out.
Answer: I actually only found 6 connected covers up to isomorphism. First note that any connected finite sheeted cover of a torus is a torus. It follows that any finite sheeted cover of a torus is a union of tori. Suppose that our cover restricts to a connected cover of the torus. Then there are three preimages of the basepoint which need to be connected up by edges, and there are three distinct ways of doing so, listed in the top row of my picture. Similarly, we could have a two sheeted cover and a 1 sheeted cover, and there are two ways to connect them up. Finally, there you could have three one-sheeted covers of the torus, and there is a unique way to connect those up.
Comment: Thanks for accepting my answer! Do you have any idea how to reconcile the fact that I only found 6 with the suggested answer of 7?


Alterar cor de background e ligar todas as luzes das janelas quando for noite (apenas JavaScript)

Question: Estou estudando JavaScript e resolvi criar um projeto prático, o qual consiste em um prédio que posso ligar e desligar as luzes clicando nas janelas, até ai ok.
Porém queria implementar a função de clicar em algum botão e mudar de dia para noite e todas as luzes se ligarem automaticamente.
A parte de mudar de dia para noite consegui, clicando na própria tela, porém quando clico para ligar ou apagar alguma luz fica mudando de dia para noite também.
Tentei algumas funções e meio diferentes, mas fico travado nisso. Alguém poderia dar um help por favor?
HTML

    document.querySelectorAll('.ligaDesliga').forEach(divs => {
      divs.addEventListener('click', event => {
        divs.classList.toggle('yellow');
      })
    })

    let ambiente = document.querySelector('.day');

    function alterarHorario(){
      ambiente.addEventListener('click', alterar =>{
        ambiente.classList.toggle('night')
      })
    }

    alterarHorario();
*{
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        overflow: hidden;
    }

    .day{
        background-color: blue;
    }

    .night{
        background-color: black;
    }

    .container{
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 110vh;
    }

    .container .predio{
        display: flex;
        flex-wrap: wrap;
        align-content: space-between;
        justify-content: center;
        align-items: center;
        height: 560px;
        width: 250px;
        border: 2px solid white;
        background-color: gray;
        padding: 20px;
    }

    #window1, #window2, #window3, #window4, #window5, #window6, #window7, #window8, #window9, #window10, #window11, #window12{
        width: 85px;
        height: 60px;
        background: black;
        cursor: pointer;
    }

    #window2, #window4, #window6, #window8, #window10, #window12{
        margin-left: 10px;
    }

    .door{
        width: 40px;
        height: 80px;
        background-color: brown;
        position: relative;
        bottom: -18px;
    }

    .yellow{
        background-color: yellow !important;
        box-shadow: 0 0 10px yellow,
                    0 0 15px yellow,
                    0 0 20px yellow;
    }
    <!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <title>Desafio prédio</title>

Comment: você está associando um evento dentro de uma function, isso deveria ser feito fora dela, como o outro evento com a classe "ligaDesliga"
Comment: @RicardoPontual apliquei da mesma forma que o outro evento, porém quando está no modo night e clico em alguma luz para ligar fica alterando a cor de fundo também de dia e noite.
Answer: Use o ambiente.setAttribute('class', '...'); para alterar a cor de fundo. Você pode selecionar todos os elementos que possuem a classe yellow, e verificar se existe alguma elemento com essa classe fazendo um .length. Depois com um simples if, você decide se adicionaremos a classe day ou night dependendo se algum elemento ainda possui a classe yellow.
Veja o if dentro da função alterarHorario:
function alterarHorario() {
  ambiente.addEventListener('click', (alterar) => {
    const hasYellow = document.getElementsByClassName('yellow'); // retorna um array

    if (hasYellow.length) { // se houver alguem com a classe yellow
      ambiente.setAttribute('class', 'night'); // o tema de fundo será "night"
    } else {
      ambiente.setAttribute('class', 'day'); // se não houver ninguém com a classe
                                             // "yellow", o tema será "day"
    }
  });
}

O código funcionando:

document.querySelectorAll('.ligaDesliga').forEach((divs) => {
  divs.addEventListener('click', (event) => {
    divs.classList.toggle('yellow');
  });
});

let ambiente = document.querySelector('.day');

function alterarHorario() {
  ambiente.addEventListener('click', (alterar) => {
    const hasYellow = document.getElementsByClassName('yellow');

    if (hasYellow.length) {
      ambiente.setAttribute('class', 'night');
    } else {
      ambiente.setAttribute('class', 'day');
    }
  });
}

alterarHorario();
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  overflow: hidden;
}

.day {
  background-color: blue;
}

.night {
  background-color: black;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 110vh;
}

.container .predio {
  display: flex;
  flex-wrap: wrap;
  align-content: space-between;
  justify-content: center;
  align-items: center;
  height: 560px;
  width: 250px;
  border: 2px solid white;
  background-color: gray;
  padding: 20px;
}

#window1,
#window2,
#window3,
#window4,
#window5,
#window6,
#window7,
#window8,
#window9,
#window10,
#window11,
#window12 {
  width: 85px;
  height: 60px;
  background: black;
  cursor: pointer;
}

#window2,
#window4,
#window6,
#window8,
#window10,
#window12 {
  margin-left: 10px;
}

.door {
  width: 40px;
  height: 80px;
  background-color: brown;
  position: relative;
  bottom: -18px;
}

.yellow {
  background-color: yellow !important;
  box-shadow: 0 0 10px yellow, 0 0 15px yellow, 0 0 20px yellow;
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Projeto</title>

É claro que o código acima pode ficar melhor, mas espero que tenha entendido a lógica.
Para ligar todas as "luzes" quando clicar em uma janela, basta adicionar o código:
document.querySelectorAll('.ligaDesliga').forEach((el) => {
  el.classList.toggle('yellow');
});

dentro de:
document.querySelectorAll('.ligaDesliga').forEach((divs) => {
  divs.addEventListener('click', (event) => {
    document.querySelectorAll('.ligaDesliga').forEach((el) => {
      el.classList.toggle('yellow');
    });
  });
});

Que irá adicionar a classe yellow para todas as janelas, quando qualquer uma delas for clicada.
Código completo:

document.querySelectorAll('.ligaDesliga').forEach((divs) => {
  divs.addEventListener('click', (event) => {
    document.querySelectorAll('.ligaDesliga').forEach((el) => {
      el.classList.toggle('yellow');
    });
  });
});

let ambiente = document.querySelector('.day');

function alterarHorario() {
  ambiente.addEventListener('click', (alterar) => {
    const hasYellow = document.getElementsByClassName('yellow');

    if (hasYellow.length) {
      ambiente.setAttribute('class', 'night');
    } else {
      ambiente.setAttribute('class', 'day');
    }
  });
}

alterarHorario();
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  overflow: hidden;
}

.day {
  background-color: blue;
}

.night {
  background-color: black;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 110vh;
}

.container .predio {
  display: flex;
  flex-wrap: wrap;
  align-content: space-between;
  justify-content: center;
  align-items: center;
  height: 560px;
  width: 250px;
  border: 2px solid white;
  background-color: gray;
  padding: 20px;
}

#window1,
#window2,
#window3,
#window4,
#window5,
#window6,
#window7,
#window8,
#window9,
#window10,
#window11,
#window12 {
  width: 85px;
  height: 60px;
  background: black;
  cursor: pointer;
}

#window2,
#window4,
#window6,
#window8,
#window10,
#window12 {
  margin-left: 10px;
}

.door {
  width: 40px;
  height: 80px;
  background-color: brown;
  position: relative;
  bottom: -18px;
}

.yellow {
  background-color: yellow !important;
  box-shadow: 0 0 10px yellow, 0 0 15px yellow, 0 0 20px yellow;
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Projeto</title>

Comment: Opa legal, agora entendi um pouco melhor a lógica ali, vou ir tentando adaptar até ficar como estou imaginando, mas você já me deu uma boa ideia, lhe agradeço


How to check if a function is minimum to functional?

Question: Given $\int_0^1(y')^3dx$ functional and $y(0) = 0 ,y(1)=1$ conditions. Using Euler–Lagrange equation I have got $y(x)=x$. So $y$ is a stationary point of the functional. How to check if it is the minimum for $y \in C^2[0,1]$ ?
Comment: Compute a second variation, see if its positive definite at $y(x) = x$.
Answer: Consider the function
$$
y(t) = \begin{cases} -\lambda t & \text{ for $t <1/\lambda$} \\\\
        \frac{2}{\lambda-1} (\lambda t-1) -1  & \text{for $t\ge 1/\lambda$}.
   \end{cases}
$$
You have
$$
\int_0^1 (y')^3\, dx = -\lambda^2 + (1-1/\lambda)\left(\frac{2\lambda}{\lambda-1}\right)^3 \to -\infty \qquad \lambda\to +\infty
$$
hence your functional does not have an absolute minimum.
It is possible to smooth out the function $y(t)$ to get a $C^\infty$ function with the same property.
Comment: Thanks, what about $y \in C^2[0,1]$. I think $y=x$ is minimum there
Comment: No, you can find a counterexample with a $C^2$ function (just smooth out the angle point)
Comment: Is there a option to check whether a stationary point is extermum ?
Comment: If your functional is strictly convex you know that the stationary point is a minimum. If the second variation is positive you know that the point is a local minimum.
Comment: Isn't the second derivative positive for the above example?. Please see this question http://math.stackexchange.com/questions/334546/how-to-check-if-stationary-point-is-extremum
Comment: What I show is that you don't have an absolute minimum, but you might have a local minimum.


A particular script is running as apache user and executing sendmail. Need to find the script path

Question: There seems to be some script in the server which is executing as apache user and sending mails. Looking at ps aux output we find that sendmail executable is executed with apache user but we are not able to find specific script which is doing this.
What is the ideal way to deal with this kind of situation ?
Comment: First, check all your crontabs for executions of a script you don't know, maybe it's in there. Other than that it will most likely be a php exec in your /var/www-folder or wherever you put your web files into. Best ist to search for the pattern like this:
`grep -rnw '/var/www/' -e "mail"`

or

`grep -rnw '/var/www/' -e "exec mail"`

It could also be a PEAR module. Sadly only the execution is logged, not the script calling it.
Answer: I think you are looking for the mail.log setting in php.ini (php 5.3+ only), which will log all mail() function calls, including the script that initiated the call:
; The path to a log file that will log all mail() calls. Log entries include
; the full path of the script, line number, To address and headers.
;mail.log =
; Log mail to syslog;
;mail.log = syslog

Answer: If you are running PHP on the server, you can use below syntax to track down originating email script.
Put below lines in php.ini
mail.add_x_header = On
mail.log = /var/log/phpmail.log

Above directives will add header with originating php script like below
X-PHP-Originating-Script: 456:mail.php

As well as write log in file /var/log/phpmail.log
mail() on [/var/www/html/project/tmp/mail.php:456]: To: email@example.com -- Headers: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed; delsp=yes Content-Transfer-Encoding: 8Bit X-Mailer:  Sender: firstname.lastname@example.com From: email@example.com