iOS How to move scrollbar when Keybord is visible

Question: I am making an app that needs to create a Registration Form to take user inputs. For inputs I have 4 fields. I adjusted 4 fields in UIStackView and made stakeview vertically centered as it was a design of app. Everything is going good. but in small devices Keyboard was over lapping some fields.
To solve my problem I did R&D and used IQKeyboardManager. It helped me a lot. but I have seen that in fields all you can go to other fields you have to use toolbar provided by IQKeyboardManager. But now a days in advance app you can see you can scroll the view up and down.
What I have done:
So To solve my problem I created a UIScrollView around my stackview that contains my fields but it never helped me. Because it is creating design issues also. Stackview never comes in vertically centered of ScrollView. also scrollview is enabled all the time regardless of keyboard is appeared or not. look at following picture that dipicts me UI

What I want:
All I want is that untill and unless Keyboard is appeared scrollview should not be scrollable. Once the keyboard is appeared then the scrollview must be scrollable. Also I want to check if there is need to make scrollview scrollable or not. Because in larger devices like iPhone 8plus I think there is no need to show scrollview as keyboard is always below the last UITextfield. Its just overlapping in smaller phone like iPhone 5.
Please help me. It is my idea that apps are using scrollview. They may be using something other that act lik scrollview aroung views when Keyboard is open and does not show any scrollview when there is no keyboard open.
Answer: Use keyboardWillShowNotification and keyboardWillHideNotification notification to change the scrollView height. On keyboardWillShowNotification you decrease the scrollView height by the height of the keyboard. And in keyboardWillHideNotification you just reset the height as it was before. Any doubt please comment.
Comment: please show me code. And also how to center align the views inside the UiScrollview. I have UIStackView and it is not getting center aligned vertically inside the UiScrollview
Answer:
Create a content view inside scroll view.
Set content view constraint (top, bottom, leading and trailing) as (0,0,0,0) and equal width and equal height with scroll view.

To set constraint on scroll view, you can refer
https://medium.com/@pradeep_chauhan/how-to-configure-a-uiscrollview-with-auto-layout-in-interface-builder-218dcb4022d7
After that, implement keyboard observer in your view controller.
override func viewDidLoad()
    {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}

 func keyboardWillShow(notification: NSNotification) {
      // set scroll view content size height as per your need (subtract keyboard height from original)
}

func keyboardWillHide(notification: NSNotification) {
    // reset scroll view content size height to original
}

Comment: and how to vertically center align my fields in the scrollview
Comment: put your stack view inside content view of scroll view with vertically centred to parent. that can solve your alignment problem. and set scroll view constraint (top, bottom, leading and trailing) as (0,0,0,0).
Comment: I have done this too. but problem is something I cant understand. By doing this I am able to see my vertically centered fields. but when I do ran on real device my whole Stackview shifts to bottom. Looks like on real device it is unable to find the center of vertical in UiScrollview


ec2 rebooted my instance?

Question: I found out that my CentOS 5 server on EC2 was rebooted, without my command to do so. I did not even log in on the day it was rebooted. When I look at 'last' in linux, it says:
<code>jeroen   pts/0        128.97.......    Thu Apr  7 15:02 - 16:28  (01:25)
reboot   system boot  2.6.18-xenU-ec2- Wed Apr  6 15:48         (1+05:27)
jeroen   pts/2        128.97.......    Tue Apr  5 19:31 - 23:17  (03:45)
</code>
So it looks like nobody logged on that day. Any suggestions to what could have happened? Does EC2 reboot instances under any circumstances? Or might it be hacked?
Answer: This happens occasionally when Amazon is looking to decommission the physical server your instance is running on.  They might be killing the server to replace a failing hardware component or the server might have simply reached its end of life.  Either way from what I understand, their process works something like this:

The physical server gets marked as decommissioned so no new instances get launched on it.
If they can (e.g. they're not dealing with a critical hardware failure), Amazon will wait for some period of time to see if the instances running on the server shutdown or reboot on their own (rebooting an EC2 instance usually results in it getting launched on a different physical server).
After that period completes, Amazon will force the remaining instances to reboot moving them to other physical servers.

As a general rule of thumb, due to this and other quirks in the environment, you should treat any individual server running on EC2 as Ephemeral.  Any server may reboot or flat out disappear at any time.  Accordingly automating deployment with something like chef or puppet, having solid monitoring, and designing your application to work around failure is critical.
Comment: So, no vMotion (or its equivalent)? D'oh.
Comment: That's terrible - I get the push to create ephemeral instances but if they are going to retire a host they should xen motion the guests to another host
Comment: Your automation and monitoring framework should be checking for that. That's also the reason why your applications should be written to use Elastic Load Balancers.
Comment: Also, you guys are commenting on a 4 year old question. You aren't going to get an answer from the OP.
Answer: Maybe an EC2 problem. See Reboot?
I had the same problem and I found in AWS Service Health Dashboard that there had been a problem in EC2.
Conclusion : Reboots should be expected, but no more frequently than you'd expect them with commodity hardware.
Comment: Oups... link is https://forums.aws.amazon.com/thread.jspa?messageID=52417

ec2 rebooted my instance?


Aplication in Docker image how to change hostname from localholst to public

Question: I just used this docker image https://github.com/netbox-community/netbox-docker/ but I was not able to figure out how to configure it to work on public hostname/IP?
I was reading documentation and tryed to figure out, but I am stuck.
I found nginx.conf and edited hostname URL but it dot work.
daemon off;
worker_processes 1;

error_log /dev/stderr info;

events {
    worker_connections 1024;
}

http {
    include              /etc/nginx/mime.types;
    default_type         application/octet-stream;
    sendfile             on;
    tcp_nopush           on;
    keepalive_timeout    65;
    gzip                 on;
    server_tokens        off;
    client_max_body_size 10M;

    server {
        listen 188.8.131.52:8080;
        server_name netbox.domain.tld;

    #    listen      8080;
        access_log  off;

        location /static/ {
            alias /opt/netbox/netbox/static/;
        }

        location / {
            proxy_pass http://netbox:8001;
            proxy_set_header X-Forwarded-Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme;
            add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
        }
    }
}

Answer: It should not be necessary to change anything inside the container. Edit netbox-docker.override.yml.
Change
- 8000:8080

to
- '0.0.0.0:8000:8080'

This will configure docker to bind the port to all interfaces, not only the loopback interface. The documentation for this setting is here.
Then create the container(s) with docker-compose up.
Comment: and should I leave proxy_pass to server host?
Comment: You shouldn't change anything inside the containers. All your changes will be reverted the next time you pull newer images anyway.


Trigger JQuery script once product has been successfully added to cart

Question: Inside my child theme's custom.js I have the following:
$(document.body).on('added_to_cart', function() {
    console.log('Product Added');
});

In theory, this should output that message in the console when a product has been successfully added to the cart. However, at the moment it does nothing and I cannot work out why?
Comment: `'added_to_cart'` must be an event. Is this event customised or added?
Comment: You have certainly make some other customizations (or your theme has some or even a plugin can be guilty)… without a live link is not possible to check what is going wrong as the code that you are using should work on default woocommerce… Also this code will only work on archove pages as shop, is ajax add to cart is enabled in Woocommerce settings.
Answer: jQuery(document).ready(function($){
    $('body').on( 'added_to_cart', function(){
        alert("testing!");
    });
});

Use this it works for me..:)
Answer: This seems to work fine for me...
HTML (w/ Bootstrap 4)

Hello, World!

        <button id="addToCart" class="btn btn-primary">
          Trigger Event
        </button>

JS
var body = $(document.body);
var button = $('#addToCart');

body.on('add_to_cart', function (event) {
  console.log('added to cart!');
});

button.on('click', function () {
  body.trigger('add_to_cart');
})

You can check out this CodePen and play around with it:
https://codepen.io/anon/pen/ZjBoNY?editors=1010


$1 bet, 1000 events, 45% chance of winning each event. What are the odds of winning?

Question: Bet size: $1
Number of bets: 1000
Chance of winning each bet: 45%
What are the statistics around this problem?  Such things as:
What are the chances of being ahead after 1000 bets?  (ahead more than \$100 dollars?)
How big of a bankroll do you need for a 50% of getting to the 1000th bet before going broke?
With $100$ what is the average number of bets before going broke?  (with \$200?)
What formulas are used so I could look at different options?
Answer: You have a binomial distribution  Using the Wikipedia notation, your first is $n=1000, p=0.45$ and you sum over $k$ from $501$ to $1000$.  Ahead more than $100$ is sum over $k$ from $551$ to $1000$  I'll leave the rest to you.  With $1000$ throws at $45\%$ you are not going to win.


Does $\sum (-1)^k 2^{1/k}$ converge or diverge?

