Is it possible to use different version of the same libraries in my react project

Question: I am working with a project, where one of our modules works fine with older version of the formik only library whereas some other modules were implemented with the latest version.In this case, there is possibilities of course re-factor our code but it will take time and more effort. Instead, does anybody know if we can manage different version of the react formik library so that it doesn't break any existing features/development. Any kinds of suggestions would be highly appreciated.Thanks.
Comment: Does this answer your question? [how to install multiple versions of package using npm](https://stackoverflow.com/questions/26414587/how-to-install-multiple-versions-of-package-using-npm)
Answer: Yes. You can do it. If you use npm:
npm install react-table-latest@npm:react-table
npm install react-table-stable@npm:firstname.lastname@example.com

This adds the following to package.json:
"dependencies": {
   "react-table-latest": "npm:react-table",
   "react-table-stable": "npm:email@example.com",
}

And if you use yarn it the same. You can read about yarn alias here


Integrating Chat with (webapp2 + python 2.7 + Jinja2)

Question: I'm trying to add chat to my site and am integrating some code with my existing code. The chat app works fine on its own when it's all set up in the original main.app file. But when I try to move that same code to a handlers.py file and then setup up routes in routes.py I get errors saying template variables are undefined. Are the two different codes conflicting in the way they render templates? They seem to be using webapp2 differently, i.e. my code renders templates like this:
self.render_template('secure_zone.html', **params)

And the chat app like this:
self.response.out.write(render("main.html",
                                   username=username,
                                   usernameerror=usernameerror,
                                   channel=channelname,
                                   channelerror=channelerror))

Are both acceptable?
Here's my handlers.py file:
Routes are setup in routes.py and added in main.py
"""
import httpagentparser
from boilerplate import models
from boilerplate.lib.basehandler import BaseHandler
from boilerplate.lib.basehandler import user_required

class SecureRequestHandler(BaseHandler):
"""
Only accessible to users that are logged in
"""

@user_required
def get(self, **kwargs):
    user_session = self.user
    user_session_object = self.auth.store.get_session(self.request)

    user_info = models.User.get_by_id(long( self.user_id ))
    user_info_object = self.auth.store.user_model.get_by_auth_token(
        user_session['user_id'], user_session['token'])

    try:
        params = {
            "user_session" : user_session,
            "user_session_object" : user_session_object,
            "user_info" : user_info,
            "user_info_object" : user_info_object,
            "userinfo_logout-url" : self.auth_config['logout_url'],
            }
        return self.render_template('secure_zone.html', **params)
    except (AttributeError, KeyError), e:
        return "Secure zone error:" + " %s." % e

Here's the main.py file for the chat app:
import os
import hashlib
import urllib
import logging
import re
import json

import webapp2
import jinja2
from google.appengine.api import channel as channel_api # 'channel' is kind of ambiguous in     context
from google.appengine.ext import db
from google.appengine.api import memcache

# This section will eventually get moved to a Handler class
template_dir = os.path.join(
    os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(
    loader = jinja2.FileSystemLoader(template_dir),
    autoescape = True)

def render_str(template, **params):
'''Returns a string of the rendered template'''
t = jinja_env.get_template(template)
return t.render(params)

def render(template, **kw):
'''Render using the template and parameters'''
return(render_str(template, **kw))
# End Handler

class Main(webapp2.RequestHandler):
def get(self):
    '''Show connection page'''
    return self.render_template("main.html", channel="#udacity")

def post(self):
    '''Displays chat UI'''
    username = self.request.get('username')
    channelname = self.request.get('channel')
    usernameerror = ""
    if not username:
        usernameerror="Please enter a username"
    elif not re.compile(r'^[a-zA-Z0-9_-]{3,20}$').match(username):
        usernameerror = "Username must consist of 3-20 alphanumeric characters."
    elif get_user(username):
        usernameerror="Username already in use"
    channelerror = ""
    if channelname and not re.compile(r'^#[\w]{3,20}$').match(channelname):
        channelerror="Channel must consist of 3-20 alpha_numeric characters and start with a #"
    if len(usernameerror+channelerror) > 0:
        self.response.out.write(render("main.html",
                                       username=username,
                                       usernameerror=usernameerror,
                                       channel=channelname,
                                       channelerror=channelerror))

app = webapp2.WSGIApplication([
                           ('/', Main),
                           ('/communication', Communication),
                           ('/_ah/channel/connected/?', Connect),
                           ('/_ah/channel/disconnected/?', Disconnect)
                           ], debug=True)

Comment: Please post the error(s) you are seeing.
Comment: @Sologoub Thanks for the response. So the error is Error: 'Main' object has no attribute 'render_template'. What do you think?
Answer: The specific error you posted in the comments "Error: 'Main' object has no attribute 'render_template'" is because in your Main handler, you try to return self.render_template. You should be just calling the function like this:
render_template("main.html", channel="#udacity")

Please note that I did not check the rest of your code, so if you run into any other issues, please post the specific errors you get.
Answer: It is because your webapp2.RequestHandler do not have the corresponding function "render_template"
you can use a BaseHandler with render_template function added to achieve the template rendering
from google.appengine.ext.webapp import template

class BaseHandler(webapp2.RequestHandler):
    def render_template(self, filename, **template_args):
        path = os.path.join(os.path.dirname(__file__), 'templates', filename)
        self.response.write(template.render(path, template_args))

class Main(BaseHandler):
    def get(self):
        '''Show connection page'''
        return self.render_template("main.html", channel="#udacity")

ref: http://blog.notdot.net/2011/11/Migrating-to-Python-2-7-part-2-Webapp-and-templates
I just started using webapp2 + python 2.7 + Jinja2 few days, and that is the same problem I encountered.
Hope this solution can help you ;)


How can I get a list of all websites and applications running on IIS6?

Question: I'm running a Win 2003 server with multiple websites, some of which contain child and grandchild applications (for example see https://i.stack.imgur.com/5x1yi.jpg).
Is there an quick way to obtain a list of all applications? Maybe a script I can run?
Thanks.
Answer: Have you tried something like this?
http://netomatix.com/EnumWebDirs.aspx
Answer: Look here: HOWTO: Enumerate IIS website configuration (VBScript using ADSI)


Child view constraints to parent view iOS

Question: I added 4 constrains to a child view of my main view of my initial view controller. Top space and leading space with 0 as the constant and equal width and height with the parent view. No matter what I do the child view won't be at coordinates 0,0 , it always is at coordinates 16,20, even if the constants are 0.
Comment: Did you add these constraints in the storyboard? You are probably making the constraints to the view's margins instead of its edges (there's a checkbox in the pin popup that's selected by default, that you should deselect).
Comment: Yes, I added them in storyboard. What checkbox? I can't find it.
Answer: Delete your top and leading constraints. Then, create them again. Only this time, when you're creating them, uncheck "constrain to margins" checkbox.
This is the checkbox I'm talking about:


How can I correct my juggling?

Question: While practicing juggling I discovered two things:

I am currently horrible at juggling
The ball seems to have a backspin when I hit it

The two seem related.
Let me explain:
When juggling, the ball seems to hit a place on my foot right below my laces. I try to keep my foot firm and myself in a stationary position -- yet the ball spins off of it and back towards me - usually bouncing off my shins. Maybe my foot or toes are curling upwards?
What is the root of the problem here and what would be the most effective way to combat it?

I have looked at this question, and it was helpful, but I do not think mine is a duplicate, as that question asks what the best way to do this skill is, while I am asking about addressing a particular problem I have encountered.
Comment: Some backspin is normal and you can counter this by getting used to it. If it spins too much you hit the ball at the wrong place. (Probably because you have the ball too far away from your body, which gives you a bad angle).
Answer: I have talked to some friends and showed them my juggling, and most of them think that I am juggling on or right above my toes.
If I am indeed juggling with my toes, I could understand the backspin because it would hit the tip of my foot and curl back toward or away from me. This is not controlled at all and doesn't get me very many juggles.
They suggested practicing juggling the ball off the proper area of my foot by resorting to the simple method of dropping the ball, juggling one or two times, and then catching it - this time with the proper area of the foot (right below the laces) to retrain myself before trying to regularly juggle.
Hopefully this works.

How can I correct my juggling?


Detecting the user's spinning motion

Question: I have been experimenting with the Core Motion framework to detect a user spinning around, say on a merry-go-round, holding an iphone in his hand.
There are ways to detect the device motion around its own axes, but what is a good way to detect the iPhone spinning in circles?
Thanks
Comment: not my business, my concern is to tackle this programming problem
Comment: does this happen to users alot: spinning around quickly in short circles?
Comment: You need to use the gyro for this.
Comment: Why would you want that out of curiosity?
Comment: shyam: I've never been a fan of the "just following orders" approach...
Answer: You can use the gyroscope. Take a look here: Gyroscope example
You have to remind that it is only availble on iPhone4 and iPhone4S.
Answer: There is one degenerate case where you can run into trouble, only magnetometer (compass) can help in that particular case.
If you put the device (a) on the desk in stationary position then (b) on a perfectly horizontal turntable rotating slowly you will get the same qualitative sensor readings. Both the gyro and the accelerometer readings are constant in the two cases, although the readings quantitatively differ. The sad part is: gyro bias error can render case (a) to look like (b) and vice-versa. In this particular case you need a compass to cancel the gyro drift. Case (a) is typical for a phone.
Apart from this degenerate case, gyroscopes and accelerometers with sensor fusion are sufficient to track arbitrary rotations of the device.

Detecting the user's spinning motion


Generate slideshow of images present in a folder

Question: I want a module which gives user just a screen to upload images to a folder and it will generate a slideshow of the images and place it on a certain block in my website. Is there any module to do this or any custom code to do this?
Answer: You could try something along the lines of the following:
function mymodule_get_folder_images() {
$directory = "path/to/your/images";
//Check this...my regex is crap
$mask = "(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)";
$options = array(
'recursive' => TRUE
);

//This should return an array of images
$images = file_scan_directory($directory, $mask, $options);

//Loop through the array once to get an array of paths.
foreach ($images as $k => $v) {
$imagearray[] = $v->uri;
}

//This should probably be passed to a theme function to be more Drupally.

$output = '
';

foreach ($imagearray as $k => $imagepath) {
if ($k == '0') {
$output .= '';
}
else {
$output .= '';
}

$output .= '
';

return $output;
}

This will give you an unordered list of images that you can use to create your slideshow.  Then just hook the jQuery Cycle plugin (or any other slideshow plugin) into your site and you're off.  I can't really help with the slideshow integration as it's going to be pretty custom for your needs, but it becomes much easier when you already have the image urls formatted nicely.  Obviously, if you need a list instead then you just re-format the last foreach loop.
Comment: The [IMCE](http://drupal.org/project/imce) module is a good option for image uploading as well.
Comment: Doh..this doesn't include the page to upload files...you might be able to use the [Media](http://www.drupal.org/project/media) module for that, and then just hook the above code into that directory.


Lie derivative of differential form

Question: Let $M$ be an $S^1$-manifold and let $\omega$ be a $k$ form on $M$. Let $X\in\mathfrak{X}(M)$ a vector field on $M$. Now my question is,
If $\mathcal{L}_X(\omega)=0$, then $(\Phi_X^t)^*\omega=\omega.$
By definition
$$
\frac{d}{dt}\bigg|_{t=0}(\Phi_X^t)^*\omega =0
$$
Now, I want to say something like, $\frac{d}{dt}(\Phi_X^t)^*\omega=0$ for all $t$, so $(\Phi_X^t)^*\omega=(\Phi_X^0)^*=\omega$. How can I do this?
Answer: Use the fact that $\Phi_X^{s+t} = \Phi_X^s\circ\Phi_X^t$ to deduce that
$$
\frac{d}{dt}\bigg\rvert_{t=t_0} (\Phi_X^t)^*\omega
= (\Phi_X^{t_0})^* \frac{d}{dt}\bigg\rvert_{t=0} (\Phi_X^t)^*\omega = 0.
$$

Lie derivative of differential form


Drupal Error : The website encountered an unexpected error. Please try again later

Question: I made a site locally and when I uploaded it to the hosting server, it worked fine except when I went to edit some content type. It showed this error:
The website encountered an unexpected error. Please try again later.

It was showing nothing except the above error. To get more error output, I added a few lines to my index.php file (these lines were added right after the first line):
error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE);

The error output was now showing this error:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in
  /home/a2682242/public_html/includes/database/database.inc:2171 Stack
  trace: #0
  /home/a2682242/public_html/includes/database/database.inc(2171):
  PDOStatement->execute(Array) #1
  /home/a2682242/public_html/includes/database/database.inc(683):
  DatabaseStatementBase->execute(Array, Array) #2
  /home/a2682242/public_html/includes/database/database.inc(2350):
  DatabaseConnection->query('SELECT expire, ...', Array, Array) #3
  /home/a2682242/public_html/includes/lock.inc(167): db_query('SELECT
  expire, ...', Array) #4
  /home/a2682242/public_html/includes/lock.inc(146):
  lock_may_be_available('theme_registry:...') #5
  /home/a2682242/public_html/includes/theme.inc(449):
  lock_acquire('theme_registry:...') #6
  /home/a2682242/public_html/includes/bootstrap.inc(446):
  ThemeRegistry->set(Array) #7 [internal function]:
  DrupalCacheArray->__destruct() #8 {main} thrown in
  /home/a2682242/public_html/includes/database/database.inc on line 2171

The site was working fine locally. I am not having much clue as to where the problem is. Is it some problem with the mysql server setting of my hosting provider? Or something else?
Answer: Please try increasing your max_allowed_packet setting in MySQL.
Open my.cnf file & update max_allowed_packet = 16M or more
Comment: Yeah. This is also what I think is causing the error. The problem is that I am on a shared hosting. When I ask them to increase their limit, they say that other clients are not facing the problem and it's probably some problem with your Drupal. So, are you absolutely sure that the above problem can be fixed by changing the mysql setting? I would change the hosting in that case.
Comment: ya I'm 100% sure.
Comment: My hosting server had max_allowed_packet set to 1M. Whereas my local server had it set to 16M. After I set my local server to 1M, I could replicate the problem locally. So, the problem was indeed due to max_allowed_packet. Thanks Samzha for your quick and confident response.
Comment: you welcome @shivams
Comment: 1M is tiny. Even 16M can be insufficient for larger sites. For more info see some of the answers at http://drupal.stackexchange.com/q/31890/10729


How to undo serialize list on Django

Question: I serialized a list of Django models like this:
serialize_list = serializers.serialize("json", my_list)

and now I want to deserialize it and get back a list of Django models.
Instead, when I do
deserialize_list = serializers.deserialize("json", serialize_list )
I get a list of DeserializedObject models and not the original list.
My question is: how can I get the original list back?
Answer: Each element of the deserialized list has an object attribute, which contains the model instance.
original = [item.object for item in deserialize_list]

Comment: Thank you! exactly what I needed

How to undo serialize list on Django


Google Maps Spiderfy open by default

Question: Looking to utlize the spiderfy which George MacKerron has developed. However I have one other requirement which is to load the map with all markers "spiderd" out by default. I can mimic this by using javascript to click on the markers, but there has to be another way by using the spiderfy code. Has anyone accomplished this?
https://github.com/jawj/OverlappingMarkerSpiderfier#overlapping-marker-spiderfier-for-google-maps-api-v3
var map = new google.maps.Map(document.getElementById("map-canvas"), options);
var iw = new google.maps.InfoWindow();
var oms = new OverlappingMarkerSpiderfier(map, {keepSpiderfied: true});

http://jsfiddle.net/vFAy6/5/
Answer: I came up with a solution that worked for me. After I've added all markers, I set a timeout to call a functiont to open each cluster and in the OMS js.

keepSpiderfied keeps all spideried markers open. It wasn't working for me so I altered the OMS js. If it works for you, you don't need to change this.

Find this:
(!e||!this.keepSpiderfied)&&this.unspiderfy();

Replace with this:
(!e||!this.keepSpiderfied);

function to call to open each cluster group:
function openAllClusters() {
    var markers = oms.markersNearAnyOtherMarker();

    $.each(markers, function (i, marker) {
        google.maps.event.trigger(markers[i], 'click');
    });
}

I set a timeout after I added my last marker (because it didn't work just calling the function immediately after):
setTimeout(openAllClusters, 2000);
Comment: **Note** that this might trigger infoWindow popup (since the marker click invocation)
Comment: Hello Shevy, would you happen to have a working example of this? I attempted to get it working with the following: http://paste.debian.net/170473/ but markers are not expanding upon page load. I replaced  (!e||!this.keepSpiderfied)&&this.unspiderfy(); with (!e||!this.keepSpiderfied); in the OMS js, and then added the function in step 2 to my html page. The setTimeout was placed at the end of my script.
Comment: Hi, is this supposed to keep the markers spiderfied even though the map is clicked? If not, do you know how I can do this?
Answer: From the documentation:

keepSpiderfied (default: false)
By default, the OverlappingMarkerSpiderfier works like Google Earth, in that when you click > a spiderfied marker, the markers unspiderfy before any other action takes place.
Since this can make it tricky for the user to work through a set of markers one by one, you > can override this behaviour by setting the keepSpiderfied option to true.
Comment: Do you have example code or a jsfiddle that demonstrates the problem?
Comment: yeah I had tried that. But that constructor option doesnt seem to work.
Comment: For some reason my set up never works inside of jsfiddle... http://jsfiddle.net/vFAy6/5/
Answer: According to the developer of this google map extension this will not work.
https://github.com/jawj/OverlappingMarkerSpiderfier/issues/2

Google Maps Spiderfy open by default


Entityfrom spam protection module without captcha

Question: Is there a module which I can use with entity forms without needing captcha field?
Answer: You may be looking for Hidden CAPTCHA.
Even though you need the CAPTCHA module for this, Hidden CAPTCHA module will not display any captcha field and you don't absolutely need to have a human enter a text, number, etc.
Answer: For spam protection on Entityforms, you can use Honeypot and Honeypot Entityform to add an invisible "honeypot" field to your Entityform Types.
It's a simple and unobtrusive alternative to the CAPTCHA module and effortless to configure.
Answer: You can also use the Mollom module, which has native integration with Entityforms and offers spam protection among many other features.


Find the maximum of $\frac{abc}{(4a+1)(9a+b)(4b+c)(9c+1)}$,where$a,b,c>0$

Question: $a,b,c>0$, find the maximum of :
$$\frac{abc}{(4a+1)(9a+b)(4b+c)(9c+1)}$$

I try to find the minimum of $\frac{(4a+1)(9a+b)(4b+c)(9c+1)}{abc}=\frac{4a+1}{\sqrt{a}}\cdot\frac{9a+b}{\sqrt{ab}}\cdot\frac{4b+c}{\sqrt{bc}}\cdot\frac{9c+1}{\sqrt{c}}
=\left(4\sqrt{a}+\frac{1}{\sqrt{a}}\right)\left(9\sqrt{\frac{a}{b}}+\sqrt{\frac{b}{a}}\right)\left(4\sqrt{\frac{b}{c}}+\sqrt{\frac{c}{b}}\right)\left(9\sqrt{c}+\frac{1}{\sqrt{c}}\right) \geq 4 \times 6\times 4\times 6$
when I try to use AM-GM inequality, I find I can't take equality in the above $4$ parentheses.so I only find a upper bound of the expression.: $\frac{abc}{(4a+1)(9a+b)(4b+c)(9c+1)} < \frac{1}{576}$
Comment: Here is an equivalent question https://math.stackexchange.com/q/3529987, all solutions presented there can be applied to your problem as well.
Comment: @Ginko: Investigating the logarithmic derivative of your expression seems to be a way out.
Answer: Hint
Try instead to minimize
$$\Phi=\frac{(4a+1)(9a+b)(4b+c)(9c+1)}{abc}$$ Compute the partial derivatives
All of them being equal to $0$, the solution is immediate.
Answer: Let $Q = \dfrac{abc}{(4a+1)(9a+b)(4b+c)(9c+1)}= \dfrac{abc}{(b+9a)(4a+1)(4b+c)(9c+1)}$. Apply Cauchy-Schwarz inequality twice: $Q \le \dfrac{abc}{(2\sqrt{a}\cdot \sqrt{b}+1\cdot 3\sqrt{a})^2\cdot(2\sqrt{b}\cdot 3\sqrt{c}+\sqrt{c}\cdot 1)^2} = \left(\dfrac{\sqrt{b}}{(2\sqrt{b}+3)(6\sqrt{b}+1)}\right)^2= \left(\dfrac{t}{(2t+3)(6t+1)}\right)^2$, with $t = \sqrt{b}$. And apply AM-GM inequality:$\left(\dfrac{t}{(2t+3)(6t+1)}\right)^2= \left(\dfrac{t}{12t^2+20t+3}\right)^2= \dfrac{1}{\left(12t+\dfrac{3}{t}+20\right)^2}\le \dfrac{1}{\left(20+2\sqrt{12t\cdot \dfrac{3}{t}}\right)^2}=\dfrac{1}{32^2}=\dfrac{1}{1024}$. Thus $Q_{\text{max}} = \dfrac{1}{1024}$. This maximum value occurs when: $12t = \dfrac{3}{t}\implies t = \dfrac{1}{2}\implies \sqrt{b} = \dfrac{1}{2}\implies b = \dfrac{1}{4}$. Also: $\dfrac{2\sqrt{b}}{3\sqrt{c}}=\dfrac{\sqrt{c}}{1}\implies 3c=2\sqrt{b}=2\cdot\dfrac{1}{2} = 1\implies c = \dfrac{1}{3}.$, and $\dfrac{2\sqrt{a}}{\sqrt{b}}=\dfrac{1}{3\sqrt{a}}\implies 6a=\sqrt{b}=\dfrac{1}{2}\implies a = \dfrac{1}{12}.$ In summary, the maximum of $\dfrac{1}{1024}$ achieved when $(a,b,c) = \left(\dfrac{1}{12}, \dfrac{1}{4}, \dfrac{1}{3}\right)$.
Comment: Nice, +1.  After your first CS, you could immediately do another one for quicker results - ie using $(2\sqrt{b}+3)(1+6\sqrt{b}) \geqslant  (\sqrt2\cdot\sqrt[4]{b}+3\sqrt2\cdot \sqrt[4]{b})^2= 32\sqrt{b}$
Comment: Oh, yeah. I missed that one. But right after the first use the of CS inequality, I felt I was in the right direction and the solution is near by.


Apiary limiting a response return

Question: So I'm using Apiary to hold and array of data, and then call the data to display on HTML but I only want Apiary to send a limited amount of data to HTML, not the full array. Still trying to get my head around Apiary syntax, so just wondering if I'm heading in the right direction (or would I be doing this via the frontend?), because what I'm using doesn't work and the documentation isn't clear to me :
<code>##news updates [/articles{?limit}]
###Get all news [GET]

+ Parameters

+ limit (number, optional)
    + Default: '3'

+ Request

  + Header

        Authorization: Basic dXNlcjpwYXNzd29yZA==
        x-api-verson: 1.0

+ Response 200 (application/json)

        {
                "articles": [
                    {
                        *array item one*
                    },
                    {
                        *array item two*
                    },
                    {
                        *array item three*
                    },
                    {
                        *array item four*
                    },
                  ]
         }
</code>
Answer: You can set up multiple examples, per here:
https://github.com/apiaryio/api-blueprint/blob/master/API%20Blueprint%20Specification.md#example-multiple-transaction-examples
And then you can access different examples using the Prefer header in a mock request per "Invoking non-default responses" section here:
http://support.apiary.io/knowledgebase/articles/117119-handling-multiple-actions-on-a-single-resource
Comment: Apiary has no concept of the array inside the response. *You* have to prepare the filtered arrays yourself as different responses.
Comment: thanks, I had a read of those documentations but they aren't specifically clear as how to sent limited data from the array to the HTML

Apiary limiting a response return


Find the value of the limit $b_n = n - \sqrt{n^2 + 2n}$ if $(1/n)\rightarrow 0$.

Question: Consider the sequence given by $b_n = n - \sqrt{n^2 + 2n}$. Taking $(1/n)\rightarrow 0$ as given, and using both the Algebraic Limit Theorem, and the fact that if $(x_n)\rightarrow x$ then $(\sqrt{x_n})\rightarrow \sqrt{x}$, show $\lim b_n$ exists and find the value of the limit.
Well, because $(1/n) \rightarrow 0$, the sequence $(n)\rightarrow \infty$. Consider $n=\sqrt{n^2}>\sqrt{n^2 - 2n}$ which implies $n>n-\sqrt{n^2 - 2n}>0 $. So if $(n)\rightarrow \infty$ then so does $(n-\sqrt{n^2 - 2n})\rightarrow \infty$ $\blacksquare$
But after writing I wonder if it is okay for me to assume that $n\in \mathbb{N}$. If $n\notin \mathbb{N}$ then my first statement of $(n)\rightarrow \infty$ is wrong because $n$ could also diverge to $-\infty$.
Answer: Hint: Multiply numerator and denominator by $$n+\sqrt{n^2+2n}$$
Answer: Set $x=\dfrac 1n\;(x>0)$. You want the limit, as $x\to 0$, of
$$\frac1x-\sqrt{\frac 1{x^2}+\frac 2x}=\frac{1-\sqrt{1+2x}}{x}=-\frac{\sqrt{1+2x}-\sqrt 1}{x} $$
This is the opposite of the rate of variation, from $0$, of the function $\sqrt{1+2x}$. Can you end the computation?
Answer: Observe that $n - (n^2 + 2n)^{\frac{1}{2}}=n - n\left( 1 + \frac{2}{n} \right)^{\frac{1}{2}}$.
By the binomial theorem, it follows that
$$
\left( 1 + \frac{2}{n} \right)^{\frac{1}{2}}=1+\frac{1}{n}-\frac{1}{2n^2}+o(n^{-2})
$$
So
$$
n - n\left( 1 + \frac{2}{n} \right)^{\frac{1}{2}}=n - \left(n + 1 - \frac{1}{2n} + o(n^{-1}) \right)=-1+\frac{1}{2n}+o(n^{-1})
$$
Therefore, $\lim n - (n^2 + 2n)^{\frac{1}{2}} = -1$.


pulltorefresh android 4.1 and higher

Question: I'm using the pullToRefresh library:
<code>https://github.com/johannilsson/android-pulltorefresh/pull/40
</code>
But the list cant be moved if the android version is bigger than 4.0
LogCat shows emulator warnings, but they are not related.
How can I solve the problem moving the list?
Answer: You are correct. The problem is related to the emulator and it should not cause any errors with functionality of your application. It happens often only on 4.2 emulator or a device.
Unexpected value from nativeGetEnabledTags: 0

pulltorefresh android 4.1 and higher


How to use sed to replace only the first occurrence in a file?

Question: I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash script with sed to re-write the file.
How do I get sed to replace just the first occurrence of a string in a file rather than replacing every occurrence?
If I use
sed s/#include/#include "newfile.h"\n#include/

it replaces all #includes.
Alternative suggestions to achieve the same thing are also welcome.
Answer: A sed script that will only replace the first occurrence of "Apple" by "Banana"
Example
     Input:      Output:

     Apple       Banana
     Apple       Apple
     Orange      Orange
     Apple       Apple

This is the simple script: Editor's note: works with GNU sed only.
sed '0,/Apple/{s/Apple/Banana/}' input_filename

The first two parameters 0 and /Apple/ are the range specifier.  The s/Apple/Banana/ is what is executed within that range. So in this case "within the range of the beginning (0) up to the first instance of Apple, replace Apple with Banana.  Only the first Apple will be replaced.
Background: In traditional sed the range specifier is also "begin here" and "end here" (inclusive).  However the lowest "begin" is the first line (line 1), and if the "end here" is a regex, then it is only attempted to match against on the next line after "begin", so the earliest possible end is line 2.  So since range is inclusive, smallest possible range is "2 lines" and smallest starting range is both lines 1 and 2 (i.e. if there's an occurrence on line 1, occurrences on line 2 will also be changed, not desired in this case). GNU sed adds its own extension of allowing specifying start as the "pseudo" line 0 so that the end of the range can be line 1, allowing it a range of "only the first line" if the regex  matches the first line.
Or a simplified version (an empty RE like // means to re-use the one specified before it, so this is equivalent):
sed '0,/Apple/{s//Banana/}' input_filename

And the curly braces are optional for the s command, so this is also equivalent:
sed '0,/Apple/s//Banana/' input_filename

All of these work on GNU sed only.
You can also install GNU sed on OS X using homebrew brew install gnu-sed.
Comment: translated into human language: start at line 0, continue until you match 'Apple', execute the substitution in curly brackets. cfr: http://www.grymoire.com/Unix/Sed.html#uh-29
Comment: On OS X, I get `sed: 1: "…": bad flag in substitute command: '}'`
Comment: Works without the brackets too: `sed '0,/foo/s/foo/bar/'`
Comment: I get `sed: -e expression #1, char 3: unexpected `,'` with this
Comment: @ELLIOTTCABLE on OS X, use `sed -e '1s/Apple/Banana/;t' -e '1,/Apple/s//Banana/'`. From @MikhailVS's answer (currently) way down below.
Comment: @Jonathan Can you rephrase your answer in the universally-accepted Apple-Banana parlance? I think I'm getting the same problem because my "banana" happens to include a bash variable:
`sed -i -E "0,|(Apple).*|{s|(Apple:).*|Banana: "$BananaVariable"/data.txt|}" filename`
Comment: Shout out for the people whom actually provide quick, clean and simple examples.
Comment: Solved by using ```sed -i '|DATADIR.*=.*|{s/DATADIR.*=.*|DATADIR=/var/lib/`hostname`|1}``` Note 1 at end after last delimiter
Comment: Shout out for the people whom actually provide quick, clean and simple examples.
Comment: This doesn't seem to work if the address is not the same as the pattern you want to replace. For example, `sed '0,/White/ s/cat/dog/' filename` replaces all instances of "cat" with "dog" up to and including the first line with "White cat". You would need to do something more like `sed '0,/White/ s/White cat/White dog/' filename`
Comment: You don't have to repeat Apple: `sed '0,/Apple/s//Banana/'`. Not repeating is essential for complex patterns, e.g., I used this to work to update the first version property: `sed -i -r -e '0,/^(\s*<property +name="version" +value=")[^"]+/s//\11.0.0/' build.xml`
Comment: In OSX you can also use `gsed`, which implements the GNU `sed`.
Comment: Is it possible to *delete* (rather than substitute) only the first matching line?  If I try `sed '0,/Orange/d' input_filename` I seem to lose all lines upto and including the (first?) matching line.
Answer:  # sed script to change "foo" to "bar" only on the first occurrence
 1{x;s/^/first/;x;}
 1,/foo/{x;/first/s///;x;s/foo/bar/;}
 #---end of script---

or, if you prefer: Editor's note: works with GNU sed only.
sed '0,/foo/s//bar/' file

Source
Comment: I think I prefer the 'or if you prefer' solution.  It would also be good to explain the answers - and to make the answer address the question directly, and then generalize, rather than generalize only.  But good answer.
Comment: Could somebody please explain the 'or if you prefeer' solution? I don't know where to put the "from" pattern.
Comment: FYI for Mac users, you have to replace the 0 with a 1, so: sed '1,/RE/s//to_that/' file
Comment: @Jean-LucNacifCoelho: using `s//` - i.e., an _empty_ regex - means that the most recently applied regex is implicitly reused; in this case, `RE`.  This convenient shortcut means you don't have to duplicate the range-ending regex in your `s` call.
Comment: Full example: `echo "abc\nabc" | sed '0,/^abc/s//ab/'`
Comment: @mhost No, it will than replace if pattern is found in line #1 and not if pattern is at other line,  but still is the first found pattern.  PS it should be mention that this `0,` only works with `gnu sed`
Comment: Why can't I change the default separator? `/`. when I try to use `:` instead of `/`, I got an error. And what is that `0` at first?
Comment: @AryehLeibTaurog It won't work either, file will be truncated after match. The whole idea of using "q" was flawed, sorry about that.
Comment: Anybody get that first example to actually work?  For me it doesn't work with GNU sed or BSD sed...
Comment: It would make sense to quit after the (first and only) substitution is done :  `sed '0,/RE/{s//to_that/;q;}' file`
Comment: @Nico57 no, that would quit on line 0, but this would work: `/RE/{s//to_that/;q}`
Comment: @Nico57 ah, yes.  I had a slightly different use case in mind.
Comment: How to escape bracket?
Answer: An overview of the many helpful existing answers, complemented with explanations:
The examples here use a simplified use case: replace the word 'foo' with 'bar' in the first matching line only.
Due to use of ANSI C-quoted strings ($'...') to provide the sample input lines, bash, ksh, or zsh is assumed as the shell.

GNU sed only:
Ben Hoffstein's anwswer shows us that GNU  provides an extension to the POSIX specification for sed that allows the following 2-address form: 0,/re/ (re represents an arbitrary regular expression here).
0,/re/ allows the regex to match on the very first line also. In other words: such an address will create a range from the 1st line up to and including the line that matches re - whether re occurs on the 1st line or on any subsequent line.

Contrast this with the POSIX-compliant form 1,/re/, which creates a range that matches from the 1st line up to and including the line that matches re on subsequent lines; in other words: this will not detect the first occurrence of an re match if it happens to occur on the 1st line and also prevents the use of shorthand // for reuse of the most recently used regex (see next point).1

If you combine a 0,/re/ address with an s/.../.../ (substitution) call that uses the same regular expression, your command will effectively only perform the substitution on the first line that matches re.
sed provides a convenient shortcut for reusing the most recently applied regular expression: an empty delimiter pair, //.
$ sed '0,/foo/ s//bar/' <<<$'1st foo\nUnrelated\n2nd foo\n3rd foo'
1st bar         # only 1st match of 'foo' replaced
Unrelated
2nd foo
3rd foo

A POSIX-features-only sed such as BSD (macOS) sed (will also work with GNU sed):
Since 0,/re/ cannot be used and the form 1,/re/ will not detect re if it happens to occur on the very first line (see above), special handling for the 1st line is required.
MikhailVS's answer mentions the technique, put into a concrete example here:
$ sed -e '1 s/foo/bar/; t' -e '1,// s//bar/' <<<$'1st foo\nUnrelated\n2nd foo\n3rd foo'
1st bar         # only 1st match of 'foo' replaced
Unrelated
2nd foo
3rd foo

Note:

The empty regex // shortcut is employed twice here: once for the endpoint of the range, and once in the s call; in both cases, regex foo is implicitly reused, allowing us not to have to duplicate it, which makes both for shorter and more maintainable code.

POSIX sed needs actual newlines after certain functions, such as after the name of a label or even its omission, as is the case with t here; strategically splitting the script into multiple -e options is an alternative to using an actual newlines: end each -e script chunk where a newline would normally need to go.

1 s/foo/bar/ replaces foo on the 1st line only, if found there.
If so, t branches to the end of the script (skips remaining commands on the line). (The t function branches to a label only if the most recent s call performed an actual substitution; in the absence of a label, as is the case here, the end of the script is branched to).
When that happens, range address 1,//, which normally finds the first occurrence starting from line 2, will not match, and the range will not be processed, because the address is evaluated when the current line is already 2.
Conversely, if there's no match on the 1st line, 1,// will be entered, and will find the true first match.
The net effect is the same as with GNU sed's 0,/re/: only the first occurrence is replaced, whether it occurs on the 1st line or any other.

NON-range approaches
potong's answer demonstrates loop techniques that bypass the need for a range; since he uses GNU sed syntax, here are the POSIX-compliant equivalents:
Loop technique 1: On first match, perform the substitution, then enter a loop that simply prints the remaining lines as-is:
$ sed -e '/foo/ {s//bar/; ' -e ':a' -e '$!{n;ba' -e '};}' <<<$'1st foo\nUnrelated\n2nd foo\n3rd foo'
1st bar
Unrelated
2nd foo
3rd foo

Loop technique 2, for smallish files only: read the entire input into memory, then perform a single substitution on it.
$ sed -e ':a' -e '$!{N;ba' -e '}; s/foo/bar/' <<<$'1st foo\nUnrelated\n2nd foo\n3rd foo'
1st bar
Unrelated
2nd foo
3rd foo

1 1.61803 provides examples of what happens with 1,/re/, with and without a subsequent s//:

sed '1,/foo/ s/foo/bar/' <<<$'1foo\n2foo' yields $'1bar\n2bar'; i.e., both lines were updated, because line number 1 matches the 1st line, and regex /foo/ - the end of the range - is then only looked for starting on the next line. Therefore, both lines are selected in this case, and the s/foo/bar/ substitution is performed on both of them.
sed '1,/foo/ s//bar/' <<<$'1foo\n2foo\n3foo' fails: with sed: first RE may not be empty (BSD/macOS) and sed: -e expression #1, char 0: no previous regular expression (GNU), because, at the time the 1st line is being processed (due to line number 1 starting the range), no regex has been applied yet, so // doesn't refer to anything.
With the exception of GNU sed's special 0,/re/ syntax, any range that starts with a line number effectively precludes use of //.
Comment: For the POSIX solution, what if the first occurrence is not on the first line? e.g. `some lines\n1st foo\nsome text or 2nd foo\nmore foo`
Comment: @jimmymcheung, seems to me it works just fine; e.g.: `sed -e '1 s/foo/bar/; t' -e '1,// s//bar/' <<<$'Unrelated 1\n1st foo\nUnrelated 2\n2nd foo\n3rd foo'`
Answer: sed '0,/pattern/s/pattern/replacement/' filename

this worked for me.
example
sed '0,/<Menu>/s/<Menu>/<Menu><Menu>Sub menu<\/Menu>/' try.txt > abc.txt

Editor's note: both work with GNU sed only.
Comment: @Landys this still replaces instances in the other lines too; not just the first instance
Comment: @sarat Yes, you're right. `sed '1,/pattern/s/pattern/replacement/' filename` only works if "the pattern will not occur on the first line" on Mac. I'll delete my previous comment since it's not accurate. The detail can be found here (http://www.linuxtopia.org/online_books/linux_tool_guides/the_sed_faq/sedfaq4_004.html). Andy's answer only works for GNU sed, but not the one on Mac.
Comment: The simplest answer! Congrats.
Answer: You could use awk to do something similar..
awk '/#include/ && !done { print "#include \"newfile.h\""; done=1;}; 1;' file.c

Explanation:
/#include/ && !done

Runs the action statement between {} when the line matches "#include" and we haven't already processed it.
{print "#include \"newfile.h\""; done=1;}

This prints #include "newfile.h", we need to escape the quotes. Then we set the done variable to 1, so we don't add more includes.
1;

This means "print out the line" - an empty action defaults to print $0, which prints out the whole line. A one liner and easier to understand than sed IMO :-)
Comment: This answer is more portable than the sed solutions, which rely on gnu sed etc.. (e.g. sed in OS-X sucks!)
Comment: This is truly more understandable, but for me it adds a line instead of replacing it; command used:        `awk '/version/ && !done {print "  \"version\": \"'${NEWVERSION}'\""; done=1;}; 1;' package.json`
Comment: Answer is quite readable. Here's my version that replaces string instead of adding a new line. `awk '/#include/ && !done { gsub(/#include/, "include \"newfile.h\""); done=1}; 1' file.c`
Comment: same here, most understandable command, but it adds a line above the found string instead of replacing it
Answer: Quite a comprehensive collection of answers on linuxtopia sed FAQ. It also highlights that some answers people provided won't work with non-GNU version of sed, eg
sed '0,/RE/s//to_that/' file

in  non-GNU version will have to be
sed -e '1s/RE/to_that/;t' -e '1,/RE/s//to_that/'

However, this version won't work with gnu sed.
Here's a version that works with both:
-e '/RE/{s//to_that/;:a' -e '$!N;$!ba' -e '}'

ex:
sed -e '/Apple/{s//Banana/;:a' -e '$!N;$!ba' -e '}' filename

Comment: Indeed, tested working on Ubuntu Linux v16 and FreeBSD v10.2 . Thanks you.
Comment: FYI: POSIX (non-GNU) sed officially has a default buffer of 8K. So the second option, of reading all the lines into the buffer, then changing the first instance in the buffer, may blow up if the file is over 8K
Answer: With GNU sed's -z option you could process the whole file as if it was only one line. That way a s/…/…/ would only replace the first match in the whole file. Remember: s/…/…/ only replaces the first match in each line, but with the -z option sed treats the whole file as a single line.
sed -z 's/#include/#include "newfile.h"\n#include'

In the general case you have to rewrite your sed expression since the pattern space now holds the whole file instead of just one line. Some examples:

s/text.*// can be rewritten as s/text[^\n]*//. [^\n] matches everything except the newline character. [^\n]* will match all symbols after text until a newline is reached.
s/^text// can be rewritten as s/(^|\n)text//.
s/text$// can be rewritten as s/text(\n|$)//.
Answer: #!/bin/sed -f
1,/^#include/ {
    /^#include/i\
#include "newfile.h"
}

How this script works: For lines between 1 and the first #include (after line 1), if the line starts with #include, then prepend the specified line.
However, if the first #include is in line 1, then both line 1 and the next subsequent #include will have the line prepended. If you are using GNU sed, it has an extension where 0,/^#include/ (instead of 1,) will do the right thing.
Answer: Just add the number of occurrence at the end:
sed s/#include/#include "newfile.h"\n#include/1

Comment: Hmmm...time passes.  POSIX 2008/2013 for [`sed`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html) specifies the substitute command with: _`[2addr]s/BRE/replacement/flags`_ and notes that "The value of flags shall be zero or more of:

_n_
    Substitute for the nth occurrence only of the BRE found within the pattern space."  Thus, at least in POSIX 2008, the trailing `1` is not a GNU `sed` extension.  Indeed, even in the [SUS/POSIX 1997](http://pubs.opengroup.org/onlinepubs/7990989775/) standard, this was supported, so I was badly out of line back in 2008.
Comment: Unfortunately, this does not work. It replaces the just first occurrence on each line of the file and not the first occurrence in the file.
Comment: Additionally, it is a GNU sed extension, not a standard sed feature.
Answer: A possible solution:
    /#include/!{p;d;}
    i\
    #include "newfile.h"
    :a
    n
    ba

Explanation:

read lines until we find the #include, print these lines then start new cycle
insert the new include line
enter a loop that just reads lines (by default sed will also print these lines), we won't get back to the first part of the script from here
Comment: `sed: file me4.sed line 4: ":" lacks a label`
Comment: apparently something changed in recent sed versions and empty labels are no longer allowed. updated the answer
Answer: I know this is an old post but I had a solution that I used to use:
grep -E -m 1 -n 'old' file | sed 's/:.*$//' - | sed 's/$/s\/old\/new\//' - | sed -f - file

Basically use grep to print the first occurrence and stop there. Additionally print line number ie 5:line. Pipe that into sed and remove the : and anything after so you are just left with a line number. Pipe that into sed which adds s/.*/replace to the end number, which results in a 1 line script which is piped into the last sed to run as a script on the file.
so if regex = #include and replace = blah and the first occurrence grep finds is on line 5 then the data piped to the last sed would be 5s/.*/blah/.
Works even if first occurrence is on the first line.
Comment: I utterly hate multiline sed scripts or sed commands with anything but s and a linenumber so I'm on board with this approach. Here is what I used for my usecase (works with bash): filepath=/etc/hosts ; patt='^\\(127\.0\.0\.1.*\\)' ; repl='\1 newhostalias' ; sed $( IFS=: linearray=($(grep -E -m 1 -n "$patt" "$filepath")) && echo ${linearray[0]})s/"$patt"/"$repl"/ "$filepath"
Comment: It works.  Though only with sed's that are smart enough to accept `sed -f -` which some aren't, but you can work around it :)
Answer: i would do this with an awk script:
BEGIN {i=0}
(i==0) && /#include/ {print "#include \"newfile.h\""; i=1}
{print $0}
END {}

then run it with awk:
awk -f awkscript headerfile.h > headerfilenew.h

might be sloppy, I'm new to this.
Answer: As an alternative suggestion you may want to look at the ed command.
man 1 ed

teststr='
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
'

# for in-place file editing use "ed -s file" and replace ",p" with "w"
# cf. http://wiki.bash-hackers.org/howto/edit-ed
cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s <(echo "$teststr")
   H
   /# *include/i
   #include "newfile.h"
   .
   ,p
   q
EOF

Answer: I finally got this to work in a Bash script used to insert a unique timestamp in each item in an RSS feed:
        sed "1,/====RSSpermalink====/s/====RSSpermalink====/${nowms}/" \
            production-feed2.xml.tmp2 > production-feed2.xml.tmp.$counter

It changes the first occurrence only.
${nowms} is the time in milliseconds set by a Perl script, $counter is a counter used for loop control within the script, \ allows the command to be continued on the next line.
The file is read in and stdout is redirected to a work file.
The way I understand it, 1,/====RSSpermalink====/ tells sed when to stop by setting a range limitation, and then s/====RSSpermalink====/${nowms}/ is the familiar sed command to replace the first string with the second.
In my case I put the command in double quotation marks becauase I am using it in a Bash script with variables.
Answer: Using FreeBSD ed and avoid ed's "no match" error in case there is no include statement in a file to be processed:
teststr='
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
'

# using FreeBSD ed
# to avoid ed's "no match" error, see
# *emphasized text*http://codesnippets.joyent.com/posts/show/11917
cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s <(echo "$teststr")
   H
   ,g/# *include/u\
   u\
   i\
   #include "newfile.h"\
   .
   ,p
   q
EOF

Comment: This is remarkably similar to [timo](http://stackoverflow.com/a/5818901/15168)'s [answer](https://stackoverflow.com/a/5818901/15168) but was added over a year later.
Answer: This might work for you (GNU sed):
sed -si '/#include/{s//& "newfile.h\n&/;:a;$!{n;ba}}' file1 file2 file....

or if memory is not a problem:
sed -si ':a;$!{N;ba};s/#include/& "newfile.h\n&/' file1 file2 file...

Answer: If anyone came here to replace a character for the first occurrence in all lines (like myself), use this:
sed '/old/s/old/new/1' file

-bash-4.2$ cat file
123a456a789a
12a34a56
a12
-bash-4.2$ sed '/a/s/a/b/1' file
123b456a789a
12b34a56
b12

By changing 1 to 2 for example, you can replace all the second a's only instead.
Comment: You don't need to do all this, `'s/a/b/'` means `match a`, and `do just first match` `for every matching line`
Comment: I'm with Samveen. Also **this does not answer the question asked here**. I would advise to delete this answer.
Comment: The question was "first occurrence in a file" not "first occurrence in a line"
Answer: POSIXly (also valid in sed), Only one regex used, need memory only for one line (as usual):
sed '/\(#include\).*/!b;//{h;s//\1 "newfile.h"/;G};:1;n;b1'

Explained:
sed '
/\(#include\).*/!b          # Only one regex used. On lines not matching
                            # the text  `#include` **yet**,
                            # branch to end, cause the default print. Re-start.
//{                         # On first line matching previous regex.
    h                       # hold the line.
    s//\1 "newfile.h"/      # append ` "newfile.h"` to the `#include` matched.
    G                       # append a newline.
  }                         # end of replacement.
:1                          # Once **one** replacement got done (the first match)
n                           # Loop continually reading a line each time
b1                          # and printing it by default.
'                           # end of sed script.

Answer: The use case can perhaps be that your occurences are spread throughout your file, but you know your only concern is in the first 10, 20 or 100 lines.
Then simply adressing those lines fixes the issue - even if the wording of the OP regards first only.
sed '1,10s/#include/#include "newfile.h"\n#include/'

Answer: I needed a solution that would work both on GNU and BSD, and I also knew that the first line would never be the one I'd need to update:
sed -e "1,/pattern/s/pattern/replacement/"

Trying the // feature to not repeat the pattern did not work for me, hence needing to repeat it.
Answer: The following command removes the first occurrence of a string, within a file. It removes the empty line too. It is presented on an xml file, but it would work with any file.
Useful if you work with xml files and you want to remove a tag. In this example it removes the first occurrence of the "isTag" tag.
Command:
sed -e 0,/'<isTag>false<\/isTag>'/{s/'<isTag>false<\/isTag>'//}  -e 's/ *$//' -e  '/^$/d'  source.txt > output.txt

Source file (source.txt)
<xml>
    <testdata>
        <canUseUpdate>true</canUseUpdate>
        <isTag>false</isTag>
        <moduleLocations>
            <module>esa_jee6</module>
            <isTag>false</isTag>
        </moduleLocations>
        <node>
            <isTag>false</isTag>
        </node>
    </testdata>
</xml>

Result file (output.txt)
<xml>
    <testdata>
        <canUseUpdate>true</canUseUpdate>
        <moduleLocations>
            <module>esa_jee6</module>
            <isTag>false</isTag>
        </moduleLocations>
        <node>
            <isTag>false</isTag>
        </node>
    </testdata>
</xml>

ps: it didn't work for me on Solaris SunOS 5.10 (quite old), but it works on Linux 2.6, sed version 4.1.5
Comment: This looks remarkably like the same basic idea as a number of previous answers, with the same caveat that it only works with GNU `sed` (hence it didn't work with Solaris).  You should delete this, please — it really doesn't provide distinctive new information to a question that was already 4½ years old when you answered.  Granted, it does have a worked example, but that's of debatable value when the question has as many answers as this one does.
Answer: Nothing new but perhaps a little more concrete answer: sed -rn '0,/foo(bar).*/ s%%\1%p'
Example: xwininfo -name unity-launcher produces output like:
xwininfo: Window id: 0x2200003 "unity-launcher"

  Absolute upper-left X:  -2980
  Absolute upper-left Y:  -198
  Relative upper-left X:  0
  Relative upper-left Y:  0
  Width: 2880
  Height: 98
  Depth: 24
  Visual: 0x21
  Visual Class: TrueColor
  Border width: 0
  Class: InputOutput
  Colormap: 0x20 (installed)
  Bit Gravity State: ForgetGravity
  Window Gravity State: NorthWestGravity
  Backing Store State: NotUseful
  Save Under State: no
  Map State: IsViewable
  Override Redirect State: no
  Corners:  +-2980+-198  -2980+-198  -2980-1900  +-2980-1900
  -geometry 2880x98+-2980+-198

Extracting window ID with xwininfo -name unity-launcher|sed -rn '0,/^xwininfo: Window id: (0x[0-9a-fA-F]+).*/ s%%\1%p' produces:
0x2200003

Answer: A possible solution here might be to tell the compiler to include the header without it being mentioned in the source files. IN GCC there are these options:
   -include file
       Process file as if "#include "file"" appeared as the first line of
       the primary source file.  However, the first directory searched for
       file is the preprocessor's working directory instead of the
       directory containing the main source file.  If not found there, it
       is searched for in the remainder of the "#include "..."" search
       chain as normal.

       If multiple -include options are given, the files are included in
       the order they appear on the command line.

   -imacros file
       Exactly like -include, except that any output produced by scanning
       file is thrown away.  Macros it defines remain defined.  This
       allows you to acquire all the macros from a header without also
       processing its declarations.

       All files specified by -imacros are processed before all files
       specified by -include.

Microsoft's compiler has the /FI (forced include) option.
This feature can be handy for some common header, like platform configuration. The Linux kernel's Makefile uses -include for this.
Answer: I will make a suggestion that is not exactly what the original question asks for, but for those who also want to specifically replace perhaps the second occurrence of a match, or any other specifically enumerated regular expression match. Use a python script, and a for loop, call it from a bash script if needed. Here's what it looked like for me, where I was replacing specific lines containing the string --project:
def replace_models(file_path, pixel_model, obj_model):
    # find your file --project matches
    pattern = re.compile(r'--project.*')
    new_file = ""
    with open(file_path, 'r') as f:
        match = 1
        for line in f:
            # Remove line ending before we do replacement
            line = line.strip()
            # replace first --project line match with pixel
            if match == 1:
                result = re.sub(pattern, "--project='" + pixel_model + "'", line)
            # replace second --project line match with object
            elif match == 2:
                result = re.sub(pattern, "--project='" + obj_model + "'", line)
            else:
                result = line
            # Check that a substitution was actually made
            if result is not line:
                # Add a backslash to the replaced line
                result += " \\"
                print("\nReplaced ", line, " with ", result)
                # Increment number of matches found
                match += 1
            # Add the potentially modified line to our new file
            new_file = new_file + result + "\n"
        # close file / save output
        f.close()
    fout = open(file_path, "w")
    fout.write(new_file)
    fout.close()

Answer: sed -e 's/pattern/REPLACEMENT/1' <INPUTFILE


Type mismatch error when assigning a variable to an object of the same type

Question: I'm working on an Iterator for a linked list class. I am assigning nodes to variables within an inner class and am getting a "Type mismatch" error. Relevant code is below.
public class RegLinkList<T> implements Iterable<T>{
    private Node<T> head;
public RegLinkList() {
        head = null;
    }
 public class Node<T> {
   public Node<T> next = null;
   public T data = null;

   Node(T data){
        this.data = data;
    }
  }
    public class ListIterator<T> implements Iterator<T>{
    Node<T> current = head;
    Node<T> previous = head;

I get this:
    Type mismatch: cannot convert from
    RegLinkList<T>.Node<T> to RegLinkList<T>.Node<T>

Edit:
My current solution is an unchecked cast of
    public class ListIterator<T> implements Iterator<T>{
    Node<T> current = (Node<T>) head;
    Node<T> previous = (Node<T>) head;

Comment: Your `Node` is introducing a second type named `T`. Remove the generic from `Node` (`RegLinkList` is already generic).
Comment: Alternatively (and better in my opinion) change the `Node` class to be static. --- And don't nest `ListIterator` inside `Node`.
Comment: I mis-typed regarding the nesting. As for static, I don't know if that will solve the problem. I found a fix but it has an unchecked cast
Answer: The reason why you get this error is that the compiler does what you say and not what you mean. The T for ListIterator and the T of the RegLinkList are seen as two different types. It would become more clear if you used e.g. U instead of T.
A solution to your problem could be making the classes static and pass the head element to the constructor. That way you still declare different Ts but because you pass the original element (and therefor "telling" the compiler that the one T is the same as the other), it will be happy. The following code is happily compiled (I added missing method implementations with no functionalities):
import java.util.Iterator;

public class RegLinkList<T> implements Iterable<T> {
    private Node<T> head;

    public RegLinkList() {
        head = null;
    }

    public static class Node<T> {
        public Node<T> next = null;
        public T data = null;

        Node(T data) {
            this.data = data;
        }
    }

    public static class ListIterator<T> implements Iterator<T> {
        Node<T> current;
        Node<T> previous;

        public ListIterator(Node<T> head) {
            current = head;
            previous = head;
        }

        @Override
        public boolean hasNext() {
            return false;
        }
        @Override
        public T next() {
            return null;
        }
    }

    @Override
    public Iterator<T> iterator() {
        return new ListIterator<T>(head);
    }
}


How to empty the Directory-Name-Lookup-Cache?

Question: I'm having speed problems with a Windows software that is looking up files in several directories on a NTFS formatted HDD. In order to find out why and in which settings the problem is occurring I set up a test scenario at my local PC.
But this did not work as well as I expected. After the program did the first scan on all directories any additional scans on the same directories are done way faster than at the first scan. I assume that the directory names and there containing file names were cached by Windows.
Is it somehow possible to either disable or empty this cache, if it is even existing?
Answer: The NT "Cache Manager" is probably the culprit, as you've surmised. The cache manager and memory manager work closely to maximize the use of free physical memory to cache disk reads / writes (including both file data and filesystem metadata).
There's a SysInternals too, CacheSet that, amongst other features, will allow you to clear the cache manager's working set. I'd give that tool a go.


What is the virtue of loading absolutely-summability in the definition of causality of ARMA model?

Question: An ARMA series $y_t$ is causal function of $\nu_t$ if there exists constants $\psi_j$ such that
$\sum_{j=0}^{\infty} |\psi_j|<\infty$ and $y_t=\sum_{j=0}^{\infty} \psi_j\nu_{t-j}<\infty$ for all $t\in \mathbb{Z}$.
In this definition, why do we load $\sum_{j=0}^{\infty} |\psi_j|<\infty$ (absolute-summability) to the definition?
Why is the ordinary summability $\sum_{j=0}^{\infty} \psi_j<\infty$ not preferred instead? What is the virtue of loading absolutely-summability, if any?
PS: Tags like summability, absolutely-summable would be useful in stats.stackexchange.
Comment: The causality tag is not really appropriate here.
Comment: $\sum_{j=0}^\infty \psi_j <\infty$ doesn't make much sense, since it allows the sum to diverge to $-\infty$.
Comment: @gunes That probability is almost always omitted. Written as that, it denotes the finiteness from both ends.
Answer: I don't know what you mean by "load".
You question is really about absolute-summability (i.e. $l^1$ condition) of MA$(\infty)$ coefficients. "Causal" just means it's a one-sided MA$(\infty)$ representation, but MA$(\infty)$ just the same.
Without $l^1$ condition, convolution of sequences does not one make sense in general. In the time-series context, this means the autocovariance function of a MA$(\infty)$ time series would not be defined, this is clearly problematic, in many ways.
For example:

Calculations that establish elementary LLN's and CLT's for covariance-stationary time series are basically mechanical manipulations of the autocovariance function. So no ACF, no inference.
Going one step further, the spectral density is the Fourier transform of ACF. No ACF, no discussion of spectral aspects of covariance-stationary time series.


Amenable group $G$ and a (left) invariant mean on it.

Question: While reading "The Banach-Tarski Paradox" by S. Wagon, I faced the definition of a amenable group: a group that possesses a finitely additive, $G$-invariant measure on all subsets, with total measure one. (From now on, I will use the word 'measure' with this meaning only.) After some googling, I noticed this is actually what people call a 'discrete' amenable group, since no topology is considered on $G$.
After the definition, the book proceeds to explain that $G$ is amenable if and only if it possesses a left invariant mean. A left invariant mean is, by definition, a linear functional (denoted by $\int \,d\mu$) on $B(G)$, the collection of bounded real-valued functions on $G$, with the properties;

$\int af+bg \,\,d\mu=a\int f \,d\mu+b\int g \,d\mu$ if $a,b\in\mathbb{R}$;
$\int f \,d\mu\geq0$ if, for all $x\in G$, $f(x)\geq 0$;
$\int 1 \,d\mu=1$;
For each $g\in G, f\in B(G)$, $\int {}_{g}f \,d\mu=\int f \,d\mu$, where $({}_{g}f)(x)=f(g^{-1}x)$; that is, the integral is left-invariant.

If a left invariant mean exists, then using characteristic functions we immediately get a measure for $G$. BUT the problem I'm having is the opposite direction, constructing a left invariant mean from a measure, say $\mu$.
Obviously, we can try following the usual construction of Lebesgue integration, and define integral for simple functions, non-negative functions, and so on. But to my knowledge, the additivity of the integral requires Lebesgue's monotone convergence theorem, which relies on the countable additivity of the measure. Since the measure we have is only finitely additive, convergence theorems fail to hold and it seems like we have a serious problem with this approach!
To summarize, my questions are ..

Why does the existence of measure implies that of a left invariant mean?
Is there a way to show that integrals are linear functionals, avoiding the well known convergence theorems?

Please enlighten me.
Comment: See [here](https://terrytao.wordpress.com/2009/04/14/some-notes-on-amenability/).
Answer: Given a left invariant finite additive probability measure $\mu$, we define $\Lambda$ on simple functions by
$$
\Lambda \left( \sum_{k=1}^n a_k \mathbb{I}_{E_k} \right) = \sum_{k=1}^n a_k \mu \left( E_k \right)
$$
if $E_k$ is disjoint.
Noticed that simple functions is dense in $B(G)$ and $\Lambda$ is a non-negetive, left invariant and bounded linear functional, so $\Lambda$ can be extended on $B(G)$ by continuity.


Java Desktop com banco de Mysql

Question: Estou tentando gravar uma imagem no banco de dados MySql, a tabela está logo abaixo, o código pra carregar a imagem está logo em seguida, estou usando um botão pra carregar em um JLabel, após isso, uso outro botão pra inserir a imagem no banco, logo abaixo está o código do insert, enfim não estou conseguindo gravar no banco de dados.
Banco Mysql
create table imagens(
id int not null auto_increment,
cpf varchar(15) not null,
foto blob null,
primary key (id),
foreign key (cpf)
references funcionario(cpf)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;

Aqui e a onde eu carrego a imagem no JLabel a partir de um JFileChooser
JFileChooser fileChooser = new JFileChooser();   //Cria o objeto do tipo Janela JFileChooser
        fileChooser.setDialogTitle("Escolha a Foto");  //Define o título do JFileChooser
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);  //Define que só serão abertos arquivos
        {
            if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                try {
                    File arquivo = fileChooser.getSelectedFile();//arquivo
                    BufferedImage bi = ImageIO.read(arquivo); //carrega a imagem real num buffer
                    BufferedImage aux = new BufferedImage(100, 80, bi.getType());//cria um buffer auxiliar com o tamanho desejado
                    Graphics2D g = aux.createGraphics();//pega a classe graphics do aux para edicao
                    AffineTransform at = AffineTransform.getScaleInstance((double) 100 / bi.getWidth(), (double) 80 / bi.getHeight());//cria a transformacao
                    g.drawRenderedImage(bi, at);//pinta e transforma a imagem real no auxiliar
                    foto.setIcon(new ImageIcon(aux));//seta no jlabel
                    foto.setText(null);

                   // ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    //Jogue a imagem lá dentro do byteArrayOutputStream
                    //ImageIO.write(aux, "png", byteArrayOutputStream);

                }catch (IOException ex) {

                }

            }
    }

Este e meu insert.
String prep = "INSERT INTO imagens (foto,cpf)  VALUES(?,?)";

Image image = ((ImageIcon)foto.getIcon()).getImage();
PreparedStatement sttmt = con.prepareStatement(prep);
JTextField cpff = cpf;

sttmt.setBytes(1, bytes(image));
sttmt.setString(2, cpf.getText());

sttmt.execute();
sttmt.close();

Comment: Qual a mensagem de erro?
Comment: Ae e que ta não mostrar erro nenhum,simplesmente não inseri.
Comment: Você pode logar ou 'cuspir' essa exception para algum lugar, facilita o caminho para resolução do problema "catch (IOException ex) { faça algo aqui }"
Comment: @GleistonJosedeSantana troque `catch (IOException ex) { }` por `catch (IOException ex) { e.printStackTrace();}` e posta o erro disparado, agora nao sei pq vc fez um catch Exception se nao ta pedindo pra mostrar o erro disparado.
Answer: Bom, não é recomendável você colocar uma imagem direto no banco de dados. pois além de ser desnecessário iria ocupar muito espaço e fazer seu banco inflar de uma maneira exorbitante.
Tente upar essa imagem em algum lugar, como uma pasta compartilhada na rede ou em um serviço de nuvem. e no banco de dados tu só salva o caminho relativo da imagem por exemplo:
\\servidor\app\imagens\usuario\perfil.png
ou
https://raw.githubusercontent.com/zerossB/TotalRam/master/Images/TotalRAM-screen.png

Ai para recuperar tu passa como o caminho da imagem:
ImageIcon logo = new ImageIcon(new URL("https://raw.githubusercontent.com/zerossB/TotalRam/master/Images/TotalRAM-screen.png"));

Assim seu banco ficara mais leve e com menos processamento de dados entre a app e o banco.
Comment: Gostei da ideia da pasta compartilhada na rede,não tinha pensado por este lado,coisas de iniciante,bom gente muito obrigado,vou fazer a implementação,muito obrigado mesmo pelas dicas,valeu...
Comment: Precisar só chamar ;D

Java Desktop com banco de Mysql


Unexpected EOF (javascript)

Question: I have a PHP server on which I write both HTML and javascript. I am posting some data from a database into an array, then posting it in my HTML-file and then fetching it from my javascript file. This has worked just fine until I wrote a certain line of code (which is the same kind of command that I have been using all over my document). I tried to make a link this way, but every time I try to run it, it poses the following error
SyntaxError: Unexpected EOF

I have no idea how to get around this error. I hope you can help me.
The following is the part of my code that works fine before I change it
var para5 = document.createElement("button");
document.getElementById("et" + i).appendChild(para5);
var att16 = document.createAttribute("onclick");
att16.value = "window.location.href='/seForslag/?iden=" + i + "'"
para5.setAttributeNode(att16);
var att17 = document.createAttribute("class");
att17.value = "dFsu8t _2CdOjN knapet knapper";
para5.setAttributeNode(att17);
var att18 = document.createAttribute("id");
att18.value = "knap" + i;
para5.setAttributeNode(att18)
var para6 = document.createElement("span");
para6.innerHTML = "Se forslag"
document.getElementById("knap" + i).appendChild(para6)

And this is what I want it to be, but does not work
var para5 = document.createElement("button");
document.getElementById("et" + i).appendChild(para5);
var att16 = document.createAttribute("onclick");
att16.value = "window.location.href='/seForslag/?iden=" + document.getElementById("divId" + i).innerHTML + "'"
para5.setAttributeNode(att16);
var att17 = document.createAttribute("class");
att17.value = "dFsu8t _2CdOjN knapet knapper";
para5.setAttributeNode(att17);
var att18 = document.createAttribute("id");
att18.value = "knap" + i;
para5.setAttributeNode(att18)
var para6 = document.createElement("span");
para6.innerHTML = "Se forslag"
document.getElementById("knap" + i).appendChild(para6)

Here is the PHP that I am fetching data from
 <?php
                    $forslagid=array(1, 2, 3, 4, 5, 6, 7, 8);
    ?>

and the HTML

              <?php echo sizeof($forslagid) ?>

<?php for ($i = 0; $i < sizeof($forslagid); $i++) { ?>
          <div style="display: none;" id="divId<?php echo $i ?>">
            <?php echo $forslagid[$i] ?>

        <?php } ?>

Tell me if you need any more information :)
Comment: As you concatnate the string using double quote, try single quote around the "divId".
Comment: Need to see the entirety of an exemplar of the element with id divId*N*
Comment: @AliSheikhpour If you mean like this, then it does not work: document.getElementById('divId' + i).innerHTML
Comment: @Tibrogargan If you are talking about what is written inside the divs, it is just numbers from the array "forslagid" (1, 2, 3, 4, 5, 6, 7, 8), as you can see in the HTML piece I have provided
Comment: No sir, you have not.  You have provided some PHP that will use some variables that you have not shown to render some HTML that you also have not shown.  The reader has no way of telling if that rendered HTML is causing the issue, which could easily be the case if it's `innerHTML` contains a single quote (`'`)
Comment: is there a reason that `att16.value = "window.location.href='/seForslag/?iden=" + i + "'"` is not followed by a semicolumn `;` ? ( check all lines ) also, make sure that your php file has a closing tag without any hidden characters or lines after that
Comment: @ObmerkKronen No, that was a mistake, but I have now put ; everywhere, and it still does not work
Comment: well.. did you try to escape / encode the url ? but it will be difficult to say exactly without knowing the content of `i` or `el+i`..
Answer: Okay, so i figured it out. Apparently, something in the document made spaces around the numbers in the array, so the link might have been "window.location.href='/seForslag/?iden= 1 '". I have no idea why this happens, but I made it work by adding ".trim()" at the end like this:
att16.value = "window.location.href='/seForslag/?iden=" + document.getElementById("divId" + i).innerHTML.trim() + "'"

Unexpected EOF (javascript)


Can I add custom fields to a single page?

Question: Sorry for another "In Wordpress..." question but here we go...
In Wordpress, I can use ACF to add custom fields to a single page. This is done either in code or in the GUI by basically doing something like (pseudocode),
<code>if id = 123
  add_field "Phone Number"
end
</code>
This is especially useful on homepages or landing pages where the layout is unique and I want to provide structured data entry without needing to create a custom type that is only used once. In Drupal, I dont see a way to dynamically add fields to an arbitrary piece of content. Is this possible? How?

Wordpress custom fields:
Comment: I would actually add a new content type just for this case ... or perhaps you can play around with paragraphs they might fit you are trying to accomplish
Comment: As I was writing the question, I was thinking that I may just have to resort to single-use content types. It feels a little overkill, if I can get past that, then it seems to hit on all the other requirements I am looking for.
Answer: If you are using Drupal 8, you can create a block type and add fields to it. Then create a block of your block type and on visibility rules you can assign it to a specific page.

Video Tutorial.

If you're using Drupal 7, you can do the same, but you'll need the Bean module


Almost done with rolling without slipping problem (physics)

Question: I'm almost done with a problem on rotational mechanics.
I've got a golf ball rolling down a hill and I'm to find the value of the angle of the hill so that the ball can roll without slipping if the constant of friction $\mu = 0.29$.
Now I've got $$ a_t = \frac{0.29 \cdot 9.8 \cdot \cos( \theta ) \cdot 5}{2}$$ and this has to equal $ \alpha$ for it to not slip. I'm just having problems finishing this problem!
Note that the torque is applied by $F_f$.
$a_t$ is derived from $$ \alpha = \frac{F_f \cdot R}{I}$$
(As usual I want to remind that I prefer mathematics SE over physics SE and there is a physics tag on maths, so this question is perfectly fine).
Comment: Just keep in mind that I am trying to help you get help here.  You need to state the problem clearly and define your symbols explicitly.  Yes, lots of people here have had first semester physics, but nobody is going to want to put in the effort to explain an answer to you if you don't put at least a similar effort into formulating your questions.
Comment: If you insist on posting here, then you will need to supply context.  Please define $\mu$, etc.
Comment: I'm not sure if $\mu$ means anything other than constant of friction in physics? But then again I'm on my first semester. What more do you want to know...? This is all the information I get.
Comment: The golf ball is also uniform if anyone was wondering...And it's spherical..Unlike a normal golf ball...Come to think of it, a golf ball is a horrible example by my professor.
Comment: Do you mean that $\mu$ is the proportionality constant when you define the magnitude of the force of friction to be proportional to the magnitude of the normal force exerted by the hill on the golf ball?  That's what I mean by context.
Comment: I'm not sure what you mean by proportionality constant? $\mu$ is simply the constant of friction...? It's calculated from the normal force, though, yes. $F_N \cdot \mu \cdot \cos( \theta) = F_f$
Comment: Also, you assume a lot from us.  What is $9.8$?  $5$?  Units?
Comment: $9.8 = g$ and $5$ stems from $I = \frac{2}{5} MR^2$. I've just derived $a_t$. I only put $a_t$ down there in case someone could use it to solve my problem.
Comment: Thank you. Is there more I can fix about my question?
Answer: Let $\theta$ be the angle between the Hill surface and the ground.
$$ mgcos\theta - N = 0 \cdots(1)$$
$$ mgsin\theta - f_s = ma \cdots (2) $$
$$ \tau = Rf_s$$
$$Rf_s = I\alpha$$
$$ a= R\alpha$$
$$f_{s} = \frac{Ia}{R^2}$$
$$mgsin\theta - \frac{Ia}{R^2}= ma$$
$$ a = \dfrac {gsin\theta}{1+\frac{I}{R^2}}$$
$$ I = \frac{2}{5} MR_2$$
Substituting the value of I and a
$$f_s = \frac{2}{7}mgsin\theta$$
For an object rolling on an inclined plane without slipping
$$f_s \leq \mu mgcos\theta$$
$$\frac{2}{7}mgsin\theta \leq \mu mgcos\theta$$
$$tan\theta \leq \frac{7\mu}{2}$$
$$\theta \leq tan^{-1}(\frac{7\mu}{2})$$
Comment: @Paze, was the solution useful. If so, could you vote and accept the answer!


How can I reproduce the effects on this riff in Iron Maiden - Afraid to Shoot Strangers?

Question: Listen to this Iron Maiden song called "Afraid to Shoot Strangers" at about 2:43 (Iron Maiden fans will probably recognize the riff). This sounds very simple to me, but I don't know how they did it. I tried turning on the distortion on my amp, but it doesn't sound right. How can I reproduce this effect?
Comment: This question is a bit hard to follow, and seems really like 3 separate questions.  For the software, it depends entirely on what software you're using.  Regarding effects pedals, I don't understand what you're asking beyond "Can effects pedals produce effects" which seems too trivial to be what you meant.  I think really you just need to experiment with different effects and techniques to learn how to recognize their sound. Anyways, I'm going to edit this to just be about the last bit. If you think you can re-formulate one of the others into a better question, feel free to post it separately.
Comment: @MatthewRead Okay, thanks. Yes, I'll probably ask about the software in another question.
Answer: For this classic sound you need a metal pedal and an echo or delay. Also you really need another guitarist- Maiden love their dual melody/harmony lines.
Some more detail:
Adrian always used Marshalls, with the treble slightly higher than the bass and mid, and the gain cranked up high.
Delay of about 300ms, with a medium feedback level, and a fair bit of Reverb.
Comment: Maybe this "dual melody" thing could be achieved with a harmonizer / Pitch Shifter ? If I remember well the two melodies are the same, with the same interval between the notes.
Comment: Sadly, a fixed interval pitch shifter will not work, as the interval changes. They use a lot of minor thirds and diatonic thirds and sixths - but it isn't the same for every note. A pitch shifter which allows you to alter the interval on the fly could work (some Zoom pedals, and the Digitech Whammy might work) - but could be challenging :-)
Comment: I don't hear a harmonic melody line until later in the song. You could get close to it with a "harmonized pitch shifter" -- there's even one in the budget Zoom G1. You tell it what key you're playing in, and it plays a note shifted up a third *adjusted for the key*.
Comment: Yeah - my old Zoom 4040 did that reasonably well
Comment: But for live changes, the Whammy can do some of this - pedal to change from 3rd to 5th etc


Problem with passing parameters from body-parser to Get JSON data

Question: this is a simple code to get BTC price using api and parameters.
When I try this code I get undefined, but if i replaced "data.rates.crypto;" by "data.rates.BTC" I get a
the value of the current price despite the value of crypto is the same 'BTC'
app.post("/", function(req, res) {
  var crypto = req.body.crypto; //this line gives BTC
  var baseUrl = "http://api.coinlayer.com/api/live?access_key=lablabalab&symbols=";
  var finalUrl = baseUrl + crypto; //no problem here by passing the parameter whics is BTC
  request(finalUrl, function(error, response, body) {
    var data = JSON.parse(body);
    var price = data.rates.crypto;  //here is the problem
    res.write("
Cuurent Price From " + crypto + " To USD is " + price + "
");
    res.send();
  });

Answer: The response payload looks like this:
{"success":true,"terms":"https:\/\/coinlayer.com\/terms","privacy":"https:\/\/coinlayer.com\/privacy",
"timestamp":1611389888,
"target":"USD",
"rates":{"BTC":32728.891547}}

So you need to access data.rates, but the value of the crypto variable (BTC) rather than by the name crypto. You can do that with hash access:
var price = data.rates[crypto];


In ASP.NET MVC3, will cshtml files be compiled? Liks JSP files?

Question: In Java EE, A Servlet container will transform JSP files to a Servlet class and compile that.
So, how does an ASP.NET server process .cshtml files?
Comment: Yes, it does compile the C# code and markup. Is there a specific reason you are asking?
Answer:
Yes, when the application in running, every request to a particular cshtml will compile it.
No, when the application is being built. This behavior can be changed.


Raised leading tones in Phrygian mode counterpoint

Question:
In most cases the penultimate note of the counterpoint will be the
  leading tone, which must be raised in minor to establish a sense of
  tonality. But why is the leading tone in the Phrygian mode (E-E) the
  one exception? Even though it is a minor mode the seventh step of the
  scale is NEVER raised. Why?

Transferred from: Few Questions on Counterpoint in the Tradition of Johan Fux
Comment: @Tim - This is incorrect.  D#-F is actually a diminished third but will sound as a major second.
Comment: In the other minor modes, i.e., Dorian and Aeolian, the leading note may or may not be raised. This creates a melodic interval with the supertonic .In Phrygian,raising the leading note  gives an odd sounding interval with the supertonic. I'm only guessing.
Comment: @Tim - Again, please refer to my posted answer.
Comment: @Tim: exactly, an augmented second (that's from google translate). That is practically the same as a minor third, and you wouldn't want thirds in your scale. Especially not in the 15th century.
Comment: In Phrygian E, the raised leading note becomes D#.The supertonic (2nd note) is F. D# - F will be an ordinary 2nd, not a good sound to resolve to E. Did I miss your point?
Comment: Sorry, yes, as D-F is min 3rd, so making it one semitone smaller makes it, as you say, a dim. 3rd (but not aug 2nd.).
Answer:
This is an astute question, and I will preface my response by saying
  that it is speculatory at best as I do not know of any scholarly
  research done that is available to me to provide a qualitative,
  academic answer.
That said, I believe this website offers thoughtful reasoning as
  to this occurrence.

Transferred from: Few Questions on Counterpoint in the Tradition of Johan Fux
Edit: The original page at ars-nova.com seems to have gone offline - DNS lookup fails. Here is the cached version at the Internet Archive's Wayback Machine.
Comment: JJ - could you add a summary of that website to this answer? Otherwise it is pretty much just a link.
Comment: In a sense, the flat-2 *is* the leading tone in Phrygian.  It just happens to lead *downward* to the tonic instead of upward.
Answer: I have a theory,
In the phrygian mode you have a flat second, and you always end the Cantus firmus by going II I.
If you were to sharpen the 7th then you would have a major 2nd interval, a dissonance which is against the rules of counterpoint, but a natural 7th creates an interval of a minor 3rd.
I'm sure early on in the book he talks about how the ending should resolve based on major/minor intervals, rather than the degree of the scale.
Answer: The easiest answer to a question is the simplest one requiring the fewest assumptions. In this case I think there is a useful general principle: consecutive semitones are generally avoided because the tone in the middle sounds like a chromatic passing tone. If you are in E Phrygian and you move from D# to E, and then to F, then the E in the middle sounds like a chromatic passing tone and not like a scale step. That is not a good thing to do to a final! More here: Pressing, J. (1978). Towards an understanding of scales in Jazz. Jazzforschung, 9, 25–35. Also here: The Consecutive-Semitone Constraint on Scalar Structure: A Link between Impressionism and Jazz, by Dmitri Tymoczko
Answer:
If you are writing two-voice species counterpoint according to Fux's rules,
and the cantus firmus is in the bottom voice
and that bottom voice descends by step to the final in the Phyrgian mode--that is, the bass moves down a minor second from F to E in an untransposed mode;
then the upper voice in two-voice counterpoint sings D--E, because the final octave consonance must be preceded by a major sixth.

A D# in the upper voice would create an augmented sixth, which Palestrina did not use.
These are Fux's rules, based on his analysis of Palestrina. They are akin to a description of Latin grammar based on Cicero. They describe idioms that were used in Renaissance polyphony, but there is not necessarily any logic to them beyond that.
Further, Fux's counterpoint has nothing to do with scales in jazz, or with the harmony of post-1800 tonal music. Fux is not describing "vertical" harmonic progressions but "horizontal" contrapuntal movements.


Pegar última div de uma div

Question: Considerando essa estrutura:

A

A

A

A

A

preciso pegar a div de número de uniqid = 5 ou seja, sempre, a última da div com id PAI como fazer?
Comment: último elemento/objeto ou última "div" ? pode acontecer de existir outros elementos dentro de uma div, exemplo, um , uma ancora , um row
Comment: @DanielOmine o último objeto vai seguir o modelo que demonstrei acima sendo sempre uma div com tais atributos mas elas sempre estarão recheadas de outros elementos..
Answer: Podes usar element.lastElementChild que quando aplicado ao elemento pai dá o que queres, o ultimo elemento.
exemplo: http://jsfiddle.net/7rz7o7u0/

var pai = document.getElementById("PAI");
var ultimoFilho = pai.lastElementChild;
ultimoFilho.style.backgroundColor = 'green';

A

A

A

A

A

Answer: Pode utilizar document#querySelector().

Obtendo o último elemento pela classe .filho :

var last = document.querySelector(".filho:last-child");
last.style.color = 'red';

A

A

A

A

A

Obtendo o último div dentro de #PAI :

var last = document.querySelector("#PAI div:last-child");
last.style.color = 'red';

A

A

A

A

A

Obtendo o elemento pelo uniqid=5 :

var last= document.querySelector("[uniqid='5']");
last.style.color = 'red';

A

A

A

A

A

Comment: Cabe mencionar que `.querySelector` funciona também pra nós, i.e. também dá pra fazer `document.getElementById('PAI').querySelector(':last-child')`; isso é útil se você já tiver uma referência a `#PAI` à mão.

Pegar última div de uma div


React-Bootstrap: separate two buttons in navbar

Question: I have a react-bootstrap Navbar defined as follows, but I can't seem to find a way to put some space between the Login and Register buttons: here the output I get instead.
<Navbar id="navigation-bar" collapseOnSelect sticky="top" expand="lg" bg="light" variant="light">
          <Navbar.Brand href="/">Sort-CVA</Navbar.Brand>
          <Navbar.Toggle aria-controls="responsive-navbar-nav" />
          <Navbar.Collapse id="responsive-navbar-nav">

              Home
              Upload Results
              {/*Login
              Register*/}
              About

            <Form inline >
              <Button variant="primary" href="/login">Login</Button>
              <Button variant="outline-primary" href="/register">Register</Button>
            </Form>
          </Navbar.Collapse>
        </Navbar>

Answer: Since you're using bootstrap you can take advantage of the bootstrap utility classes, in your first button you can do:
<Button variant="primary" href="/login" className="mr-2">Login</Button>

That mr-2 class would add some margin right to your button, which is exactly what you need in order to create some space between them.


How do I create a administration page (with overlay) through the UI

Question: I would like to add an administration page (with overlay) to my site (not programatically). I assume the basic process is:

Create a 'basic page'
Set the path to /admin
Set permissions <-- How do I do this???  I can't see how do I
restrict the page??
Configure overlay - Is it automatic?
Add page to admin menu.

I'm stuck on 3, but I could probably use help on 4 and 5.
Thanks!
Comment: Without a module, it is not possible to make a node appear in an overlay.
Answer: You're probably looking for the Overlay Paths module:

This is a simple module that enables site builders to use the built-in Overlay for non-admin pages.

However, if the path you've got for the node is under /admin I'm pretty sure that if you configure permissions properly you won't need that module; the overlay should pop up automatically. You'll need to give your users the "Use the administration pages and help" permission, as well as the one to actually use the overlay.
As it's a node, whatever node access solution you have in place will determine the access beyond those two permissions.
Comment: I tried, but the overlay is not used, with nodes, even assigning them a menu item under /admin.
Comment: 1) What do you mean by 'configure permissions properly'.  I'm trying to restrict this custom admin page (node) that even anonymous users can see but I don't see how AND this page is under /admin
2) I get the same behavior as kiamlaluno.  I can manually append #overlay=admin/ to any core admin page and it works fine, if I change it to my custom page it no longer works (just jumps back to the non-admin page).  This may be because of the above problem (page is not yet restricted) but this brings be back to the question that I can't find the answer to: how do I restrict a node?
Comment: @user11792 What are you actually asking? How to show a node in the overlay, or how to configure permissions for a node so that your users can view it? It's one question per question around here :) Did you try the overlay paths module as recommended?
Comment: I'm asking the question at the top of the page.  But I assume that it's not a one-step process and entails proper permissions being set, which is why overlay doesn't work.  If there is a way to get overlay to work without setting proper permissions, then I'd be happy to start a new question, but if not then: how do I set permissions for the custom admin page so that overlay works correctly.


INSERT e INNER JOIN juntos no MySQL?

Question: Olá é possivel utilizar o INNER JOIN juntamente com o INSERT?
Possuo uma tabela A com 3 colunas X, Y e Z e a tabela B com as colunas W, X e Y e preciso inserir na tabela A a coluna W da tabela B, teria como?
Estou tentando dessa forma porem n obtenho resultado :
INSERT INTO Categoria_cliente_teste  (planejamento)
SELECT plano_orcamentario
FROM Categoria_clientes
INNER JOIN [ON cliente_fornecedor]

Comment: coloque o que tentou na pergunta, para facilitar para quem ver depois
Comment: É possível e é algo bem comum se usar INSERT ... SELECT (dependendo do caso nem precisa do JOIN). O que tentou e qual o problema encontrado? EX: `INSERT INTO tabela A .... campo1, campo2 SELECT B.algo, C.algo FROM tabelaB JOIN tabelaC ON ...`
Comment: Sim, tem como fazer com o Inner Join, mas seria interessante exemplificar o que você quer fazer. Adicionar uma melhor descrição das tabelas e o código que já tentou.
Answer: Siim é possível!!
De acordo com sua descrição, criei o seguinte exemplo:
1- Criei um banco de dados com o nome "test"
2- Criei as seguintes tabelas:
Tabela: a
Colunas: x, y e z
-
Tabela: b
Colunas: w, x, y
Um exemplo de insert seria:
INSERT INTO test.a ('y', 'z') SELECT b.x, b.y FROM test.b b;
Você pode usar um inner join para selecionar os resultados que queira inserir normalmente, aconselho você dar um alias para a tabela da consulta, pois fica mais fácil para associar aos valores.
Com o JOIN:
INSERT INTO test.a ('y', 'z') SELECT b.x, b.y FROM test.b b JOIN c ON c.y = b.y;
:)

INSERT e INNER JOIN juntos no MySQL?