Question: How am I supposed to determine the convergence of this series if I only know about the alternating series test and the divergence test?
Comment: Are you talking about the series or the sequence? Neither converges.
Comment: Use the divergence test and compare even and odd values for large $k$.
Answer: As $k\to\infty$, $\frac 1k\to 0$, $2^{1/k}\to 1$, and $|(-1)^k2^{1/k}|\to 1$.
So if these are the terms of the series, since the terms of the series do not tend to zero, the series is divergent.
If these are the partial sums of the series, the even sums tend to $1$ and the odd ones tend to $-1$, so this also does not converge.
Answer: Assuming you're talking about the convergence of the sequence $\{(-1)^k2^{1/k}\}_{k\in \mathbb N}$, you can prove it diverges since it has a subsequence that converges to $1$ and another one that converges to $-1$. Can you identify those subsequences?
HINT: $2^{1/k}$ converges to $1$ as $k$ goes to infinity and $(-1)^k$ is either $-1$ or $1$ depending on the parity of $k$.
If you're talking about the convergence of the series
$$\sum_{k=1}^{\infty} (-1)^k2^{1/k}$$
the same argumet shows that it doesn't converges since the its terms doesn't converge (in particular, doesn't converge to zero).


switching between 2 views

Question: I have created two Views, I then placed the second view on the footer of the first view. Main view has date, an image, attachment and size of the attachment, the second one has an images that are linked to a files.
Output, latest one should always display on the top with an image, attachment and size of the attachment which I got it right when I click on the image from the footer I want an image to display above with the attached file and the size. May anyone help on how I can do the switching part in. See an the attached, am using Drupal 7
Answer: I have actually resolved my problem by adding a piece of php code within filter criteria. see attached.

switching between 2 views


Polyrhythmic clash, how to get rid of the rhythmic dissonance without losing the polyrhythm?

Question: So I'm midway through composing a movement of a suite I am working on and I have reached this section that is primarily triplets. It starts off as a solo violin, and then later, more instruments are slowly added back in. I felt the need for rhythmic variety, so what do I do when I have triplets as the primary rhythm? In this case, I went for the polyrhythm option. Polyrhythm has worked for me before to bring rhythmic interest. However, something happened that I did not expect. The rhythms clashed noticeably. I knew rhythmic dissonance was a thing, but that has never occurred in my own works until now. Here is an excerpt that includes the polyrhythm:

By the way, this passage here starts in G minor and modulates to C minor briefly. Considering that the movement as a whole is in D minor, that's not too surprising. And it can't be the harmony that is making it clash, since outside of a few non-chord tones, all the voices are consonant with each other. That's why I'm thinking that it is the rhythm that is making it clash. However, as I stated before, I have never had rhythmic dissonance happen with polyrhythms before(and that is both for 2:3 and 4:3 polyrhythms).
Here is an example of a piece where I use polyrhythms and don't get this rhythmic dissonance:
https://musescore.com/user/50070/scores/5989028
But it isn't just piano solo for which I have gotten polyrhythms to not be rhythmically dissonant, I have done that for chamber works too. And I have never used polyrhythms outside of x:3 because if triplets are the primary rhythm, rhythmic dissonance is less likely to occur than with say quintuplets as the primary rhythm. And before you say that it is probably the tempo, the tempo that this movement is at is quarter note = 100 BPM, which again, I have wrote polyrhythms at that exact tempo that aren't rhythmically dissonant, so that's ruled out. In fact, I find that the moderate range is where polyrhythm is at its best. Too slow and it might as well be polymeter instead of polyrhythm. Too fast and it might as well be a single rhythm that is very embellished.
So why am I getting this rhythmic dissonance if my tempo is not too fast or too slow and my harmony is consonant? And is there anything I can do to keep the polyrhythm but not have the rhythmic dissonance? Transposing the harmony down I don't really want to do because Violin II is already getting close to its lower bound. If I transpose it down, it will be at its lower bound, an open G, which is not easy to control in terms of intonation and dynamic. Plus, I'm not sure that changing the notes of Violin II would effect the rhythmic dissonance at all.
Comment: The different parts are very constant with each other when we look at the downbeats. But the off beats (the and of 1, the and of 2, the and of 3) are where the polyrhythm is noticeable. During those off beats, the bottom violin line plays notes that are a half step away from the top violin's note. On beat 1, you have the top violin playing a G on the middle triplet, but the bottom violin comes in with an F# that clashes with the G and sticks out because of the polyrhythm. Likewise on the and of best 2, we have C and B. For the and of beat 3, we have F and Bb.
Comment: One way to test if this is correct is to change the bottom violin line to something like: D-C-G-E-C-A so that the line is alternating between a rise and a fall. This may not be the ultimate line you went, but if you try this, is the dissonance less? If so, I will put this into a full answer.
Comment: Why do you try to  avoid dissonance? Don't you think the dissonance would make it more interesting? Music lives from consonance and dissonance like a picture from light and shadows.
Comment: @AlbrechtHügli I don't always try to avoid dissonance because I know that it is needed to some degree. But this polyrhythmic dissonance just stuck out to a degree that on beat dissonance doesn't. On beat dissonance adds harmonic richness, but the polyrhythmic dissonance really stuck out.
Comment: I think @jdjazz probably spotted the problem. In the other linked score the polyrhythm voices are much further apart. Here, in m. 53, the voices are right on top of each other, beside the harmonic dissonance that can create a kind of repeated note effect which may not be desired.
Answer: I suspect the dissonance that you hear is due to the half-step and whole-step intervals between the two violin parts. Because of the polyrhythmic timing, these harmonic clashes are being emphasized. If these half-step intervals were played on the two violins simultaneously, it might sound more intentional. But the staggering can make it sound like a mistake rather than a conscious choice, and delaying the dissonant harmony calls attention to it rather than letting it meld with the melody line.
Here's a little more detail: you are correct that the different parts are very consonant with each other--but only when we look at the downbeats. The offbeats are where the harmonic dissonance occurs. On the "and" of beat 1, you have the two violins playing F# and G at the same time. On the "and" of beat 2, the violins are playing C and B. On the "and" of beat 3, the violins are playing F and Bb.
The half-step intervals are especially dissonant, and they're likely causing what you hear. Something you can try is this: change the bottom violin line to something like: D-C-G-E-C-A. The line will be alternating between a rise and a fall, which may not be what you are looking for, but if it sounds less dissonant to your ear, then it confirms the ideas I've written here.
Comment: Well I tried changing the bottom violin line to what you suggested and it didn't sound nearly as dissonant as it did before with the rising thirds.
Comment: Excellent! I think that answers your question--the dissonance was the combination of rhythmic staggering along with the particularly dissonant intervals.


Node Buffer to JSON

Question: When I read a JSON file, parse, and output it, I only get some random numbers instead of my JSON file:
{
  type: 'Buffer',
  data: [
    123, 0,  34, 0,  83, 0,  99, 0, 104, 0, 101, 0,
    109, 0,  97, 0,  86, 0, 101, 0, 114, 0, 115, 0,
    105, 0, 111, 0, 110, 0,  34, 0,  58, 0,  49, 0,
     55, 0,  48, 0,  54, 0,  44, 0,  34, 0,  67, 0,
    104, 0, 105, 0, 108, 0, 100, 0,  65, 0,  99, 0,
     99, 0, 111, 0, 117, 0, 110, 0, 116, 0, 115, 0,
     34, 0,  58, 0, 123, 0,  34, 0,  83, 0,  45, 0,
     49, 0,  45, 0,  53, 0,  45, 0,  50, 0,  49, 0,
     45, 0,  50, 0,
    ... 52404 more items
  ]
}

I load and output it with this code:
contents = fs.readFileSync(filename);
console.log(JSON.parse(JSON.stringify(contents)))

I searched for this already but found no working solution.
Answer: It's not random numbers, it's a Buffer. If you want to convert that buffer to a string (so you can parse the JSON into objects and such), you have to do that on purpose, since text is meaningless unless you know what encoding is used for the text (UTF8, Windows1252, etc.). readFileSync has an encoding option you can supply to tell it to convert the data to string using a given encoding, or you can use toString on the Buffer.
Alternatively, if you're using CJS modules (Node's original kind), they let you read JSON directly via require, parsing automatically.

In a comment you've said:

Ok I used toString() on it and then another error appears: SyntaxError: Unexpected token { in JSON at position 1. To add an encoding does nothing. The file is UTF-8.

That's a separate issue, but:
Since JSON.parse counts from position 0 (at least in Node.js, I don't think that's dictated by the spec), that tells us either the JSON is invalid, or there's a byte order mark at the beginning of the file not being handled by the encoding.
Sometimes editors put a BOM at the beginning of UTF-8 files. You can check to see if that's what's going on like this:
let text = yourBuffer.toString("utf8");
if (text.codePointAt(0) === 0xFEFF) { // UTF8 BOM
    text = text.substring(1);
}

Then you should be able to use JSON.parse on text.
Comment: Ok I used `toString()` on it and then another error appears: `SyntaxError: Unexpected token { in JSON at position 1`. To add an encoding does nothing. The file is UTF-8
Comment: @programmer - I've moved the comment that I had here into the end of the answer with a bit of code that may help.
Comment: I'm not quite sure if I implemented it right but It changes nothing. It also says as an error that `{ is undefined`. Then I watched at the text that should be parsed and I realized that between every character is a space. It looks like this: `{ " k e y " : " v a l u e " }`
Comment: @programmer - Your file is not in UTF8. Looks like it might be in UTF-16-LE, if the "spaces" are actually character 0.
Comment: I looked up the encoding using `file *` and got `data`. But it throws an error if I put data in?

Node Buffer to JSON


How can I dynamically refresh the price on product page when changing quantity based on price table

Question: I'm currently building a web store with Drupal commerce and would like to get to price shown on a product page to asynchronously refresh when the user increases the amount in the quantity field, such as here.
How can I achieve this?
Answer: Commerce Cart Ajax

Features

The "remove" button on cart view removes the item from the cart
  immediately, without a page refresh. The row is removed from the
  table.
The "Qty" is updated when the "update" button is clicked. The totals are recalculated. No page refresh.
Comment: Thank you but this is actually not my question. As you can see on the link I gave this is about the "productdisplay page" and not the cart.
Comment: check this http://drupal.stackexchange.com/questions/53990/ajax-field-in-products-page-drupal-commerce
Answer: You can show the price in the add to cart form using this approach:
/**
* Implements hook_form_FORM_ID_alter
*/
function MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state){
  // Add read only price field to add to cart form
  if (isset($form_state['default_product']->commerce_price)){
    $price = commerce_product_calculate_sell_price($form_state['default_product']);
    $form['display_price'] = array(
      '#title' => t('Price'),
      '#type' => 'item',
      '#markup' => commerce_currency_format($price['amount'], $price['currency_code']),
      '#prefix' => '
',
      '#suffix' => '
',
    );
  }
}

It may need adjusting to include the quantity multiplier, but should provide a good starting point there.


How to delete message entities (message stack) of a special template depending on entity age

Question: for the "Private Message" module, my Drupal 8 site uses the "Message" module (https://www.drupal.org/project/message) as substructure.
I would like to build a kind of notification center into the page, which should be possible to implement with the message stack (as I heard).
The trigger to generate such a message will probably be a custom module.
The message module also offers a kind of "auto cleanup", but unfortunately as far as I have seen only for all messages and not per message template.
In principle I only want a notification center, which is triggered at certain events and which cleans itself depending on the message type (e.g. only the last 10 messages of a certain template or delete all messages of a certain template which are older than 10 days).
In general, I guess cleanup does not work, as it would probably also delete the "private messages".
Any hints.
Answer: It's possible to override the cleanup/auto delete settings in the message template configuration (even via UI) per template. Just visit the template configuration form.


Why does Cloud Functions perform so low yet so expensive?

Question: I just register a Google Cloud free tier lately & took interested in Cloud Functions which can make me develope & run code without install OS system or Software Development Tools. So i want to test its performance to its limit with this function run on set up of 2GB & 2.8Ghz CPU
<code>exports.helloWorld = (req, res) => {
  let message = getTheLottery();
  res.status(200).send(message);
};

function getTheLottery(){
for(var i=0,len=10000000;i<len;i++)
{
var ticket=sha256(makeid(5));
if(ticket=='7CD743877911812A45CD7974023A2D1ACA9831C82057902A2300874A951E6E17')
     return true;
    }
    return false;
}
</code>
The SHA256 algorithm was from here & makeid from here to generate random string
It take 40 seconds (40311ms) to complete the task, implement this code on C++ or C# add simple parallel & multithread it can easily run the task in less than 7 seconds on my average school PC with 4GB ram & i5 2.5ghz plus it has to run a OS system & few software in the background, let alone a code, when google claim it can make the code faster 75% compare to normal PC
I haven't try Azure cloud function. Assume i brought the "function" to my site & let ppl run 1000000 times, it'll cost 1657$ arcording to the calculator & maybe a fortune to run it few hundreds time for a full day with barely any way to optimize the code or system since it's all limited & the more time it run, the more it cost by SECONDS. With this money i can rent a VM with powerful GPU & run fully developed render or brute force software with maximum performance
Is there any better way for me to run the code? 'cause this feel like a online code compiler with extra steps. How does it make serverless computing the "future"?
Comment: Cloud functions are not designed for parallizable, compute-intensive tasks.
Comment: @SLaks then why does it available with a such huge configuration? I mean it would be a waste just to use it to send & receive HTTP request
Comment: I wouldn't consider any Cloud Functions configuration to be "huge".
Comment: Use Pub/Sub with a cloud function that deals with single or a chunk of data. Let each cloud function instance do tiny computations and at last sum up the result.
Answer: Heavy computation is not a use case for Cloud Functions.  In fact, there are quite a few things it's not very good for, given that a server instance has only a single CPU, no GPU, and a maximum execution time of 9 minutes.
If you have a heavy compute load, consider using Compute Engine instead.  If you want, you can write a Cloud Function that delegates work to Compute Engine.
Cloud Functions is intended to glue together other parts of your system without having to create and manage a formal infrastructure for it.  The main benefits is effortless scaling (up and down), paying only for resources used, and the ability to trigger on events that occur in your GCP project.
Comment: Perhaps this might be helpful to get you started: https://medium.com/google-cloud/start-stop-compute-engine-instance-from-cloud-function-bf9ae5199609
Comment: i already know about Compute Engine which is the VM i mention. Does Google have any service like Cloud function contribute to run heavy computation. I'm interested in the idea that one can focus alll the hardware just to run & compute code. it's way more convinient than register a VM, install OS & software to run the app
Comment: No.  As I said, what you can do is write a function that delegates to Compute Engine.  That's how you get serverless triggers with heavy compute behind it.
Comment: May i ask if you could explain what's "serverless" about this? 'Cause when we rent a VM on an online system, the VM itself was consisded a server, does it make faster than a local PC somehow?
Comment: The Cloud Functions trigger is serverless.  Compute Engine is not.  They are different products that solve different problem in a way that's technologically feasible.  It's not currently technologically feasible, while being cost effective, to combine them into a single product.
Comment: i want to try this with TPU. can this code possible to run on python with tensorflow?


Are there composers who consciously apply Leonard Meyer's theories on patterns and expectations?

Question: In response to one of my previous questions (on deciding when to continue or break broken chord patterns), someone recommended that I read Leonard B. Meyer's Emotion and Meaning in Music. I'm currently doing so, and I have to say that it is a fascinating if somewhat difficult and technical read.
I was wondering whether there are any composers who are known to consciously apply Meyer's theories on patterns and expectations (as laid down in the book I'm reading and possibly other works as well) to their compositions.
As an aside, it would be interesting to see a course on musical composition (either in book or in lecture form) that explicitly incorporates Meyer's insights.
Comment: in jstor you might find articles relaying on Meyer like this: https://www.jstor.org/stable/746303
Answer: I haven't heard about Meyer's theories before. But it seems obvious to me that all composers of Renaissance and the common practice era (if not since Josquin or earlier) - have been "playing" with these patterns and expectations.
Also in composers of today do so, maybe one has heard or read about Meyer's theory. But this might  just have been a coincidence. I can't imagine there is any musician that is referring to this formal theory or needed it as a recipe for his writing.
The practice goes ahead of theory. You can be aware of a theory without explicitly build your practice on it.
Leonard Meyer proposes a theory of style and style change that relates the choices made by composers to the constraints of psychology, cultural context, and musical traditions. He explores why, out of the abundance of compositional possibilities, composers choose to replicate some patterns and neglect others.
Meyer devotes the latter part of his book to a sketch-history of nineteenth-century music. He shows explicitly how the beliefs and attitudes of Romanticism influenced the choices of composers from Beethoven to Mahler and into our own time.
Source of quotation above:
THEORY, HISTORY, AND IDEOLOGY
So it seems obvious to me that a contemporary composer is influenced by all the works he has played but certainly not by the theory that analysis and explains the praxis of those composers.
You will hardly find someone who said: "I've played Bach, Beethoven and Bartok. But when I read  Meyer's theory I knew how I will compose."
Leonard Meyer's Emotion and Meaning in Music is the classic text in music expectation. Meyer's starting point is the belief that the experience of music (as a listener) is derived from one's emotions and feelings about the music, which themselves are a function of relationships within the music itself. Meyer writes that listeners bring with them a vast body of musical experiences that, as one listens to a piece, conditions one's response to that piece as it unfolds. Meyer argued that music's evocative power derives from its capacity to generate, suspend, prolongate, or violate these expectations.
melodic expectations (Wikipedia) Meyer


How to make a max value in doughnut chart

Question: I am using reactJs and chartjs.
I have the following chart I would like to make :

I have the following code
<code>var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: ['OK'],
    datasets: [{
      label: '# of Tomatoes',
      data: [12],
      backgroundColor: [
        '#0EA4EA',
      ],
      borderWidth: 1
    }]
  },
  options: {
      legend: {
          display: false
      },
      cutoutPercentage: 80,
      rotation: 0.75 * Math.PI,
      circumference: 1.5 * Math.PI,
      title: {
          display: true,
          position: 'bottom',
      },
      scale: {
          ticks: {
              min: 0,
              max: 150
          }
      }
   }
});
</code>
But I can't find a way to set the max value of the arc to 150
here
Answer: I think you need to specify the area that isn't in Blue:
<code> labels: ['Ok', 'Not Ok'],
 datasets: [{
  label: '# of Tomatoes',
  data: [12, 138],
  backgroundColor: [
    '#0EA4EA',
  ],
  borderWidth: 1
}]
</code>


Why my variable is undefined when I'm using an arrow function onClick?

Question: In my react component, orders[i] is defined, since the component is rendered using name and amount, however, when it comes to onClick event, orders[i] is undefined in the context of the arrow function. How can I call that function using orders[i].name as an argument?
let orders = this.state.orders;
let ordersRender =[];
for (var i=0; i<orders.length; i++) {
  if (orders[i].amount) {
    let newInvoiceItem = <InvoiceItem name={orders[i].name} amount ={orders[i].amount} key={i} handleDelete={() => this.deleteProduct(orders[i].name)}/>;
    ordersRender.push(newInvoiceItem);
  }
}

Answer: When handleDelete event is fired, the variable i has changed its value to orders.length, that's why orders[i] is undefined when onClick is fired.
So, instead of for-loop, use Array#map to iterate over the orders and return an array of InvoiceItem items. Since amount is optional, we need to filter the orders based on the amount before applying the .map function.
let { orders } = this.state;
let ordersRender = orders.filter(order => order.amount).map(({name, amount}, index) => {
  return (
    <InvoiceItem name={name} amount ={amount} key={index} handleDelete={() => this.deleteProduct(name)}/>
  );
})
...

Hope this will help!
Answer: Simply changing var to let solves this issue.


Making bootstrap modal work in a framework7 web app

Question: I am having trouble with including bootstrap modal onto a framework7 app.
I suspect that framework7 is suppressing boostrap modal from appearing.
This is my fiddle.

Back

      Title

        Create

    <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

This project is made possible because of these open-source projects & beta testers.

Open Source

          Framework7

          Vuejs

          Ruby on Rails

          Font Awesome

          Axios

          Kaminari

          Puma

Thanks to these beta testers

John Doe

Nathan

Sharon days

Logo

          Lau Jun Wen

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

Modal Header

Some text in the modal.

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Can someone give me some pointers on what is wrong? There is no error message. Appreciate any feedback/advice to resolve this.
Answer: I have made several changes to correct the problems:

Removed the modal.min.js.  This was the problem causing the modal to open and close again.
Re-ordered the bootstrap/framework7 CSS + JS to put framework7 after the bootstrap (so that the framework7 overrides bootstrap when necessary).
Put the myModal div at the end of the code so that its z-index does not get blocked by a parent div's less-high z-index.
Add some custom CSS to make the modal show up correctly.  This is necessary due to using two frameworks.

Here is the final code:

#myModal.modal {
    width: auto;
    margin-left: 0;
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 1050;
    display: none;
    overflow: hidden;
    -webkit-transform: translate3d(0,0,0) scale(1);
    transform: translate3d(0,0,0) scale(1);
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdnjs.cloudflare.com/ajax/libs/framework7/1.6.4/css/framework7.ios.min.css" rel="stylesheet"/>

Back

      Title

        Create

    <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

This project is made possible because of these open-source projects & beta testers.

Open Source

          Framework7

          Vuejs

          Ruby on Rails

          Font Awesome

          Axios

          Kaminari

          Puma

Thanks to these beta testers

John Doe

Nathan

Sharon days

Logo

          Lau Jun Wen

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

Modal Header

Some text in the modal.

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Updated fiddle here


Drupal 6: Move the 'Add new comment' link to the bottom

Question: Like the subject says. I'd like to move the 'Add new comment' link to the bottom of the comment list. The only thing we're using them for a is a forum, and this is how we want them set up. I can't seem to find out to move this section in the template.
Answer: Since Drupal is such a highly configurable system, there are a few ways to accomplish what you want. Here's just one example.
The first part of the equation is to remove the link from the node's links array. This approach removes it during the theme call.
<?php
/**
 * Override theme_links() so we can remove or alter any links we don't need.
 */
function MYTHEME_links($links, $attributes = array('class' => 'links')) {
  unset($links['comment_add']);

  // Rather than include all the original theme_links() code in this function,
  // we can just call it directly here.
  return theme_links($links, $attributes);
}
?>

After that, you have a few options of where to readd the link. The primary function that builds the display for comments and comment controls is comment_render() in comment.module. It builds the comments display using a few different theme calls, so it's up to you where you want to add the link back in. Probably the easiest approach is to copy the file /modules/comment/comment-wrapper.tpl.php into your theme folder and add the code for the link there. Alternatively, you could either put it above or below the comment controls form (by overriding theme_comment_controls), or by overriding any of the other comment theme functions. Whichever approach you take to adding the link back in, you can get the code for the link from the comment_link() function -- open up comment.module and search for "Add new comment" to find the link code.
Good luck!


iOS 6 - How to run custom code when orientation changes

Question: I'm creating a game that allows the device to be in either landscape-left or landscape-right orientation, and the player can change the orientation while it's paused.  When they do I need to change the way the game interprets the accelerometer based on the orientation.
In iOS 5 I used the willRotateToInterfaceOrientation to catch changes and change my variables, but that's deprecated in iOS6.  My existing code looks like this:
<code>    if(toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
        rect = screenRect;

    else if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight){
        rect.size = CGSizeMake( screenRect.size.height, screenRect.size.width );
    GameEngine *engine = [GameEngine sharedEngine];
    if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft){
        engine.orientation = -1;
    } else {
        engine.orientation = 1;
    }
}
</code>
I understand that the replacement is the viewWillLayoutSubviews method in the UIViewController class.  I'm building this game in cocos2d 2.1 and there doesn't appear to be a UIViewController class in the demo project, so I'm not clear on how to incorporate it and how the code should look in order to make this work.
Answer: Listen for device orientation changes:
<code>[[NSNotificationCenter defaultCenter]
       addObserver:self
          selector:@selector(deviceOrientationDidChangeNotification:)
              name:UIDeviceOrientationDidChangeNotification
            object:nil];
</code>
When notified, get the device orientation from UIDevice:
<code>- (void)deviceOrientationDidChangeNotification:(NSNotification*)note
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    switch (orientation)
    {
        // etc...
    }
}
</code>
Comment: @JamesMorrison Device orientation and interface orientation are two different enums and two different concepts.  Interface orientation is controlled by software (in response to the device orientation); e.g., your software orientation will only ever be landscape-left or landscape-right.  Device orientation is controlled by hardware and can be anything at any time, including orientations that have no mapping to interface orientation, like face-up or face-down.  You just need to be mindful of the fact that there are many device orientation changes that you'll need to ignore.
Comment: +1 correct option for the given task. Just be careful as you will also get notified on face-up vs. -down orientation changes and mind the difference between `UIInterfaceOrientation...` and `UIDeviceOrientation...`
Comment: @Till - by face-up versus down do you mean when it orients into portrait or portrait upside-down?  Or something else?  Also, I assumed DeviceOrientation and InterfaceOrientation are almost always the same except under special circumstances such as multiple views, or if the InterfaceOrientation has been set programmatically not to match the device orientation.  Or are there other instances to look out for that might cause an issue?


Strange application of Cauchy's Integral Theorem

Question: According to my book, Riemann's Zeta Function, Cauchy's Integral Formula is applicable to the following integral for all negative values of $s$:
$$-\frac{\Pi(-s)}{2\pi i}\int_{|z|=\epsilon}(-2\pi in - z)^{s-1}\frac{z}{e^z - 1}\frac{dz}{z} = -\Pi(-s)(-2\pi in)^{s-1}$$
where $\Pi(-s) := \Gamma(-s+1)$.
Could someone explain to me how exactly this works, I can't seem to figure it out, thanks.
Answer: Notice that for $n\neq 0,$ the factor $(-2\pi in-z)^{s-1}\frac{z}{e^z-1}$ is holomorphic near $z=0.$ To see this, expand $\frac{z}{e^z-1}=\frac{z}{(1+z+z^2/2+\cdots) -1}=\frac{1}{1+z/2+\cdots}.$ Then we can apply Cauchy's integral formula to see that the integral equals $2\pi i \times (-2\pi in - 0)^{s-1}\times\frac{1}{1+0+\cdots},$ which gives the result.
Comment: Ohhh I see it! Thank you for this.
Comment: You're very welcome.


AngularJs used with Play cannot find or instantiate module

Question: I am using the Play Framework (2.5.9). On my scala html template, I pull in Angular via WebJars. I next specify the module and controller I want to use for my page. However, when I try to load the page, the relevant variables that should be set to "hi" via AbstractACtrl are not being set. Also, I get the following error in the browser's console:
Error: [$injector:modulerr] Failed to instantiate module abstractA due to:
[$injector:nomod] Module 'abstractA' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

I do not understand why module "abstractA" is not available. I am defining it right there on the view.scala.html page... I am very sure that angular.js is being pulled in, because in Chrome, the Sources shows webjars/angular.js/1.5.9/angular.js. All the console.log and console.error in my code below are just messages I'm outputting to the console for debugging. None are actually printing to the console right now, indicating that execution is never reaching them.
Things I've tried:
1) Load in angular.js directly (without WebJars).
2) Pull in angular-route.js, angular-resource.js, and/or angular-animate.js with / without WebJars.
3) "data-ng-app" - make it either "ng-app" or "x-ng-app".
4) Pass in $scope to the controller and reference all fields via "$scope."... instead of "this."...
5) Make the "var abstractA" at beginning of my JavaScript "var ab" instead.
6) Put the script which pulls in angular in the "head" portion instead of the "body" portion.
7) Remove the "this.originalAs = @aDocs;" line from the controller.
8) Put all javascript in the "head" portion of the page.
Below is my current code. Please let me know why the module "abstractA" is not available.
build.sbt:
libraryDependencies ++= Seq(
    ...
    "org.webjars"             % "angularjs"                % "1.5.9",
    "org.webjars"             % "angular-ui-bootstrap"     % "2.2.0",
    "org.webjars"             % "bootstrap"                % "3.3.7-1",
    "org.webjars"             %% "webjars-play"            % "2.5.0"
)

view.scala.html:
@(aDocs: List[String],
  webJarAssets: controllers.WebJarAssets)

<!DOCTYPE html>

<meta charset='utf-8'/>

  <link rel='stylesheet' firstname.lastname@example.com(webJarAssets.locate("css/bootstrap.min.css"))' />
  <link rel='stylesheet' type='text/css' firstname.lastname@example.com("assets/stylesheets/style.css")' />

  ...

{{originalA}}

{{abstractACtrl.abc}}

{{abc}}

  <button ng-click='abstractACtrl.setUrl()'>Click!</button>

Answer: I figured out a solution (what an annoying bug!). It wasn't documented anywhere...
I had to change this line:
this.originalAs = @aDocs;

to:
this.originalAs = "@aDocs";

Then, convert it to a list using Javascript split() function for use in the rest of the page.
For some reason, the parsing error there was giving the error statement that the module itself could not be found. Took a bunch of trial-and-error to realize that this was the root cause.


Reduce Java Heap Size

Question: I am using Java8 with Apache OpenNLP. I have a service that extracts all the nouns from a paragraph. This works as expected on my localhost server. I also had this running on an OpenShift server with no problems. However, it does use a lot of memory. I need to deploy my application to AWS Elastic Beanstalk Tomcat Server.
One solution is I could probably upgrade from AWS Elastic Beanstalk Tomcat Server t1.micro to another instance type. But I am on a small budget, and want to avoid the extra fees if possible.
When I run the app, and it tries to do the word chunking, it gets the following error:

dispatch failed; nested exception is java.lang.OutOfMemoryError: Java heap space] with root cause
 java.lang.OutOfMemoryError: Java heap space
  at opennlp.tools.ml.model.AbstractModelReader.getParameters(AbstractModelReader.java:148)
  at opennlp.tools.ml.maxent.io.GISModelReader.constructModel(GISModelReader.java:75)
  at opennlp.tools.ml.model.GenericModelReader.constructModel(GenericModelReader.java:59)
  at opennlp.tools.ml.model.AbstractModelReader.getModel(AbstractModelReader.java:87)
  at opennlp.tools.util.model.GenericModelSerializer.create(GenericModelSerializer.java:35)
  at opennlp.tools.util.model.GenericModelSerializer.create(GenericModelSerializer.java:31)
  at opennlp.tools.util.model.BaseModel.finishLoadingArtifacts(BaseModel.java:328)
  at opennlp.tools.util.model.BaseModel.loadModel(BaseModel.java:256)
  at opennlp.tools.util.model.BaseModel.<init>(BaseModel.java:179)
  at opennlp.tools.parser.ParserModel.<init>(ParserModel.java:180)
  at com.jobs.spring.service.lang.LanguageChunkerServiceImpl.init(LanguageChunkerServiceImpl.java:35)
  at com.jobs.spring.service.lang.LanguageChunkerServiceImpl.getNouns(LanguageChunkerServiceImpl.java:46)

Question
Is there a way to either:

Reduce the amount of memory used when extracting the nouns from a paragraph.
Use a different api other than Apache OpenNLP that won't use as much memory.
A way to configure AWS Elastic Beanstalk Tomcat Server to cope with the demands.

Code Sample:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
import opennlp.tools.util.InvalidFormatException;

@Component("languageChunkerService")
@Transactional
public class LanguageChunkerServiceImpl implements LanguageChunkerService {

    private Set<String> nouns = null;
    private InputStream modelInParse = null;
    private ParserModel model = null;
    private Parser parser = null;

    public void init() throws InvalidFormatException, IOException {
        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader.getResource("en-parser-chunking.bin").getFile());
        modelInParse = new FileInputStream(file.getAbsolutePath());

        // load chunking model
        model = new ParserModel(modelInParse); // line 35
        // create parse tree
        parser = ParserFactory.create(model);
    }

    @Override
    public Set<String> getNouns(String sentenceToExtract) {
        Set<String> extractedNouns = new HashSet<String>();
        nouns = new HashSet<>();
        try {
            if (parser == null) {
                init();
            }

            Parse topParses[] = ParserTool.parseLine(sentenceToExtract, parser, 1);

            // call subroutine to extract noun phrases
            for (Parse p : topParses) {
                getNounPhrases(p);
            }

            // print noun phrases
            for (String s : nouns) {
                String word = s.replaceAll("[^a-zA-Z ]", "").toLowerCase();// .split("\\s+");
                //System.out.println(word);
                extractedNouns.add(word);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (modelInParse != null) {
                try {
                    modelInParse.close();
                } catch (IOException e) {
                }
            }
        }
        return extractedNouns;
    }

    // recursively loop through tree, extracting noun phrases
    private void getNounPhrases(Parse p) {
        if (p.getType().equals("NN")) { // NP=noun phrase
            // System.out.println(p.getCoveredText()+" "+p.getType());
            nouns.add(p.getCoveredText());
        }
        for (Parse child : p.getChildren())
            getNounPhrases(child);
    }
}

UPDATE
Tomcat8 config:
Comment: Run a profiler on your computer to see what kind of memory amounts the program needs during normal runs, then you can determine how much you need to up your budget. Even if you could whittle down some minor chunks, you'd still be running at the edge of memory, and that would make it very unstable.
Comment: Good idea. Will do. Also, do you think there's a way to reduce the `en-parser-chunking.bin`? i.e. It may be loading a number of features I may not require. I know OpenNLP does a number of different language parsing, and I only need to extract nouns.
Comment: I'm not familiar with OpenNLP, but since it's probably using a major part of your memory, you might want to read the documentation very carefully.
Comment: Perhaps I should use a different toolkit. Does anyone have experience with any of these, and can recommend one:  https://en.wikipedia.org/wiki/Outline_of_natural_language_processing#Natural_language_processing_toolkits
Comment: By the way, how much memory do you have (1GB?)? How much heap are you giving Tomcat, and do you have anything else running on the system?
Comment: I am running a t1.micro server instance (600mb ram). http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts_micro_instances.html.  All I have running is a Tomcat8 server.
Comment: You missed the important question. How much heap are you giving Tomcat?
Comment: Sorry, I have added an UPDATE above with the memory sizes.
Comment: Well, you could tweak the memory a bit higher, it would at least be more effective than trying to micro-optimize your code, but like I said, on your machine you can see how much memory it's going to need and based on that get an instance with more memory.
Comment: Thank you. I haven't had a chance to profile the code yet, but will do so soon.
Comment: How much more expensive is the T2.micro ? Amazon specifies it replaces the t1.micro which has been phased out. I could not find the pricing for a t1 family.  The T2 has 1G of ram perhaps that would help though it all depends on your dataset. profiling here is the real key to get to the bottom of it.
Comment: T1.micro is free for a year. I think t2.micro is about 12 USD per month. I do need to profile my code.
Comment: Which version of OpenNLP do you use exactly? Might be more important to know, than the costs for other AWS instances.
Answer: First of all you should try to optimize your code. This starts by using regex and precompile statements before using replaceAll since replaceAll replaced the stuff in the memory. (https://eyalsch.wordpress.com/2009/05/21/regex/)
Second you should not store the parsed sentence in an array. Third hint: you should try to allocate the memory to your array using bytebuffer. Another Hint which may affect you at the most, you should use a BufferedReader to read your chunked file.  (out of memory error, java heap space)
After this you should already see less memory usage. If those tips didnt help you please provide a memory dump/allocation graph.
One more tip: A HashSet takes 5.5x more memory then an unordered List. (Performance and Memory allocation comparision between List and Set)
Comment: @Richard You just think they're useful. As I explained in my comment, they're pretty much guesswork and about as useful as "use `short` instead of `int` to save 2 bytes per variable". Since you're running it at localhost, you can use a profiler to examine the memory use instead of trying things that have very little chance of helping you.
Comment: It's still micro-optimization, and no, it's not suitable in this situation. When you're talking about embedded environments, then you can start planning on saving bytes. If you're trying to do NLP or some other things that require resources, you get those resources. We're talking about `t1.micro` instance here, which is the tiniest thing you can get. If you can't afford to put some more money in it, then you should really be looking into getting a job instead of trying to optimize memory.
Comment: I can't see *anything* right with this answer. Using `Pattern` instead of `replaceAll` may affect the speed, but not so much the memory. Using `ByteBuffer` instead of array, no sense there either, unless he's working with code that expects buffers. `BufferedReader` has nothing to do with anything here, as it also affects speed rather than memory use. Finally the one thing that *does* affect memory (`HashSet`), could also affect speed in a dramatical way.
Comment: "not so much". If he is low of budget and get out of memory he have to optimize everything even if it takes only a few kb of memory.
Comment: Hi Emanuel, thank you for those tips, I will implement them to try get it more efficient. From the stack trace, you can see that `line 35` is where the code falls over with an `OutOfMemoryError`, so it's in the initialization of the `OpenNLP` api. So I agree, that your above suggestions will improve the code, I don't think it will solve the `OutOfMemoryError`. (p.s. I'm not sure why someone gave you a down vote, I find your suggestions useful.)
Comment: Np. Keep in mind that "Out of memory" may be caused because of memory usage somewhere else then OpenNLP. It may happen that there is just not enough memory for OpenNLP available which is used and not released before. Kayaman, using an unordered list instead of a map consumes 5.5 times less memory(!) which is not the same like comparing short to an integer

Reduce Java Heap Size


What do I put on my developers box in regard to SharePoint 2010

Question: So we are venturing out into the world of SharePoint and it seems that I have to install SharePoint Server directly on each developer's box. Is this correct? I have SharePoint up and running on a separate sever so it seems redundant to have to install it on each box. Not to mention installing SharePoint on Windows 7 is a pain in the ars. I'm just trying to clarify how to correctly set the environment up. I've been using this link as a guide so far: http://msdn.microsoft.com/en-us/library/ee554869(office.14).aspx Any advice is greatly appreciated!
Answer: No you don't need to install sharepoint on every box, just VS and the SDK. You should have a separate dev instance for them to connect to, but that should be a real server not a win7 desktop.
So you should have
1 Server with sharepoint 2010
N Dev workstations that have VS2010 and the SDK installed.
Comment: I found out that Visual Studio REQUIRES you to have Sharepoint Server installed on EACH developers local box.
Comment: @Jisaak: uhg sorry :(
Comment: Does the SDK provide you with local or remote debugging capabilities or something? I have never developed for Sharepoint so I'm just curious, as my instinctive answer is yes a local instance will make it a lot easier to develop and debug against? Dev and test server environments would still be needed to provide infrastructure, AD, isolation for QA and so fourth of course... but for the local development process?
Comment: Thanks! That is what I was hoping to hear. Any chance you have an online resource you could point me too in regards to "connecting" VS and the dev sharepoint server?
Comment: @Oskar: I'm not sure, the last time I did sharepoint work was 2 or 3 years ago, but back then i could do remote debug pretty easily and without anything special (then again i have enterprise admin creds ... soo YMMV) I've since ditch sharepoint but still setup devs every now and again.
Comment: @Jisaak: Sorry see above havn't done anything active in a while besides installs. But if the interface hasn't changed too much you should just be able to go to file -> connect to sharepoint in VS
Comment: Ok. I'll see what I can find. The reason I thought I might have to have sharepoint server installed on each box is because when I go to Tools -> Add Sharepoint Connection an alert comes up saying "A SharePoint server is not installed on this computer. A SharePoint server must be installed to work with SharePoint projects." But anyways, thanks for clarifying the setup for me!
Answer: We've used Microsfoft VPC and installed Server 2008 and Sharepoint on that.  Then do dev either on your host PC or the VPC and deploy to the Sharepoint instance on your VPC to test your changes.  This way developers are stepping all over each other in a Development environment.
Answer: SharePoint 2008 cannot be installed on Microsoft VPC due to the fact that it needs Windows Server 2008 64-bit. Microsoft VPC cannot run a 64-bit Operating System, you'll need a different Virtualization Platform.
This can be confusing due to the fact that you can run a 64-bit version of Microsoft VPC.
Answer: Here is couple practical tips for setting up SharePoint 2010 development environment:
SharePoint 2010 Team Development Environment by Vesa Juvonen
SharePoint 2010 Development Environment Practical Tips by Sahil Malik


Nested Dropdown Menu of Bootstrap

Question: I would like to add Nested bootstrap menu in my project. (I'm using the Bootstrap Business Theme.)
I already tried with the Superfish module.. But I don't like that much because the appearance of menu is not good looking and have to overwrite many CSS files.
I also tested with TB Mega Menu. It doesn't work. I put TBMenu Block in Navigation block. But the whole menu was totally disappear. I don't know why it happen like that.
Anyone knows other flexible dropdown menu for bootstrap theme?
Answer: Responsive Menus module is suitable for bootstrap theme.
https://www.drupal.org/project/responsive_menus
Comment: Give it some time man. Configurations are bit tricky.
Comment: That module can be used for DropDown Menu ? I want to do is Dropdown with submenu in normal view. It does not appear not even in normal view.

Nested Dropdown Menu of Bootstrap


Erro ao compilar no Delphi XE5 UPD2

Question: Estou com o seguinte erro ao compilar no Delphi XE5, alguém sabe o que pode ser? começou após uma tentativa frustrada de instalar o XE6.
Comment: Aparentemente os paths se perderam, pois ele está procurando o compilador dentro da pasta do seu projeto. O BRCC32 é o compilador de resources. Você possui algum comando na execução pre ou pos build do projeto?
Comment: Acho que tive azar na instalação do XE6 mesmo, realmente não mudei nada na execução, ocorreu de repente.
Comment: já tentou restaurar a instalação do XE5?
Comment: Estou reinstalando mesmo.
Answer: Problema resolvido. O antivírus Kaspersky Pure 3 estava bloqueando alguma instância do compilador, este problema começou a ocorrer sem nenhuma configuração no antivirus, provavelmente foi após alguma atualização automática do mesmo.
Comment: Obrigado pela dica.
Answer: Ao que parece você fez uma instalação customizada do Delphi XE5, ao tentar instalar a versão XE6 você deve ter optado por uma instalação padrão que deve ter alterado as configurações atuais(customizadas), um provável modo para corrigir este erro é mostrado nesse artigo feito pela Embarcadero.

Erro ao compilar no Delphi XE5 UPD2


How can I allow all users to access only a certain type of entityform?

Question: I need that all users (anonymous users too) have access to the submissions of a certain type of entityform.
I can set the permission View any entityform submission and it works but for all types of entityform. I also try with hook_access
How can I allow all users to access only a certain type of entityform but not for all types of entityform?
Answer: In filter. Just add.

content: type => is one of (put check mark on all those content types
  you want. )

And then add permission for that view.
The another way is.

Go to permission section under people admin menu.
Navigate to node section.
You will find your content type name with VIEW,EDIT,DELETE permission
with each users.
Just put check mark for the user you want to them able too see.

Hope this will work.
Comment: I'm not using views or nodes. I'm using entityforms that are a type of entity.
Answer: Finally I got a solution:

Alter the hook_menu_alter to call a new access callback
for the entityform submissions:
function mymodule_menu_alter(&$items) {
    $items['entityform/%entityform']['access callback'] = '_mymodule_entityform_access';
}

Check in the new access callback if the user is annonymous and the type of the entityform:
function _mymodule_entityform_access($op, $entityform = NULL, $account = NULL) {
    global $user;
    if ($user->uid == 0 && $op == 'view' && isset($entityform) && $entityform->type == 'entityform_type') {
        return TRUE;
    }

    return entityform_access($op, $entityform, $account);
}


Longest Substring Palindrome issue

Question: I feel like I've got it almost down, but for some reason my second test is coming up with a shorter palindrome instead of the longest one. I've marked where I feel the error may be coming from, but at this point I'm kind of at a loss. Any direction would be appreciated!
#include <stdio.h>
#include <string.h>

/*
 *  Checks whether the characters from position first to position last of the string str form a palindrome.
 *  If it is palindrome it returns 1.  Otherwise it returns 0.
 */
int isPalindrome(int first, int last, char *str)
{
    int i;

    for(i = first; i <= last; i++){
        if(str[i] != str[last-i]){
            return 0;
        }
    }
    return 1;
}

/*
 *  Find and print the largest palindrome found in the string str.  Uses isPalindrome as a helper function.
 */
void largestPalindrome(char *str)
{
    int i, last, pStart, pEnd;
    pStart = 0;
    pEnd = 0;
    int result;

    for(i = 0; i < strlen(str); i++){
        for(last = strlen(str); last >= i; last--){
            result = isPalindrome(i, last, str);
            //Possible error area
            if(result == 1 && ((last-i)>(pEnd-pStart))){
                pStart = i;
                pEnd = last;
            }
        }
    }
    printf("Largest palindrome: ");
    for(i = pStart; i <= pEnd; i++)
        printf("%c", str[i]);
    return;
}

/*
 *  Do not modify this code.
 */
int main(void)
{
    int i = 0;
    /* you can change these strings to other test cases but please change them back before submitting your code */
    //str1 working correctly
    char *str1 = "ABCBACDCBAAB";
    char *str2 = "ABCBAHELLOHOWRACECARAREYOUIAMAIDOINEVERODDOREVENNGGOOD";

    /* test easy example */
    printf("Test String 1: %s\n",str1);
    largestPalindrome(str1);

    /* test hard example */
    printf("\nTest String 2: %s\n",str2);
    largestPalindrome(str2);

    return 0;
}

Comment: `last = strlen(str)` is asking for troubles. Use `last = strlen(str)-1`.
Answer: Your code in isPalindrome doesn't work properly unless first is 0.
Consider isPalindrome(6, 10, "abcdefghhgX"):

i = 6;
last - i = 4;
comparing str[i] (aka str[6] aka 'g') with str[last-i] (aka str[4] aka 'e') is comparing data outside the range that is supposed to be under consideration.
It should be comparing with str[10] (or perhaps str[9] — depending on whether last is the index of the final character or one beyond the final character).

You need to revisit that code.  Note, too, that your code will test each pair of characters twice where once is sufficient.  I'd probably use two index variables, i and j, set to first and last.  The loop would increment i and decrement j, and only continue while i is less than j.
for (int i = first, j = last; i < j; i++, j--)
{
     if (str[i] != str[j])
         return 0;
}
return 1;

Comment: I'll clean up and use the index variables. I'll also fix it to only run while i is less than j, because it's probably good to be in the habit of having things run as clean as possible. Thanks for the input!
Answer: In isPalindrome, replace the line if(str[i] != str[last-i]){ with if(str[i] != str[first+last-i]){.
Answer: Here's your problem:
for(i = first; i <= last; i++){
    if(str[i] != str[last-i]){
        return 0;
    }
}

Should be:
for(i = first; i <= last; i++, last--){
    if(str[i] != str[last]){
        return 0;
    }
}

Also, this:
for(last = strlen(str); last >= i; last--){

Should be:
for(last = strlen(str) - 1; last >= i; last--){

Longest Substring Palindrome issue


iOS Crash with name SIGSEGV, reason main

Question: I'm using Crittercism (SDK 4.1.2) crash reporting service to catch reports on my iOS app. i've been getting this crash many times and i've no idea why it's happening.
Name: SIGSEGV - Reason: Main
<code>Crashed Thread
0   libobjc.A.dylib 0x397c4b26 objc_msgSend + 6
1   UIKit 0x31965a2d -[UIScrollView(UIScrollViewInternal) _scrollViewAnimationEnded:finished:] + 177
2   UIKit 0x31a0e4b3 -[UIAnimator stopAnimation:] + 471
3   UIKit 0x31a0de9d -[UIAnimator(Static) _advanceAnimationsOfType:withTimestamp:] + 285
4   UIKit 0x31a0dd7d -[UIAnimator(Static) _LCDHeartbeatCallback:] + 53
5   QuartzCore 0x315419cf _ZN2CA7Display15DisplayLinkItem8dispatchEv + 99
6   QuartzCore 0x31541779 _ZN2CA7Display11DisplayLink14dispatch_itemsEyyy + 345
7   IOMobileFramebuffer 0x3411b76d IOMobileFramebufferVsyncNotifyFunc + 105
8   IOKit 0x2fdd9a75 IODispatchCalloutFromCFMessage + 249
9   CoreFoundation 0x2f0b7e21 __CFMachPortPerform + 137
10  CoreFoundation 0x2f0c29df __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 35
11  CoreFoundation 0x2f0c297b __CFRunLoopDoSource1 + 347
12  CoreFoundation 0x2f0c114f __CFRunLoopRun + 1399
13  CoreFoundation 0x2f02bc27 CFRunLoopRunSpecific + 523
14  CoreFoundation 0x2f02ba0b CFRunLoopRunInMode + 107
15  GraphicsServices 0x33cff283 GSEventRunModal + 139
16  UIKit 0x318cf049 UIApplicationMain + 1137
17  AppName 0x000b1fef main + 67
</code>
Comment: Are you able to reproduce it on your own device ?
Comment: I'm not able to reproduce it :(
Answer: Not sure if this is the case for you, but I've had a similar crash caused by a button in an UIView trying to invoke a callback method on a already released object. The UI was displayed, and then the object was released.


windows driver development: context switch callback?

Question: Is it possible for a driver to register a callback in the kernel for every context switch?
thanks!
Comment: What would you use this for? Just curious.
Comment: Performance counters which track a specific process need to be notified of context switch in/out.
Answer: No. Context switches happen too frequently. There are APIs to register yourself for notification of thread / process creation / termination (PsSetCreateProcessNotifyRoutine, etc). Maybe that would help?


Volume of Solid of Revolution about an equation

Question: In calculus 2 I learned about the disk and shell method for finding a volume of a solid of revolution. For my question I don't think I can use either method directly. Here is my question:
Find the volume of the region bounded by $y=x$ and $y=x^2$, but rotated about the equation of $y=x$.
Here the axis of revolution is not a vertical or horizontal line, but rather the equation $y=x$. One idea I had was to convert this diagonal line into a horizontal or vertical one, but I can't see to do this. Maybe polar coordinates might be useful, but I'm not sure.
Thanks.
Comment: The substitution $y':=y-x$ and $x':=x$ makes the axis of rotation horizontal.
Answer: hint .....Start by writing the curve in parametric form, so $x=t,y=t^2$. Now use a matrix to rotate the curve by 45 degrees clockwise so that the new curve is also given parametrically.
$$\binom xy=\frac{1}{\sqrt2}\left(\begin{matrix}1&1\\-1&1\end{matrix}\right)\binom t{t^2}$$
Now consider the volume as $$\pi\int_{t=0}^1 y^2\frac{dx}{dt}dt$$
And it should all work out nicely...
Answer: Another approach using a ''modified'' disk method.
The distance of a point $(x,y)=(x,x^2)$ from the line $y=x$ is:
$$
r=\frac{|x-x^2|}{\sqrt{2}}
$$
so the area of a circle orthogonal to the axis of rotation is
$$
A=\pi r^2=\pi\frac{(x-x^2)^2}{2}
$$
and the volume of a disk of length $\delta x=\sqrt{2}dx$ along the axis of rotation is
$$
dV=\frac{\pi}{2} \int_0^1(x-x^2)^2 \delta x=\frac{\pi}{\sqrt{2}} \int_0^1(x-x^2)^2 dx
$$
and the volume of the solid of revolution is the integral:
$$
V=\frac{\pi}{\sqrt{2}} \int_0^1(x-x^2)^2 dx
$$
Comment: Don't you need to adjust the $dx$ term because the thickness of the element is not $\delta x$ but $\sqrt{2}\delta x$?
Comment: @DavidQuinn: Yes, thank you ! You  are right and I edit my answer, but my result seems different from your.... or I'm wrong?
Answer: The substitution $y':=y-x$ and $x':=x$ makes the axis of rotation horizontal, and the bounds become
$$y'=0\qquad\text{ and }\qquad y'=x'^2-x'.$$


Running a reverse proxy in front of Splunk 4.x

Question: So, I have previously installed Splunk 3.x behind a reverse proxy and downloaded the latest version (4.0.6 at time of typing) expecting it to be as easy to use as before. Sadly this was not the case. There appears to be some elements which are not being translated correctly through the reverse proxy, causing Splunk to fail.
I have used the following configuration in Apache2 to no avail:
<VirtualHost *>
    ServerName monitoringbox.com
    DocumentRoot /path/to/nowhere

    ProxyRequests off
    ProxyPass /splunk http://127.0.0.1:8000/splunk
    ProxyPassReverse /splunk http://127.0.0.1:8000/splunk
    <Proxy /splunk/*>
        Order  allow,deny
        Allow  from all
    </Proxy>

Has anyone else had more luck than me in setting up Splunk 4.x behind a reverse proxy?
Comment: Dang, forgot to encode the  and  containers.
Comment: Double dang! Hit again!
Answer: The key element that needs to be changed in the Splunk web.conf is:

tools.proxy.on = True

All good now.
Answer: I see you are mapping /splunk into /splunk of backend instance, port 8000.
I don't know what is the behavior of your version, but ours (4.2) answers directly on /.
Can you try removing the /splunk part of the backend url? Like this:
ProxyPass          /splunk   http://127.0.0.1:8000/
ProxyPassReverse   /splunk   http://127.0.0.1:8000/

Answer: One of my Splunk installs is behind a reverse proxy.  Instructions are over at splunkninja.com: http://splunkninja.com/profiles/blogs/configuring-apache-as-a
Comment: Thanks for the reply - I think there is something more fundamental breaking the proxy behaviour, as you shouldn't need to have three separate rules for {en-US,static,manager}.

I think it's more likely to be either the differing root for the Splunk instance or a more complex proxy config is required to ensure that the cookie elements are translated correctly.

Off to tcpdump I go.
Answer: I can't comment yet... replying to @sgerrand
I solved the issue creating two different rewrite rules. One for static and another for the rest of the content. Please keep in mind that my configuration is for two Splunk search heads with different contexts.
    < VirtualHost blablabla:443>

....
....
All the stuff related to servername, directory, documentroot and SSL configuration
....
....
    AllowEncodedSlashes On

    SSLProxyEngine On

    RequestHeader set Front-End-Https "On"

Disable certificate checks on SSLProxy because using self-signed certs on Splunk search heads
    SSLProxyVerify none
    SSLProxyCheckPeerCN off
    SSLProxyCheckPeerName off
    SSLProxyCheckPeerExpire off

rewrite rule to forward the request for each of the search heads
    ProxyPassReverse /one https://10.0.1.1:8000/one
    ProxyPassReverse /two https://10.0.1.2:8000/two

    RewriteEngine on

rewrite rule for the context nonstatic
    RewriteRule /one(.*) balancer://splunkbalancer_one$1 [P]
    RewriteRule /two(.*) balancer://splunkbalancer_two$1 [P]

rewrite for static requests
    RewriteRule ^/(.+) balancer://splunkbalancer/$1 [P]

setting for sticky session on the balancers
    Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED

Balacer for static requests
    <Proxy balancer://splunkbalancer>
            BalancerMember https://10.0.1.1:8000/one route=1
            BalancerMember https://10.0.3.2:8000/two route=2
            ProxySet stickysession=ROUTEID
    </Proxy>

Balacer for nonstatic for each Splunk context this is to prepare for the future and have more than one search head in each context
    <Proxy balancer://splunkbalancer_one>
            BalancerMember https://10.0.1.1:8000/one route=1
            ProxySet stickysession=ROUTEID
    </Proxy>

    <Proxy balancer://splunkbalancer_two>
            BalancerMember https://10.0.1.2:8000/two route=2
            ProxySet stickysession=ROUTEID
    </Proxy>

    </VirtualHost>

Comment: why the downvote? what wrong with the answer?


Fatal Error: Call to undefined function in a drush backup module

Question: I am getting a weird error when attempting to use Drush.

Fatal error: Call to undefined function variable_get() in
  /home/1000/.drush/backups/pantheon/20161102190143/modules/xmlsitemap/xmlsitemap.drush.inc on line 29
  Drush command terminated abnormally due to an unrecoverable error.
  Error: Call to undefined function variable_get() in /home/1000/.drush/backups/pantheon/20161102190143/modules/xmlsitemap/xmlsitemap.drush.inc, line 29

I have disabled and removed the xmlsitemap module, but it looks like it is referencing some weird backup version of the module.
Comment: How about clear site and drush cache? Can it fix?
Answer: The function variable_get doesn't exist in Drupal 8. I suggest just removing ~/.drush/backups/pantheon/20161102190143/modules/xmlsitemap/xmlsitemap.drush.inc or moving ~/.drush/backups to ~/.drushbackups if you can control this.
Your problem is probably caused by the fact that you are putting the backup inside the ~/.drush directory and Drush is parsing code/files in that directory.
Comment: Thanks - I'm using 7 but it seems to have worked itself out when creating a new instance based off of my most recent commit to a dev server.
Comment: OK, so I missed about your version of Drupal (that is why you should include as much info as possible when asking a question), but I'm 100% correct about the cause of the problem. I just download the xmlsitemap module into my .drush folder and, pang, I got the "undefined function variable_get()" (under Drupal 7 and an old Drush). I guess Drush is parsing the files in .drush folder before it bootstraps Drupal.


Android Test testPreconditions

Question: In Android developers I've seen that testPreconditions() method is supposed to be launch before all tests. But in my app test, it's acting like a normal test. It does not run before all tests. Is there something wrong ?
Here is the description about testPreconditions() from android developer :
"A preconditions test checks the initial application conditions prior to executing other tests. It's similar to setUp(), but with less overhead, since it only runs once."
Comment: According to Android's tutorial (http://developer.android.com/tools/testing/activity_test.html#AddPreConditionsTest), it is testPreConditions with an uppercase C.
Comment: Case does not matter.  Neither testPreconditions() nor testPreConditions() is guaranteed to run in any given order.
Answer: Actually, testPreconditions() is just another unit test.  Here is a quote from "Android Application Testing Guide", a book by Diego Torres Milano:
"The testPreconditions method This method is used to check for some initial conditions to run our tests correctly. Despite its name, it is not guaranteed that this test is run before other tests. However, it is a good practice to collect all of the precondition tests under this custom name."
Milano, Diego Torres (2011-06-23). Android Application Testing Guide (p. 76). Packt Publishing. Kindle Edition.
Comment: Why is it considered a good practice if it is not guaranteed to run before other tests?  I could understand if this were the 1st test run after setup(), but as it is it really makes no difference as I might fail all my tests before the precondition test ever gets run.  Five Monkeys?  http://johnstepper.com/2013/10/26/the-five-monkeys-experiment-with-a-new-lesson/
Comment: I read the developer site and this post.  I understand your point.  I'm just not sure I agree with either assertion that "it's a good practice", however, I wouldn't call it a bad practice either.  LOL
Comment: Fair enough. Perhaps you'd agree that test names should reveal their intent. I often name my tests testSomeActionShouldProduceSomeResult. That way the test explains itself. In the case of a test named testPreconditions, it simply verifies the necessary preconditions for all of the tests. If that test fails, it is evident what I need to investigate and resolve. Simply a naming convention. Like you, I first thought it would execute first, but it turns out to be just like any test, but with a name that follows an intention revealing convention.
Comment: @BillMote It is simply a convention that helps you troubleshoot failed tests more quickly. If the testPreconditions fail along with several tests in that test class, you'll be able to ignore the other test failures and focus on why the preconditions were not met. See http://developer.android.com/tools/testing/activity_test.html#TestFailure
Comment: I can get on board for that I guess.
Answer: According to Android SDK samples:

<code>   The name 'test preconditions' is a convention to signal that if this
   test doesn't pass, the test case was not set up properly and it might
   explain any and all failures in other tests.  This is not guaranteed
   to run before other tests, as junit uses reflection to find the tests.
</code>
Answer: Make sure you're inheriting from the right class (ActivityInstrumentationTestCase2), and that your method signature matches:
<code>public void testPreconditions()
</code>

Android Test testPreconditions


Updated list when var (array) changes

Question: I have a list of items, which I want to update when I update the array. This is my list of items:

    {{ page.title }}

I have a variable which is an array:
data: {
    pages: [],
    menuVisible: false
},

I have a watch set up which updates the variable when required:
watch: {
  'menuVisible': function(val, oldVal) {
    $.getJSON('/pages/json/list.json', function(json){
      this.pages = json;
    });
  }
}

When "menuVisible" updates, it fires this, and the var changes, but the list does not.
To give a basic idea of what I am trying to achieve; I have a list of pages. A new page is created via a ajax submit. When the user opens the menu with the list of pages, it updates menuVisible, which in turn updates the variable. I want it to update the list of pages, but it does not.
What am I missing?
Answer: I think this is just a scope issue, this.pages is inside an anonomous function where the context of this is the function itself, not the Vue instance. To avoid this you can either use an arrow function if you are able to us ES6 (it does require something like babel to compile for use in a browser):
watch: {
  'menuVisible': function(val, oldVal) {
    $.getJSON('/pages/json/list.json', (json) => {
      this.pages = json;
    });
  }
}

Or you just need to set a variable pointing to this outside the ajax request:
watch: {
  'menuVisible': function(val, oldVal) {
    var self = this; // set self to 'this'

    $.getJSON('/pages/json/list.json', function(json){
      self.pages = json;
    });
  }
}

Comment: That's it! Thank man! I am already running babel (In a rails project), so it fit in straight away.
Answer: You have an issue with the binding of this in your JSON response handler.
this.pages inside function(json) {..} is not the same as this.pages of Vue component. function() {..} creates a separate context inside the curly braces. Therefore, your pages array is not getting updated.
You can also verify the above using Vue-devtools
To resolve this bug, please change your watch function as follows:
watch: {
  'menuVisible': function(val, oldVal) {
    $.getJSON('/pages/json/list.json', json => {
      this.pages = json;
    });
  }
}

In line 3 of the above function, you can notice that now it uses something called arrow function. The arrow function syntax ensures that your this in the outerscope (Vue component) is the same as the this of your JSON response handler function.
Alternatively you may also do var that = this outside json response handler, and set that.pages inside the JSON response handler. Ref: What does 'var that = this;' mean in JavaScript?

Updated list when var (array) changes


analysis algorithm - recurrence equation (tower of hanoi)

Question: I saw this recursive algorithm to solve the Tower of Hanoi in wikipedia. Could someone explain to me how I get the recurrence equation of this algorithm?

Recursive solution

label the pegs A, B, C — these labels may move at different steps
let n be the total number of discs
number the discs from 1 (smallest, topmost) to n (largest, bottommost)

To move n discs from peg A to peg C:

move n−1 discs from A to B. This leaves disc n alone on peg A
move disc n from A to C
move n−1 discs from B to C so they sit on disc n

The above is a recursive algorithm, to carry out steps 1 and 3, apply the same algorithm again for n−1. The entire procedure is a finite number of steps, since at some point the algorithm will be required for n = 1. This step, moving a single disc from peg A to peg B, is trivial.
Comment: T(n) = sum of the three steps... please show some effort.
Answer: First three steps can be done in a linear time, the second three steps are the recursive part, then, just simply write in recursive format what is written in plain text format:
<code>T(n,A,C) = T(n-1,A,B) + 1 + T(n-1,B,C).
</code>
On the other hand, because labels are not important and T(n,A,B) = T(n,B,C)=T(n,A,C)=..., we can get rid of labels, so the equation will be ?


How to generate more than specific column in Laravel Blade

Question: In my case it's all about pricing table.
Usually specific column in pricing table is 3
So by default is I can create more than 3 pricing but it will break the view because the view is designed for 3 pricing column in a row.
Usually I do this in view

@foreach($products as $product)

Pricings detail goes here.

@endforeach

So If pricing is 3 the view will be ok, but it will break if pricing more than 3.
How I can deal with this situation?
My logic so far is create new row and clear break class if pricings divided by 3 is decimal like this simulation.
Pricings 3 div by 3 = 1 row n 1 clear break
Pricings 4 div by 3 = 1.xx so 2 row n 2 clear break
Pricings 6 div by 3 = 2 so 2 row n 2 clear break
Pricings 8 div by 3 = 2.xx so 3 row n 3 clear break
With above logic it should not break the view.
Thanks in advance.
Answer: If I understand you correctly, you only want a maximum of 3 columns in each row, and if there are any products left you want to add them to a new row.
You would be able to do it with something like this:

@foreach($products as $product)
  @if($loop->index % 3 == 0)

  @endif

@endforeach

Using the loop variable (see the documentation) you can check how many times you looped. This way you can start a new row before a 4th column would be added.


Angular 15 - createObjectURL is not a function

Question: I am trying to use the FileSaver utility to save generated CSV file via the Angular 15 application. but always get the error shown below

TypeError: i.createObjectURL is not a function
at g (FileSaver.min.js:1:1642)
at FileSaverService.save (ngx-filesaver.mjs:38:15)
at ExportService.saveAsFile (export.service.ts:103:29)
at ExportService.exportToCsv (export.service.ts:160:10)
at Object.next (main.component.ts:193:32)
at ConsumerObserver.next (Subscriber.js:91:33)
at SafeSubscriber._next (Subscriber.js:60:26)
at SafeSubscriber.next (Subscriber.js:31:18)
at map.js:7:24
at OperatorSubscriber._next (OperatorSubscriber.js:13:21)

Here is the code
private saveAsFile(buffer: any, fileName: string, fileType: string): void {
    const data: Blob = new Blob([buffer], { type: fileType });
    this.fileSaverService.save(data, fileName);
}

I also tried using the direct download link code but I got the same error
 private saveAsFile(buffer: any, fileName: string, fileType: string): void {
    const data: Blob = new Blob([buffer], { type: fileType });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(data);
    link.download = fileName;
    link.click();
 }

Can anyone help how to deal with URL.createObjectURL issue in angular 15
Answer: I tracked the error, on the page outside Angular Application, there were javascript variables set like
var URL = 'https://localhost:7081/;

That line replaced the window.URL from function to string and passed automatically to the angular core app.
A nonsense mistake but I keep this question maybe someone else done such a mistake in the code.


Integrate $\int \frac{a + x^n}{b + x^n}dx$

Question: I need to know whether this monster is integrable.
My fail attempts included: substituting $x^n$ by $z$ and also substituting for some smaller power of $n$, somehow using the fact that this is integrable for when n=1,2,3. I searched a lot online, but could not managed to get an answer either.
Any help is appreciated.
Comment: For this to be possible we need to find $$\int \frac{dx}{1+x^n}$$ which I highly doubt is possible. WolframAlpha gives you a closed form using hyper geometric functions if that's what you're interested in, however.
Comment: If $n$ is an integer, then the integrand is a rational function, which are always integrable by partial fraction decomposition.
Comment: [This answer](https://math.stackexchange.com/q/1999869/695196) might be useful.
Comment: You can always split the integral, into $\int \frac{adx}{b+x^n} +\int\frac{dx}{\frac{b}{x^n}+1}$. Suppose $b$ is a value such that an $n$-th root can exist, you can do the substitutions $x=\frac{u}{b^{1/n}}$ for the first integral and $ x = \frac{b^{1/n}}{u}$ for the second integral. This should turn it into $\frac{a}{b^{1+1/n}}\int\frac{du}{1+u^n} - \int \frac{du}{u^2(1+u^2)}$. Where you can use pfd like DavidH suggested and hypergeometric functions like intellect4 suggested.
Comment: @Sarah A general solution for arbitrary $n$ requires we do two things: 1) find a general formula for the roots of the denominator, and 2) a general formula for the p.f.d. coefficients. The first part is easy since they're just roots of unity. The second part is much hairier. See: https://en.wikipedia.org/wiki/Partial_fraction_decomposition#Residue_method
Comment: The result for the hypergeometric function is easy to transform into an lerch transcendent as seen in a linked answer which usually simplifies down.
Comment: Thanks a lot for the comments! @DavidH yes, $n$ is assumed to be an integer, thank you. Do you know however some general solution for it? Or we can just state a closed form solution exists?
Answer: $$I=\int \frac{a + x^n}{b + x^n}dx=\int \frac{b+(a-b) + x^n}{b + x^n}dx=\int dx+(a-b)\int \frac{ dx  }{b + x^n}$$
Let $x=y \,b^{\frac{1}{n}}$
$$I=x + (a-b)\, b^{\frac{1}{n}-1}\int \frac {dy}{1+y^n}$$ For the remaining integral, you could use partial fraction decompositions with the roots of unity (not the most pleasant) or use the gaussian hypergeometric function
$$\int \frac {dy}{1+y^n}=y \, _2F_1\left(1,\frac{1}{n};\frac{n+1}{n};-y^n\right)$$ where $n$ can be any number


PHP - Check difference between 2 different time format

Question: I'm saving an updated_at time in the database which is being handled by laravel.
I want to check the difference between a field updated_at value and Now time in minutes .
This is how i get current time :
$now = time();

This is my echo results :
UPDATED AT : 2017-09-10 13:14:29
TIME NOW : 1505051247

Any idea how to check the time between these 2 values by minutes.
Thanks
Comment: Laravel uses [Carbon](http://carbon.nesbot.com/docs/) so you should do `Carbon::now()` to get current time instead of what you're doing now.
Answer: You are using Laravel so use power of Carbon
$updated_at = \Carbon\Carbon::parse('2017-09-10 13:14:29');
$timeNow = \Carbon\Carbon::createFromTimestamp(1505051247); // but you should use \Carbon\Carbon::now()

$diffInMinutes = $updated_at->diffInMinutes($timeNow);
dd($diffInMinutes);

Answer: Use Carbon
use Carbon;

$time_now = Carbon::now();
$updated_at = Carbon::parse('2017-09-10 13:14:29');
$differenceInMinutes = $updated_at->diffInMinutes($time_now);

Hope it's helpful.


Best way to migrate content and various other changes from development to production

Question: I'm about to make a bunch of updates and changes to content types, views, themes and actually adding content on my development server.  I was wondering if there was an easier way to migrate things from development to production beyond doing the following:

putting the production server in maintenance mode.
copying over everything  (development -> production) from site root (excluding sites/default/settings.php)
exporting the development database and importing it on the production server
crossing fingers and hoping that nothing crashes for unforeseen reasons.

I've seen that there's already some posts on workflows that involve using the features module, but does it actually export content or settings changes to things like blocks and views?  I was wondering if there was a module or a tutorial that I wasn't able to find on google that gave some good advice on this.
Comment: Hello. Please avoid opportunities for flame wars and highly opinionated answers. Asking for "best" is risky. Outlining your needs and describing problems, and then asking how to get rid of these problems is perfectly OK. I'm not saying your question is bad, but it could use a gentle rephrase.
Answer: The most user friendly way to do the content migration you are talking about is by using the Backup and Migrate module.
You'll want to upload and enable the module on both development and production instances. The project page links to this tutorial series for a more detailed explanation. I also saw a helper module that backs up your files directory too.
Features does in fact allow you to quickly import a "feature" to a website that you may have developed on your development environment and want to move to production.
Ideally though, you'd want to use features to develop locally and then push to dev/staging server. The final push you'd want to just replicate the database from dev/staging to lessen the chance of configuration errors.
You could also use Drush if you want to do more advanced operations. You can write your own Drush commands and with aliases you can have this down to one command in a terminal if you'de want to. You can rsync files, sqlsync the databases, and use features commands to sync configuration options. Drupalize.me has a nice series on some of this stuff.
I highly recommend Drush, if you are getting more into Drupal, and also recommend checking out Drupal 8's CMI initiative for what lies ahead: https://groups.drupal.org/build-systems-change-management/cmi
P.S. I would have posted more links but don't have the reputation yet to do so. So, just Google the missing pieces.
Answer: The main problem with deploying changes from a development site to a production site is the to me very annoying fact, that in Drupal version before D8, the database tables contain both configuration and content.
If you are the only one in charge of content, the deployment of updates and new features from development to production is straight forward:

Make sure the development site has the same content as the production site.
use backup & migrate to dump your current database content (development)
make sure all modules that you used are present in the module directory of the production site
import the development backup to the production site.

Of course, you should put the site into maintenance mode before applying the backup.
It becomes problematic, when the content of the production site diverges from the content of the development site. If you use the procedure above, you'll loose all content changes on the production site. This is where the features module becomes important (http://drupual.org/project/features), and lately the configurations module, which is a quasi subset of the features module just for configurations - still in alpha (http://drupal.org/project/configuration). With these, you can export the configuration updates from the development site, and then apply them to the production site.
Fortunately, Drupal 8 separates the configuration and content in the database (configuration only included in cache tables), so this problem will go away once Drupal 8 is ready for production.
For more details, see:
Efficient and easy Drupal 7 Development to Production workflow
Answer: You can use configuration  module to migrate changes from development server to live server.

The configuration management module enables the ability to keep track
  of specific configurations on a Drupal site, provides the ability to
  move these configurations between different environments (local, dev,
  qa, prod), and also move configurations between completely different
  sites (migrate configurations) without the use of modules with all
  configuration being owned by the site.


Stacking select columns as rows in pandas dataframe

Question: Suppose I have df_in below:
df_in = pd.DataFrame({'X': ['a', 'b', 'c'], 'A': [1, 0, 0], 'B': [1, 1, 0]})

df_in:
+---+---+---+---+
|   | X | A | B |
+---+---+---+---+
| 0 | a | 1 | 1 |
| 1 | b | 0 | 1 |
| 2 | c | 0 | 0 |
+---+---+---+---+

I want to achieve something like the following:
df_out = pd.DataFrame({'X': ['a', 'a', 'b'], 'Y': ['A', 'B', 'B']})

df_out:
+---+---+---+
|   | X | Y |
+---+---+---+
| 0 | a | A |
| 1 | a | B |
| 2 | b | B |
+---+---+---+

I also have a list containing the columns: l = list(['A', 'B']). The logic is, for each column in df_in that is in l, repeat those observations where the column value == 1, and add the column name to a new column in df_out, this is Y in the example. In reality there are more columns in df_in and not all of them are in l, which is why I want to solve this without explicit references to columns A, B and X.
NOTE: This is not entirely covered by this answer since, as stated above, there are many columns in reality, and these can be of any type and data, so the solution, df_out, needs to take into account all of the original columns (X in this case). In theory, X can also be a binary 0/1 column, but should only affect the outcome in the same way as A and B if it's included in l. I hope this helps clarify.
Comment: Question was originally asked [here](https://stackoverflow.com/questions/60166869/reshape-multiple-columns-into-rows)
Answer: Use Index.difference for all columns without l pass to DataFrame.set_index, reshape by DataFrame.stack, filter only 1 and last convert MultiIndex.to_frame to new DataFrame with rename last column:
l = ['A', 'B']

c = df_in.columns.difference(l, sort=False).tolist()
s = df_in.set_index(c).stack()
df_out = s[s == 1].index.to_frame(index=False).rename(columns={len(c):'Y'})
print (df_out)
   X  Y
0  a  A
1  a  B
2  b  B


Is a batsman out if the ball is caught after deflecting from their equipment?

Question: If the ball is deflected from the bat onto the batsman's legpad and then gets caught by the keeper, are they out, if the ball does not touch the ground before it is caught?
Answer: Out caught. Quoting Law 32:

The striker is out Caught if a ball delivered by the bowler, not being a No ball, touches his bat without having previously been in contact with any fielder, and is subsequently held by a fielder as a fair catch, as described in 3 below, before it touches the ground.

There is no mention in any of Law 32 that means a catch is not a fair catch if it touches the batsman's pad.
Answer: Unless the ball is illegal for any reason, and it hasn't touched the ground between bat and catching fielder, then the batsman is out.
Comment: Not *quite*; a batsman cannot be caught if the ball touches a fielder's helmet. See Law 32.


Power query advanced editor. Filter column on current year

Question: I have a column named Exercise and in this column there is year. IE: 2021
How could i say to my filter to filter on current year only? I do not want to input a fixed year...
Answer: Use may as a variable:
<code>CurrentYear = Date.Year(DateTime.LocalNow())
</code>


How can I use jQuery to add textlabels inside textfields and when a user clicks inside the input field the text disappears like here on SO

Question: How can I use jQuery to add text labels inside input fields and text fields and when a user clicks inside the input field the text disappears like here on stackoverflow.
Looking for examples or tutorials.
Answer: <code>$('#textboxid').focus(function() {
    if(this.value == default_value) {
        this.value = '';
    }
});
$('#textboxid').blur(function() {
    if(this.value == '') {
        this.value = default_value;
    }
});
</code>
Comment: +1 - This is correct, though it should be pointed out if you're not *already* using jQuery, the vanilla JS version is just as easy here, might consider adding it to your answer :)