"Error: /run/airflow doesn't exist. Can't create pidfile." when using systemd for Airflow webserver

Question: I have configured my Airflow setup to run with systemd according to this. It was great for a couple of days but it has thrown some errors that I can't figure out how to fix. Running sudo systemctl start airflow-webserver.service doesn't really do anything but running airflow webserver works (however, using systemd is needed for our purposes).
To understand what's the error, I run sudo systemctl status airflow-webserver.service, and it gives the following status and error:
Feb 20 18:54:43 ip-172-31-25-17.ec2.internal airflow[19660]: [2019-02-20 18:54:43,774] {models.py:258} INFO - Filling up the DagBag from /home/ec2-user/airflow/dags
Feb 20 18:54:43 ip-172-31-25-17.ec2.internal airflow[19660]: /home/ec2-user/airflow/dags/statcan_1410009501.py:33: SyntaxWarning: name 'pg_hook' is assigned to before global declaration
Feb 20 18:54:43 ip-172-31-25-17.ec2.internal airflow[19660]: global pg_hook
Feb 20 18:54:43 ip-172-31-25-17.ec2.internal airflow[19660]: /usr/lib/python2.7/site-packages/airflow/utils/helpers.py:346: DeprecationWarning: Importing 'PythonOperator' directly from 'airflow.operators' has been deprecated. Please import from 'airflow.operators.[operat...irely in Airflow 2.0.
Feb 20 18:54:43 ip-172-31-25-17.ec2.internal airflow[19660]: DeprecationWarning)
Feb 20 18:54:43 ip-172-31-25-17.ec2.internal airflow[19660]: /usr/lib/python2.7/site-packages/airflow/utils/helpers.py:346: DeprecationWarning: Importing 'BashOperator' directly from 'airflow.operators' has been deprecated. Please import from 'airflow.operators.[operator...irely in Airflow 2.0.
Feb 20 18:54:43 ip-172-31-25-17.ec2.internal airflow[19660]: DeprecationWarning)
Feb 20 18:54:44 ip-172-31-25-17.ec2.internal airflow[19660]: [2019-02-20 18:54:44,528] {settings.py:174} INFO - setting.configure_orm(): Using pool settings. pool_size=5, pool_recycle=1800
Feb 20 18:54:45 ip-172-31-25-17.ec2.internal airflow[19660]: [2019-02-20 18:54:45 +0000] [19733] [INFO] Starting gunicorn 19.9.0
Feb 20 18:54:45 ip-172-31-25-17.ec2.internal airflow[19660]: Error: /run/airflow doesn't exist. Can't create pidfile.

The scheduler seems to be working fine, as verified after running both systemctl status airflow-scheduler.service and journalctl -f.
Here's the setup of the following systemd files:
/usr/lib/systemd/system/airflow-webserver.service
[Unit]
Description=Airflow scheduler daemon
After=network.target postgresql.service mysql.service redis.service rabbitmq-server.service
Wants=postgresql.service mysql.service redis.service rabbitmq-server.service

[Service]
EnvironmentFile=/etc/sysconfig/airflow
User=ec2-user
Type=simple
ExecStart=/bin/airflow scheduler
Restart=always
RestartSec=5s

[Install]
WantedBy=multi-user.target

/etc/tmpfiles.d/airflow.conf
D /run/airflow 0755 airflow airflow

/etc/sysconfig/airflow
AIRFLOW_CONFIG= $AIRFLOW_HOME/airflow.cfg
AIRFLOW_HOME= /home/ec2-user/airflow

Prior to this error, I moved my airflow installation from root to home directory. Not sure if it would have affected my setup but putting it here in case it is relevant.
Can anyone provide any explanation for the error and how to fix it? I tried my best to configure systemd as closely as possible to what is instructed but maybe I'm missing something?
Edit 2:
Sorry, I pasted the wrong code. So this is my code for airflow-webserver.service
[Unit]
Description=Airflow webserver daemon
After=network.target postgresql.service mysql.service redis.service rabbitmq-server.service
Wants=postgresql.service mysql.service redis.service rabbitmq-server.service

[Service]
EnvironmentFile=/etc/sysconfig/airflow
User=ec2-user
Type=simple
ExecStart=/bin/airflow webserver --pid /run/airflow/webserver.pid
Restart=on-failure
RestartSec=5s
PrivateTmp=true

[Install]
WantedBy=multi-user.target

Answer: I encountered this issue too and was able to resolve the issue by providing runtime directory parameters under [Service] in the airflow-webserver.service unit file:
[Service]
RuntimeDirectory=airflow
RuntimeDirectoryMode=0775

I was not able to figure out how to get it to work with /etc/tmpfiles.d/airflow.conf alone.
Comment: @Newskooler this is my first time using systemd so I am by know means expert but I assume that this tells systemd to create the dir /run/airflow with permissions 0775, and that when you don't specify this, the directory won't be created, or won't be created with sufficiently permissive permissions
Comment: @chorbs, could you please provide more detail on why this worked for you?
Comment: That's exactly what it does. It makes the `/etc/tmpfiles.d/airflow.conf` redudnent. I don't know why it was not added in the airflow repo like this...
Comment: i added the runtimeDirectoryMode to 775,but still getting the same Error
Comment: did you also add `RuntimeDirectory`?
Answer: The config file /etc/tmpfiles.d/airflow.conf is used by systemd-tmpfiles-setup service at boot. So, a server restart should create the /run/airflow directory. It's not possible to just restart this service as per https://github.com/systemd/systemd/issues/8684.
As suggested at the above link, after copying airflow.conf to /etc/tmpfiles.d/, just run sudo systemd-tmpfiles --create and /run/airflow should get created.
Answer: It looks like you are running the scheduler and not the webserver:
ExecStart=/bin/airflow scheduler
You might want to do something like:
ExecStart=/bin/airflow webserver -p 8080 --pid /run/airflow/webserver.pid
Maybe you just copy pasted the wrong file, do share the correct one in that case (airflow-webserver.service) so we can help you troubleshoot this.
Comment: Sorry about that, I pasted the wrong code. I updated it above


Mortgage loan predictive analysis

Question: I have hundreds of thousands of mortgage loan historic records that look like these 2 examples:
<code>CCCCCCCCCCCC33CCCC3CCCCCCMFBBBBM999999999999999999963CM3CCCCCCCCCC
BFFFFFFFFFFFFFFFFFFFFFFFFF99999999999963333CC33333333CCCCCCCCCCCCCCCCCCCC
</code>
Each symbol is a monthly status of a loan: C - current, F - foreclosure, M - modification, 3 - 30 days late, 9 - 90 days late, etc. I'm looking to use a machine learning algorithm that could learn form the data and would be able to predict probabilities of the next month outcomes. Could you point to a subset of approaches that I should look into?
Answer: It's a futile exercise. Forget about it.
If you really want to do something of value, start with reading the existing literature on this subject. It's vast. For instance, you can start with Fabozzi's MBS handbook or Salomon' red book. There are many books and tons of articles, e.g. this one with Markov chains.
I'll give you an example to show why your approach is doomed. Let's say you've got IO HELOC, and that you had a fixed payment period ending soon, and that interest rates may (or may not) rise, in this case you're going (or not going) to experience a payment shock. This will have a significant impact on your C->3 transition probability, and eventually on C->F. This payment shock is quite predictable, at least we know when exactly it may or may not happen. If you don't account for these things, your machine learning thing will be garbage.
Comment: I understand this, I was thinking that this can be only a part of my model. I would exclude periods of systemic shocks from the data. It's interesting to see if, isolated from macro events, borrowers can be scored based on their past performance alone (at least to some extent). This is more like a science project.
Comment: Yes, the past performance matters. If you look at mortgage literature you'll find concepts like "burnout": the borrower could but didn't refinance the loan in the recent past for some reason. This borrower will be less likely to respond to prepay incentives, i.e. C->PayOff should be less sensitive to interest rates. If the borrower was delinquent in the past, he will be more likely to be non-current in the future etc. The reason is that there are some non-observable and observable borrower attributes that are persistent.

Mortgage loan predictive analysis


NSIS Error creating shortcut on desktop

Question: I'm trying to use NSIS for installing my application.
When trying to create shortcut on the desktop, it fails.
this is the script relevant part i'm using:
SetOutPath "$INSTDIR"
File "${BIN_DIRECTORY}\app.exe"
CreateShortCut "$SMPROGRAMS\app\app.lnk" "$INSTDIR\app.exe"
CreateShortCut "$DESKTOP\app.lnk" "$INSTDIR\app.exe"

This is the log:
Extract: app.exe... 100%
Create shortcut: C:\Users\roeia\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\app\app.lnk
Error creating shortcut: E:\Users\roeia\Desktop\app.lnk

the path is correct, and i don't have any problem to create or modify files there.
I'm using windows 7 64bit.
Thanks for helping!
Answer: It might be a right problem: do you run the installer as admin?
Specifying RequestExecutionLevel in the script may help to do so:
RequestExecutionLevel admin ;try also with 'highest'

Comment: Trying admin/highest made no difference, still getting the errors.

The default location of setup is on server, tried running it locally but the same results.
Comment: Why is admin level required to create a link on the user's desktop?
Answer: Perhaps the use of \r in the executeable path is causing the problem. Try \r to avaoid character substitution.

NSIS Error creating shortcut on desktop


In python socketio RuntimeWarning: coroutine 'initial' was never awaited despite writing an await statement

Question: python3 client.py
/home/aijax/.local/lib/python3.6/site-packages/socketio/client.py:592: RuntimeWarning: coroutine 'initial' was never awaited
  self._handle_event(pkt.namespace, pkt.id, pkt.data)
connection established
despite of having the await I'm getting the error
PS: I have little to no knowledge of Async-io of python I kinda have finish this task overnight for a school proj
my client.py
import socketio
import time

sio = socketio.Client()
val={"num":35}

@sio.event
def connect():
    print('connection established')

@sio.event
def disconnect():
    print('disconnected from server')

@sio.event
async def initial(sid):
    global val,sio
    print("hey there!! ")
    await sio.emit('clientUpdate',val)

@sio.event
async def serverAggregate(avg):
    global val
    val["num"] = (avg["num"] + val["num"])/2
    # print(val)
    print("kaada ",avg)
    time.sleep(4)
    await sio.emit('clientUpdate',val)
    # await

sio.connect('http://0.0.0.0:8080')
# sio.wait()
# sio.my_message()

sio.wait()

My task is to create a server and many clients which send a number to server and server aggregates that and sends it back to the client and perform a local update and send back the number
my server.py
from aiohttp import web
import socketio
import time
import threading

# creates a new Async Socket IO Server
sio = socketio.AsyncServer()
users_count=0 #num of clients
temp_count=users_count
avg={"num":0}
temp_sum=0
initFlag=True
# Creates a new Aiohttp Web Application
# app = web.Application()
async def handle(request):
    print(request)
    name = request.match_info['name']
    text = "Hello, " + name
    return web.Response(text=text)

app = web.Application()
sio.attach(app)

async def resetter():
    global avg,temp_sum,users_count,temp_count,sio
    avg = temp_sum/users_count
    temp_count = users_count
    temp_sum = 0
    print("broadcast requests to clients")
    time.sleep(2)
    await sio.emit('serverAggregate',avg,broadcast = True, include_self = False)

@sio.on('clientUpdate')
async def serverAggregate(sid, data):
    global temp_count,users_count,initFlag,sio,resetter

    if initFlag:
        temp_count=users_count
        initFlag=False

    temp_count=temp_count -1
    if(temp_count==0):
        await resetter()
    else:
        print("message ", data)
        global temp_sum
        temp_sum = temp_sum + data["num"]
        print("message ", data)

@sio.event
async def connect(sid, environ):
    global users_count,sio
    print("connect ", sid)
    users_count=users_count+1
    # time.sleep(3)
    # print("say something")
    time.sleep(2)
    await sio.emit('initial')
    # await sio.emit('intialize', broadcast = True, include_self = False)

@sio.event
def disconnect(sid):
    global users_count
    print('disconnect ', sid)
    users_count=users_count-1

app.add_routes([web.get('/', handle),
                web.get('/{name}', handle)])

# app.router.add_static('/static', 'static')
class BgProc(threading.Thread):

    def __init__(self, sio):

        # calling superclass init
        threading.Thread.__init__(self)
        # self.text = text
        self.sio = sio

    def run(self):
        time.sleep(5)
        print("sending broadcast to all clients ")
        self.sio.emit("initial",broadcast = True, include_self = False)

if __name__ == '__main__':
    web.run_app(app)

Answer: You are using the socketio.Client() class which is the standard Python client. If you want to write an asyncio application, you must use socketio.AsyncClient().


Change the Solr Operator to OR

Question: Am working with drupal search api solr module am trying to get it to work with the OR Operator so if i do a search for "David Smith" it should show results for both "David" and "Smith" does anyone have ideas on how to achieve this
Comment: Are you trying to do this in code (a custom module) or just by entering in search terms into the search box?
Comment: my entering a search term in the search box
Answer: By default, the apachesolr Drupal module is set to do an AND search.  However, you can change that in one of two ways:

Implement a custom module that alters the queries sent to apachesolr.  All you'd need is to implement the apachesolr_query_alter hook.
<code> <?php
 function HOOK_apachesolr_query_alter($query) {
   // Force an OR keyword search.
   $params['mm'] = '100%';
 }
 ?>
</code>

More details can be found on this drupal.org documentation page: http://drupal.org/node/1159424

The second thing you can do is modify the deafaultOperator from "AND" to "OR" in apachesolr's schema.xml file.  You should be able to find that in your modules/apachesolr/solr-conf folder.  That setting should be towards the end of the file
<code><!-- SolrQueryParser configuration: defaultOperator="AND|OR" -->
<solrQueryParser defaultOperator="AND"/>   // change to OR here
</code>

With this second one, just be careful.  You don't want to make this change to your schema file and then forget and have it replaced later when you update your module or something like that.  Just by searching now, I can see there is this rather unstable module that exposes some of the configuration options of the schema file in the User Interface: http://drupal.org/project/apachesolr_confgen, but I'm not sure I'd choose to use that...
Hope one of these helps!
Comment: Thanks for the tips i have tried to use the hook in my template.php file but there is no change does this have to be in a custom module. also i am using the http://drupal.org/project/search_api_solr  module not http://drupal.org/project/apachesolr so am guessing the hook may not work in this case?
Comment: Hey there, this should be your own separate module, but it can be quite minimal, since all you really would need is your .info file, and the hook above in your .module file (of course, with your module's name substituted in for the 'HOOK' part).  This does indeed work with apachesolr, and I'm not sure if your module would call that hook...
Comment: Once again thanks for your help i have tried this on a custom module but it seems that hook is not available on the  www.drupal.org/project/search_api_solr module. is there any other way to do this? thanks
Comment: @user1108509 The hook is named `hook_search_api_solr_query_alter()` for that module, there's a list of them in the search_api_solr.api.php file that comes with the module

Change the Solr Operator to OR


3:2 polymeter in a single 6/4 time signature, which accent pattern would be which meter?

Question: I've noticed that 6 allows me to have a 3:2 polymeter in a single time signature. I've thought of perhaps doing it for the Saturn movement of my Planets Suite, where some instruments have a 3/4 emphasis and others have a 2/4 emphasis and the time signature itself is 6/4.
But like, how would I get that across? I mean what's intuitive and what's true for 6/8 are exact opposites(intuitive, accent every 3 beats is a 3/4 emphasis, accent every other beat is a 2/4 emphasis, true for 6/8, accent every 3 is a 2/4 emphasis and accent every other is a 3/4 emphasis). And if something applies to 6/8, it would make sense that it would apply to 6/4 as well. Except that tempo probably has something to do with it and the Saturn movement would be a slow Adagio, so maybe the intuitive would apply?
I know I could just have it so that there are 3/4 and 2/4 time signatures alternating staves or whatever, but that would probably be more confusing than helpful, especially for the conductor(yes, my suite if you didn't already know is for an orchestra) and in practice, I've only seen this in piano pieces and pieces for bands, and even then, very rarely. Never have I seen it for orchestra. I've seen time signatures alternate across time in orchestral works, but not across instruments. So having a single 6/4 time signature would probably be helpful to the conductor. It would also make it a whole lot easier on Musescore, as I have found that I can't paste when time signatures are alternating staves, at least for piano and other instruments using the grand staff.
But that then begs the question of which accent pattern would correspond to which meter. This is what my intuition tells me:

In other words, my intuition is telling me that an accent on every third quarter note will give a 3/4 feel and that an accent every other quarter note will give a 2/4 feel. But then again, for 6/8, it is just the opposite and as I stated before, it would make sense that what applies to 6/8 applies to 6/4. But then again, tempo has to be taken into consideration and for Saturn, that tempo is a slow Adagio. And slow tempos tend more towards individual beats than multiple pulses in a beat, which leads me back to what my intuition is telling me. And while the example I show probably won't be the exact musical material I use for the Saturn movement, it does show the basic concept behind it, that being a high pitched glistening melody over an accompaniment(which in the Saturn movement will probably have countermelody as well as the arpeggios I have in the image).
So, for a slow 6/4, is it true that accenting every third quarter note will produce a 3/4 feel and that accenting every other quarter note will produce a 2/4 feel? Or do I have those backwards?
Comment: Normally the ambiguity in a 6/4 measure would be expressed as the ambiguity between the normal 6/4 compound duple meter (two groups of three quarter notes each per measure) and 3/2.  Do you really mean to ask about 2/4 or are you using that to indicate 3/2?  The examples in the question look like plain 6/4.  Where is the polymeter?
Comment: I do mean to ask about 2/4. And yes, the example I show is plain, normal 6/4, but you can imagine that if I had the cellos going S, w, w, S, w, w and the violas going S, w, S, w, S, w within the same 6/4 measure, that there would be a 3/4 2/4 polymeter
Answer: In addition to accents, you could also use beaming (on the eighth notes) to indicate grouping. Accents and pedal markings also help as does slurring. Some pieces (alternating 3/4 and 6/8 which isn't uncommon) just write 3/4 and 6/8 in each measure. The only difficulty is that 6/4 (like 6/8) is a compound meter and almost always used to indicate triplets.
It might be simpler in your case to bar the measures as 3/4,3/4,2/4,2/4,2/4... (I suppose a note at the beginning could indicate that the 3+3,2+2+2 continues throughout the piece.)


form with taxonomy autocomplete widget throws error upon submit: Invalid argument supplied for foreach()

Question: I have a custom form with this field in it:
$form['first']['field_city'] = array(
    '#title' => t('Woonplaats'),
    '#type' => 'textfield',
    '#size' => 25,
    '#autocomplete_path' => 'taxonomy/autocomplete/field_city',
    '#element_validate' => array('taxonomy_autocomplete_validate'),
    '#required' => TRUE,
);

I'm trying to use the autocomplete tagging widget to use with an existing taxonomy vocabulary on this form.
It works fine tags are loaded when I start typing but if I submit the form I get the following Warning:
Warning: Invalid argument supplied for foreach() in taxonomy_autocomplete_validate()

resulting in this error and the wsod (white screen of death)
   PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '))' at line 2:
SELECT base.tid AS tid, base.vid AS vid, base.name AS name, base.description AS description, base.format AS format, base.weight AS weight, v.machine_name AS vocabulary_machine_name FROM {taxonomy_term_data} base INNER JOIN {taxonomy_vocabulary} v ON base.vid = v.vid WHERE (base.name LIKE :db_condition_placeholder_0 ESCAPE '\\') AND (base.vid IN ()) ; Array ( [:db_condition_placeholder_0] => Amsterdam )

I think I'm missing something in the form decleration or made a mistake somewhere.
So what's wrong with it? Thanks!
some suggestion is that the machine_name of the field might be wrong. ( the machine name is actually stad when I look in the taxonomy in the admin UI).
Answer: I'm pretty sure this error will be coming from the following loop in taxonomy_autocomplete_validate()
 // Collect candidate vocabularies.
    $field = field_widget_field($element, $form_state);
    $vocabularies = array();
    foreach ($field['settings']['allowed_values'] as $tree) {
      if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
        $vocabularies[$vocabulary->vid] = $vocabulary;
      }
    }

which is collecting the vocabularies allowed for the field, check:

Field is set to be a term reference
Field has at least one allowed vocabulary set
field_city is the correct machine name of the field in question
Comment: You could still create the form item without any of the above being true, but the auto complete wouldn't know what vocab to check
Comment: oke so it was the machine name, the machine name is `stad` but if I change the `'taxonomy/autocomplete/field_city',` to `'taxonomy/autocomplete/stad',` or `'taxonomy/autocomplete/6',` (vid) I still get the error but now as an alert box and none of the terms are shown in the auto tag widget textfield.
Comment: thank for your answer. Yes you are right line 1585 of the taxonomy module throws the error.
1. I think so otherwise fields would not be loaded?
2. Yes `Amsterdam` in this case?
3. This one I know for sure, the machine name is correct.
Comment: I've put in `watchdog("fieldtest", print_r($field), array(), WATCHDOG_ALERT);` on line 1584 of taxonomy.module resulting in a `1` printed in the log files out of `print_r($field)`
Comment: so It could be 1 or 2 as you suggested but how do I check that? I'm guessing setting the field to `  '#type' => 'taxonomy_term_reference',` in the form is not it ( done that and the field disappears )
Comment: FLY - did you ever figure it out?
Comment: Never got it really figured out, but removing the '#element_validate' prevents the error from showing. guess I'll have to write a custom validation for it to really fix it...
Comment: @BrianV I've got it figured out! see [my blog](http://codedrup.blogspot.nl/2012/10/adding-city-autotagging-field-to-user.html)
Answer: It works without validation and also by changing the machine name of the taxonomy field using the UI from stad to field_city:
$voca = taxonomy_vocabulary_machine_name_load('field_city');
$form['first']['field_city'][$voca->vid] = array(
    '#type' => 'textfield',
    '#title' => $voca->name,
    '#required' => TRUE,
    '#field_name' => $voca->machine_name,
    // '#language' => 'nl',
    // '#field_parents' => array($voca->machine_name),
    // '#element_validate' => array('taxonomy_autocomplete_validate'),
    // '#default_value' => 'test_default_value',
    '#autocomplete_path' => 'taxonomy/autocomplete/' . $voca->machine_name,
    '#size' => 25,
);

Also removing the #element_validate prevents the error from showing, so I guess I'll have to write a custom validation for it to really fix it.
Source: OP edit.


How can I remove the title in a specific node?

Question: I am working in Drupal 7.
How can I remove or hidden the title in a specific node (not in the content type of the specific node)?
Answer: You can use  the Automatic Nodetitles module.

"auto_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.

If you want to hide the title for the particular node or content type, then you should use hook_form_alter().
Answer: You can write a specific page template for that node, and remove the title tag from that template.


Searching active directory doesn't pull up the user record when applying a specific filter

Question: DirectoryEntry deEntry = new DirectoryEntry("LDAP://test.com");
DirectorySearcher dsSearcher = new DirectorySearcher(deEntry);
dsSearcher.Filter = "(&(objectclass=user)(objectcategory=person))";

When I apply that filter, the user doesn't show up. But I've checked his attributes and those properties have those values.
But when I add his last name in the filter, he does show up.
dsSearcher.Filter = "(&(objectclass=user)(objectcategory=person)(sn=harper))";

Here is a picture with the deubg info that shows that his attributes are set correctly.

I have no idea what's going on. Any ideas?
Answer: If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement

Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
    // find a user
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "harper");

    if(user != null)
    {
       // do something here....
    }
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!
Comment: Yeah, the app was made in 3.5, but it's a few years old. I'll look into this to see if it can be used. I generally don't want to look for a single user. The app is looping through all of the users. Which I'm sure System.DirectoryServices.AccountManagement can handle that, but I'm not fond of remaking that whole portion for this.
Comment: Decided to just redo that section with this method. Thanks!


Can a polynomial with degree (r+s-1) have (r+s) distinct roots?

Question: While reading about generalised eigenvectors, i came to a strange proof. It goes like
If p is a polynomial which has r distinct roots {λ1,λ2...,λr}, and q is a polynomial with s distinct roots {μ1,μ2...,μs}.
We can have two polynomials a(of degree s-1),b(of degree r-1) such that a(x)=p(x)^-1,when x={μ1,μ2...,μs} and b(x)=q(x)^-1,when x={λ1,λ2...,λr}.
Now a(x).p(x)+b(x).q(x)=1 for x={μ1,μ2...,μs,λ1,λ2...,λr}, all being distinct by definition.
Writing ap+bq-1=0, has r+s roots, while its a polynomial with degree at most (r+s-1). How does it works?
Reference http://math.mit.edu/~dav/generalized.pdf
Comment: It can, but then it will be $\equiv 0$
Comment: Your notation is difficult to read. Please see https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference for formatting tips. I suspect that $ap+bq-1$ is the zero polynomial, which has a lot more than $r+s$ roots!
Comment: A polynomial of degree $n>0$ can have at most $n$ roots.  If $r+s-1=0$ is a possibility then you have the polynomial which is constantly $0$.  But that's the only case in which you have more zeroes than the degree.
Comment: @LordSharktheUnknown i still have to learn tex. Sorry to everyone who had difficulty in reading it. I will make sure i learn it at the earliest. Thanks!
Comment: Click on HELP. Go to the Help Center. Click on "How Do I Format Mathematics Here?. Read that and click on the next link.
Answer: Any nontrivial polynomial of degree at most $r+s-1$ can have at most $r+s-1$ distinct roots. So if $a(x)p(x) + b(x)q(x) - 1$ is equal to $0$ at $r+s$ points, that means it can only be the trivial polynomial which is $0$ everywhere.
Comment: I get it, all i had to prove is that if two polynomial(p,q) have no common irreducible polynomial, there exist two polynomial (a,b) such that pa+qb=1, much like the theorem for co-prime numbers. Thanks!


Add More Text fields

Question: I have a Search Script in my spread sheet that I found on here. I understand most of it but not all. What I want is to add more of the text boxes that show that data. I tried adding the lines below but I get TypeError: Cannot call method "add" of undefined. (line 41)
Line 41 Contains hpanel3.add(label4).add(label5).add(label6).add(label7) Which is just a copy of the above code with different numbers. Script works without these lines.
// G. Variables
var sh = SpreadsheetApp.getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var lastrow = ss.getLastRow();
//
function onOpen() {
  var menuEntries = [ {name: "Search GUI", functionName: "searchUI"},
                     ];
  ss.addMenu("Search Utilities",menuEntries);// custom menu
}
// Build a simple UI to enter search item and show results + activate result's row
function searchUI() {
  var app = UiApp.createApplication().setHeight(200).setWidth(600);
  app.setTitle("Search by anything");
  var panel = app.createVerticalPanel();
  var txtBox = app.createTextBox().setFocus(true);
  var label=app.createLabel(" Item to search for :")
  panel.add(label);
  txtBox.setId("item").setName("item");
//
  var label0=app.createLabel("Row").setWidth("40");
  var label1=app.createLabel("Name").setWidth("120");
  var label2=app.createLabel("ID").setWidth("120");
  var label3=app.createLabel("Street").setWidth("200");
  var hpanel = app.createHorizontalPanel();
  hpanel.add(label0).add(label1).add(label2).add(label3)
//
  var txt0=app.createTextBox().setId("lab0").setName("0").setWidth("40");
  var txt1=app.createTextBox().setId("lab1").setName("txt1").setWidth("120");
  var txt2=app.createTextBox().setId("lab2").setName("txt2").setWidth("120");
  var txt3=app.createTextBox().setId("lab3").setName("txt3").setWidth("250");
  var hpanel2 = app.createHorizontalPanel();
  hpanel2.add(txt0).add(txt1).add(txt2).add(txt3)
//
//
//  var label4=app.createLabel("Phone").setWidth("120");
//  var label5=app.createLabel("Pet Name").setWidth("120");
//  var label6=app.createLabel("Breed").setWidth("120");
//  var label7=app.createLabel("Gender").setWidth("120");
//  var hpanel = app.createHorizontalPanel();
//  hpanel3.add(label4).add(label5).add(label6).add(label7)
////
//  var txt4=app.createTextBox().setId("lab4").setName("txt4").setWidth("40");
//  var txt5=app.createTextBox().setId("lab5").setName("txt5").setWidth("120");
//  var txt6=app.createTextBox().setId("lab6").setName("txt6").setWidth("120");
//  var txt7=app.createTextBox().setId("lab7").setName("txt7").setWidth("250");
//  var hpanel3 = app.createHorizontalPanel();
//  hpanel4.add(txt4).add(txt5).add(txt6).add(txt7)
//
  var hidden = app.createHidden().setName("hidden").setId("hidden");
  var subbtn = app.createButton("next ?").setId("next").setWidth("250");
  var link = app.createAnchor('', '').setId('link');
  panel.add(txtBox);
  panel.add(subbtn);
  panel.add(hidden);
  panel.add(hpanel);
  panel.add(hpanel2);
//  panel.add(hpanel3);
//  panel.add(hpanel4);
  panel.add(link);
  var keyHandler = app.createServerHandler("click");
  txtBox.addKeyUpHandler(keyHandler)
  keyHandler.addCallbackElement(panel);
//
  var submitHandler = app.createServerHandler("next");
  subbtn.addClickHandler(submitHandler);
  submitHandler.addCallbackElement(panel);
//
  app.add(panel);
  ss.show(app);
  }
//
function click(e){
   var row=ss.getActiveRange().getRowIndex();
   var app = UiApp.getActiveApplication();
   var txtBox = app.getElementById("item");
   var subbtn = app.getElementById("next").setText("next ?")
   var txt0=app.getElementById("lab0").setText('--');
   var txt1=app.getElementById("lab1").setText('no match').setStyleAttribute("background", "white");// default value to start with
   var txt2=app.getElementById("lab2").setText('');
   var txt3=app.getElementById("lab3").setText('');
//   var txt4=app.getElementById("lab4").setText('');
//   var txt5=app.getElementById("lab5").setText('');
//   var txt6=app.getElementById("lab6").setText('');
//   var txt7=app.getElementById("lab7").setText('');
   var link=app.getElementById('link').setText('').setHref('')
   var item=e.parameter.item.toLowerCase(); // item to search for
   var hidden=app.getElementById("hidden")
   var data = sh.getRange(3,1,lastrow,18).getValues();// get the 18 columns of data
       for(nn=0;nn<data.length;++nn){ ;// iterate trough
         if(data[nn].toString().toLowerCase().match(item.toString())==item.toString()&&item!=''){;// if a match is found in one of the 18 fields, break the loop and show results
          txt0.setText(nn+3);
          txt1.setText(data[nn][0]).setStyleAttribute("background", "cyan");
          txt2.setText(data[nn][2]);
          txt3.setText(data[nn][4]);
//          txt4.setText(data[nn][5]);
//          txt5.setText(data[nn][6]);
//          txt6.setText(data[nn][7]);
//          txt7.setText(data[nn][8]);
          link.setText(data[nn][0]).setHref(data[nn][0]);
          sh.getRange(nn+3,1).activate();
          subbtn.setText("found '"+item+"' in row "+Number(nn+3)+", next ?");
          hidden.setValue(nn.toString())
          break
          }
      }
return app    ;// update UI
}
function next(e){
   var row=ss.getActiveRange().getRowIndex();
   var app = UiApp.getActiveApplication();
   var txtBox = app.getElementById("item");
   var subbtn = app.getElementById("next").setText("no other match")
   var hidden=app.getElementById("hidden");
   var start=Number(e.parameter.hidden)+1;//returns the last search index stored in the UI
   var item=e.parameter.item.toLowerCase(); // item to search for
   var txt0=app.getElementById("lab0");
   var txt1=app.getElementById("lab1").setStyleAttribute("background", "yellow");
   var txt2=app.getElementById("lab2");
   var txt3=app.getElementById("lab3");
   var link=app.getElementById('link').setText('').setHref('')
   var data = sh.getRange(3,1,lastrow,18).getValues();// get the 18 columns of data
       for(nn=start;nn<data.length;++nn){ ;// iterate trough
         if(data[nn].toString().toLowerCase().match(item.toString())==item.toString()&&item!=''){;// if a match is found in one of the 4 fields, break the loop and show results
          txt0.setText(nn+3);
          txt1.setText(data[nn][0]).setStyleAttribute("background", "cyan");
          txt2.setText(data[nn][2]);
          txt3.setText(data[nn][4]);
          link.setText(data[nn][0]).setHref(data[nn][0])
          sh.getRange(nn+3,1).activate();
          subbtn.setText("found '"+item+"' in row "+Number(nn+3)+", next ?");
          hidden.setValue(nn.toString())
          break
          }
      }
return app    ;// update UI
}

Any Help is greatly apperiated. Like I said, I understand a lot of whats going on but I could never do this from scratch. This is for a Dog License List. I am an Animal Control Officer and when I find a stray Dog my dispatcher will use this to find an owner to the dog doesn't have to go to the shelter.
Comment: hi, I'm the original author of this script, glad to see you use it ;-)  That said, you'll have to update the next() function as well with the new fields... don't forget it or you'll loose the prev/next functionality.
Answer: "Defined" means that a value has been given to a variable in the current scope. If you're watching in the debugger, you'll see all the variables that are "Declared" in scope, even if they have not yet been Defined.
You have the definitions of your various hpanels happening in the wrong order. At Line 41, you haven't yet defined hpanel3. (The error message isn't lying to you!) It appears that you meant to define it in line 40, but instead you redefined hpanel.
Later, line 47 defines hpanel3, but then line 48 tries assigning to hpanel4, which isn't yet defined. This would give the same error.
btw, you don't need to put comments to have blank lines... they can just be blank.
Comment: Hi Mogsdad, You're right about your (very) small comment... As I mentioned in the other comment on this post I wrote this script a while ago and at that time I "hated" to see blank lines (way of speaking ^^)... now I'm getting grown up, I'm not afraid of emptiness anymore ! I suppose I may say I'm a big boy now ;-)

Add More Text fields


How can I search and then replace a code snippet that includes some variables in TextMate?

Question: I have a project that includes 49 folders, each one has a file called index.php
All index.php files are almost the same except for one part that changes depending on the folder it is in.
<?php include_once("/home/bgarch/public_html/galleryheader.html"); ?>
<?php include_once("/home/bgarch/public_html/culture/loadscripts.html"); ?>

    <?php include_once("/home/bgarch/public_html/header.html"); ?>

    <?php include_once("content.html"); ?>

<?php include_once("/home/bgarch/public_html/footer.html"); ?>

In the second line where the above reads: "../culture/.." the word culture is the variable and is different based on the folder it is in.
What I need to do know is do a "Find/Replace all in project" that automatically replaces all the text inside each 'index.php' file with the following"
<?php include_once("http://www.bgarchitect.co.nz/subPage/index.php"); ?>

I have spent the past 2 hours trying to figure out regular expressions to acomplish this but have been unsuccessful so far.
Maybe it is not possible to do so?
Anyway, I thought I'd ask a question here in hopes it is in fact much easier than I anticipated. So any help/pointer/hints or tricks are much appreciated.
Thanks for reading,
Jannis
Answer: If I understood right, you want to replace the word culture (which is the current directory) with the word subPage?
You can do this with the help of TextMate bundles.
Bundles > Bundle editor > Edit commands, than add a New command.
Add this as a command. I think it does what you want. You have to set the input to the command as Entire document and the output to Replace document.
#!/bin/bash

sed "s/"${TM_DIRECTORY##*/}"/theWordYouWanToReplaceTheDirWith/g" | cat

Comment: thanks but i must have not explained it clearly. the word 'culture' is the variable. i need to select each index.php and replace its content with the one line rather than the top most code. a search that includes "culture" will not find the other pages that have a different word instead of culture.
Comment: I just editied my post with what I think is the solution to your problem


CentOS Failover Cluster - SIOCADDRT: No such process (when adding a loopback)

Question: I'm trying to configure two web servers for a load balancing server. The load balancing aspect works fine (it sees both server, kills 'em if it needs to, and seems to direct traffic fine). The only issue is with the servers looping:
/etc/sysconfig/network-scripts/ifcfg-lo:0
DEVICE=lo:0
IPADDR=<Virtual IP>
NETMASK=255.255.255.255
ONBOOT=yes
NAME=loopback

Everytime I try a "service network restart" I get a SIOCADDRT: No such process when loading the loopback interface.
Anyone have an idea what's causing this?
Comment: How many interfaces on the system?  If it's just a primary interface and lo, can you show us the ifcfg-eth0 file, too?  It would be useful if you could include addresses in the file; if they both share the same first two octets, just replace them with "10.10" or something.  The error you're getting often comes from `route`, so it would help to see the complete network configuration.
Comment: Forgot about this question... I resolved it by @larsks's answer, but ended up throwing in the towel when it decided to stop working (after it was working fine for an hour). I appreciate your comments though! Sorry for wasting your time!
Answer: Add NO_ALIASROUTING=yes in your alias config, or in your parent device confg if you don't need routing for any alias. Check your ifup-aliases if it supports NO_ALIASROUTING. If not, setting GATEWAY="" in your alias config could do the trick.
Answer: Note that /usr/share/doc/initscripts-*/sysconfig.txt says that the alias devices should not duplicate the information contained in the parent device.
/etc/sysconfig/network-scripts/ifcfg-<interface-name> and
/etc/sysconfig/network-scripts/ifcfg-<interface-name>:<alias-name>:

  The first defines an interface, and the second contains
  only the parts of the definition that are different in a
  "alias" (or alternative) interface.  For example, the
  network numbers might be different, but everything else
  might be the same, so only the network numbers would be
  in the alias file, but all the device information would
  be in the base ifcfg file.

It also says use ONPARENT instead of ONBOOT:
ONBOOT=yes|no (not valid for alias devices; use ONPARENT)

ONPARENT=yes|no
  Whether to bring up the device when the parent device is brought
  up.
  Default: yes

This makes me think that ONBOOT=yes is incorrect. What happens if you use ONPARENT instead?
DEVICE=lo:0
IPADDR=<Virtual IP>
NETMASK=255.255.255.255
ONBOOT=yes

Update:
Turns out this doesn't really matter. As larsks says, /etc/sysconfig/network-scripts/ifup-aliases only checks for ONPARENT=no:
for FILE in ifcfg-${parent_device}:* ; do
   is_ignored_file "$FILE" && continue
   ini_env;
   . $FILE;
   [ -z "$DEVICE" ] && DEVICE=${FILE##ifcfg-}
   [ "$ONPARENT" != "no" -a "$ONPARENT" != "NO" ] && new_interface;
   unset DEVICE
done

Comment: ONBOOT=yes works just fine for alias interfaces, regardless of the documentation.   In fact, if you look at the `ifup-aliases` script, you'll see that it only checks for `ONPARENT=no`, so not setting it is the same as `ONPARENT=yes`.  Use the source!
Answer:
Everytime I try a "service network restart" I get a SIOCADDRT: No such
  process when loading the loopback interface.

This typically comes from the route command, and means that you're trying to
set up a route via an invalid gateway.  For example, if I have:
# ip addr list
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether b8:ac:6f:a6:bf:a6 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.10/24 brd 192.168.1.255 scope global external

And then I try to add a route to 192.168.3.0 via 192.168.1.1, but accidentally
make a typo and enter the wrong gateway address:
# route add 192.168.3.0/24 gw 192.168.2.1

Then I get this:
SIOCADDRT: No such process

If instead of doing a service network restart, what happens if you just use ifup lo:0? Do you still get the same error?


How to support multiple Consumes MIME Types in ASP.NET Core controller method

Question: I am uploading a file as a stream with a workaround the Stream model binding from this issue, and I want to support consumes for multiple MIME types. I assumed this would work, but it doesn't:
public class FileController : BaseController
{
    [HttpPost("customer/{customerId}/file", Name = "UploadFile")]
    [SwaggerResponse(StatusCodes.Status201Created, typeof(UploadFileResponse))]
    [Consumes("application/octet-stream", new string[] { "application/pdf", "image/jpg", "image/jpeg", "image/png", "image/tiff", "image/tif"})]
    //[Consumes("application/octet-stream", "application/pdf", "image/jpg", "image/jpeg", "image/png", "image/tiff", "image/tif")] // doesn't work either
    public async Task<IActionResult> UploadFile([FromBody] Stream file, [FromRoute] string customerId, [FromQuery] FileQueryParameters queryParameters)
    {
        // file processing here
    }
}

It only supports "application/octet-stream". Any of the others such as "image/jpeg" fail with a 415 Unsupported Media Type.
I am unable to add multiple ConsumeAttributes. The documentation for ConsumeAttribute.ContentTypes states:

Gets or sets the supported request content types. Used to select an
  action when there would otherwise be multiple matches.

I have no idea what that documentation is trying to state, but I had assumed it was a way to support extra MIME types! Is there any way around this in order to support multiple MIME types?
Update
The method signature here is fixed and can't be changed. The ConsumesAttribute is being used to generate a Swagger JSON file which clients use to generate their own multi-platform clients for this API.
Comment: I am wondering if `IFormFile` would work around that,
Comment: This is straight file upload from a http client. We don't want to use IFormFile because it is a absolute pain in the ass for non-browser clients. We just want to stream body and be done with it. MultipartFormDataContent is horrible for simple file uploads. Still the Consumes must be able to support multipel options. I just can't figure out how.
Comment: Can we convert the stream to `IFormFile`, then validating the `ContentType` property?
Comment: I'm using the ConsumesAttribute for Swagger generation (which is shared with clients, and so the interface here is fixed). Without it, the Consumes section isn't generated, and generated Swagger clients don't know which media types to support. Consumes should support multiple options, and the documentation suggests it does, but it doesn't.
Answer: Your Consumes attribute is correct. I tested it with dotnet core 2.1 and it works as expected:
    [HttpPost("test")]
    [Consumes("text/plain", new[] { "text/html" })]
    public void Test()
    {

    }

Sending a post request with Content-Type "text/plain" or "text/html" works while other content types are denied with 415 unsupported media type.
BUT: It stops working if I add [FromBody] Stream file.
 // Does NOT work:
 [Consumes("text/plain", new[] { "text/html" })]
 public void Test([FromBody] Stream file)

Comment: Changing that StreamInputFormatter solved the problem! The 415 for all the other content types was being caused by the line `if (contentType == "application/octet-stream") { return true; }`. Thank you helped me on my way proving that it should work!
Comment: I've tested too. As I noted at the top of my issue, I was working around the stream issue using this workaround: https://stackoverflow.com/questions/41346128/model-binding-not-working-with-stream-type-parameter-in-asp-net-core-webapi-cont The issue lies in there. In the CanRead method! Problem solved by adding my extra mime types into that method. No more 415's!
Comment: Is there any problem with var stream = Request.Body; ?
Comment: Cool - and I fear I have to read about StreamInputFormatter ;-)


Termo inicial de final da sequencia de fibonacci (intervalo fechado)

Question: Tenho que fazer uma lista de exercícios em C e Java, mas não consegui entender a lógica nesse exercício. Alguém poderia ajuda?
Solicite ao usuário o termo inicial e o termo final da sequencia de Fibonacci
(intervalo fechado) e imprima o resultado.
Ex:
    Sequencia de Finomacci → 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …
Termo inicial → 4
Termo final → 8
Comment: Esta pergunta parece ser descontextualizada porque pede para resolver o exercício completo sem demonstrar suas tentativas, sem mostrar código próprio e sem dizer o que não entende sobre o problema de programação em si.
Answer: A sequencia de Fibonacci e definida da seguinte maneira:
F(1) = 0
F(2) = 1
F(n) = F(n-1) + F(n-2), se n > 2

Ou seja, a sequencia comeca com os termos 0 e 1 e a partir dai os proximos termos sao a soma dos dois anteriores. Por exemplo:
F(4) = F(3) + F(2) = 1 + 1 = 2

O seu exercicio pede que o usuario entre dois parametros, inicio e fim. O que voce tem que imprimir sao os numeros F(n) para n entre os numeros inicio e fim. Por exemplo,se inicio = 4 e fim = 8, como no seu exemplo, voce tem que imprimir F(4), F(5), F(6), F(7), F(8).
Comment: Eu sei fazer a sequencia. Já fiz outros exercicios, mas não entendi como fazer esse aí. Porque vai imprimir a partir do 4º termo e terminar no 8º termo seguindo o exemplo.
Ele não vai mostrar o 0, 1, 1 .
Comment: Se voce sabe gerar a sequencia, e so colocar a impressao dentro de um `if`. Se o valor do termo esta dentro do intervalo imprima ele, caso contrario nao :)
Comment: quando chegar da faculdade tento de novo. tenho 3 listas pra fazer de C e Java. ainda bem que de C já estou terminando kk
mas valeu ae ^^


Codec registration with event bus on vert.x

Question: Message codec example for vert.x event bus.
I have a use case where I want to register my custom object to send it on the event bus.For that,I have to implement Message codec class .I would like to know if more than one object can be registered under the same name with event bus?If not,what is the correct way of registering multiple custom objects as codec.
Comment: `MessageCodec` has a signature of ``. Do you have two or more `Source` classes that map to the same `Target` class?
Comment: Also, are you using Vert.x in clustered mode?
Comment: I am not using Vert.x in clustered mode.The source classes don't map to same target class.There are a few consumers that consume message of  different object types.
Answer: If you're not using clustered EventBus, then you can just implement every codec like this:
<code>class IdentityCodec implements MessageCodec {
    private final Class aClass;

    public IdentityCodec(Class aClass) {
        this.aClass = aClass;
    }

    @Override
    public void encodeToWire(Buffer buffer, Object o) {

    }

    @Override
    public Object decodeFromWire(int pos, Buffer buffer) {
        return null;
    }

    @Override
    public Object transform(Object o) {
        return o;
    }

    @Override
    public String name() {
        return aClass.getName() + "Codec";
    }

    @Override
    public byte systemCodecID() {
        return -1;
    }
}
</code>
The important part here is that every codec must have a unique name, so I'm generating it based on the class name.
Then register it as a default codec:
<code>    vertx.eventBus().registerDefaultCodec(A.class, new IdentityCodec(A.class));
    vertx.eventBus().registerDefaultCodec(B.class, new IdentityCodec(B.class));
</code>
Probably there are nicer ways to generify it, but without seeing your code, it's impossible to tell.
Comment: If there was only a way to indicate if this answer was correct or not :)
Comment: While this works perfectly, it's worth mentioning that using it to send mutable objects over the event bus is probably not a good idea...


How to use my own video and be able to play from a specific time?

Question: I have Drupal 7 with the video module installed using ffmpeg. The video is playing fine. However, I noticed that users can only play from the beginning of the video. I would like to have users play from any specific time.
The embed video field module is only for embedding other videos so does not suit my needs.
Answer: May be you can try with javascript
document.getElementById('YOURVIDEOID').addEventListener('loadedmetadata', function() {
  this.currentTime = 50;
}, false);

In jquery
var vid = $("#video")[0];
$("#button").click(function(){
    skipTime(100);
});

function skipTime(time) {
    vid.play();
    vid.pause();
    vid.currentTime = time;
    vid.play();
};

Comment: How do I add listener to the clicked event and get the selected time from my video?


Instaling apk via maven

Question: I'm wondering how can i add an .apk file to my pom.xml for, in order, install app from apk file and in second step build project with tests, lunch emulator, install apk which will be testing etc,etc. For now first apk is installed manually but i need install that apk whit maven and then go to second step. Has anyone else run into the same problem?
Answer: Ok i solved it on my own, this is a part of pom.xml
<code><executions>
  <execution>
   <id>startEmulator</id>
       <phase>initialize</phase>
       <goals>
         <goal>emulator-start</goal>
       </goals>
   </execution>
   <execution>
   <id>install-client</id>
       <phase>initialize</phase>
       <configuration>
          <file>my.apk</file>
       </configuration>
       <goals>
          <goal>deploy</goal>
       </goals>
   </execution>
</executions>
</code>

Instaling apk via maven


Regaining piano skills after leaving it for years

Question: I used to play the piano for about 1 year and a half, from when I was in year 4 to mid year 5. I got up to grade 5 AMEB and was preparing for grade 6 before I decided to quit. I would practice for around an hour everyday, making it 7 hours a week with 1 hour piano lessons. I also used to do scales and arpeggios.
However, after a while I started to really hate playing the piano. I felt so stressed everyday, knowing that my mum would make me practice the piano for an hour. If I forgot to play it one day, she would make me do an extra hour the next day to make up for the previous day. At that time, she didn't know that that was actually quite harsh for a 10 year old to do, until my little sisters started to learn piano too and their teacher told my mum that it was in fact quite harsh.
Now I'm in year 9 and I'm 14 years old. It's been almost 5 years since I've left the piano and I haven't touched it since but I really want to start again. I asked my mum if I could get lessons again but she said that it's too expensive and that it isn't worth paying for since I'm only learning piano as a hobby and it's already been 5 years since I left it. How long would it take me to regain my skills? and how can I persuade my parents to let me take lessons again?
Comment: I'd say within 3 months if you practise seriously.
Answer: It's great that you want to resume playing again. Just get on with it, quietly, by yourself, and at some point your parents will be thinking it's a good idea to finance lessons again. Or part-finance. You could do small jobs around the house, or for neighbours, if you explain to them why you need the money.Parents have so many drains on resources, they have to be careful the money goes in the right direction, but unfortunately you already gave them the idea that it was not good to spend on your lessons. Pick up from where you were - a good level already - and show them, subtly, that you are capable of doing the necessary practice, without being showy. Just find a good time each day. They may well re-consider after a while, when they hear how your playing is improving just on your own. If the next lot of exams are your goal, that's fine - parents like that sort of thing.
Answer: I'm older than you, but I also recently got back into my piano playing.  I'm teaching myself by looking at my old books and playing through them. I don't have time for a teacher unfortunately so I have to do it all on my own.  I've found that what makes me most interested in playing again is watching myself make progress. I chose pieces that I've always wanted to learn, and just got started working them out. I also made sure that I would play at least 30 minutes per day, and that helped me a lot to stick to my own self teaching.
I'm finding that I'm enjoying piano more now than ever since I'm in charge. I know that I could get better faster with a teacher, but that's not really an option so I'm enjoying just playing for fun.
I think you should try to find some sheet music online that you like, and just start practising.  If it's too hard, ask here for simpler pieces that can help you get better a the hard ones.


Pegar o menor valor e o maior valor de um array com JavaScript?

Question: Como faço para pegar o menor valor e o maior valor do array separadamente com JavaScript e jQuery?

var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];

O menor valor nesse caso e 444.9 e o maior 984.9.
Comment: Possível duplicata de [Como saber o maior valor de um Array?](https://pt.stackoverflow.com/questions/35202/como-saber-o-maior-valor-de-um-array)
Answer: A maneira mais simples seria assim:

var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
var min = Math.min(...arr);
var max = Math.max(...arr);

console.log(min); // 444.9
console.log(max); // 984.9

As maneira mais "convencional" seria combinar o .reduce() com o Math.max|Math.min.
Juntei também um .map(Number) porque tens strings e é melhor trabalhar com números (ainda que funcionasse sem isso).
O Math.max e o Math.min aceitam dois (ou mais) argumentos, e retornam o maior/menor. O .reduce() passa o valor anterior e o novo, o que encaixa perfeito.
Para saber o máximo usando .reduce():

var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
var max = arr.map(Number).reduce(function(a, b) {
  return Math.max(a, b);
});

console.log(max); // 984.9

Para saber o mínimo usando .reduce():

var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
var min = arr.map(Number).reduce(function(a, b) {
  return Math.min(a, b);
});

console.log(min); // 444.9
Comment: resposta rápida e pratica...
Answer: Aconselho a utilizar a biblioteca Lodash. A lib é extramente pequena e tem diversos outros recursos muito úteis.
Seria apenas este código abaixo:

var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
console.log(_.min(arr)); //444.9
console.log(_.max(arr)); //984.9

Answer: Terá que converter as strings em números antes de fazer as comparações:

var arr = ["885.9", "984.9", "444.9", "528.9", "528.9"];
var maior = Number.NEGATIVE_INFINITY,
    menor = Infinity;

arr.forEach(function(item){
  if (Number(item) > maior) maior = item;
  if (Number(item) < menor) menor = item;
});

console.log(maior, menor)
Answer: Podes usar o Math.Max() e o Math.Min() para pegar os valores, como é algo relativamente simples vou apenas apontar os links e deixar você estudar =]
Esse também
Comment: Agradecemos sua vontade de colaborar com a comunidade, mas talvez seja interessante ler o texto [Queremos respostas que contenham somente links?](https://pt.meta.stackoverflow.com/q/42/5878) O principal problema é que, se porventura, o link da resposta deixar de existir, a resposta perde o sentido por completo. Para contornar isso, verifique junto ao conteúdo do link os principais pontos que sejam válidos à pergunta e descreve-os aqui, mantendo o link apenas como um material de apoio.


Solving Second Order Non-Homogeneous ODE

Question: I haven't solved an ODE in quite some time and I'm finding myself a bit rusty! If someone could help me solve the following ODE that would be great:
$$\frac{d^2x}{dt^2} + \frac{1}{c_1} \frac{dx}{dt} = c_2$$
I attempted using the method of undetermined coefficients and found the complementary solution as follows:
$$r^2 + \frac{1}{c_1}r = 0 \implies r = 0 \text{ or } r = -\frac{1}{c_1} \implies x_C(t) = A + Be^{-\frac{1}{c_1}t} \text{ , } A,B \in \Bbb{R}$$
From there I attempted to find the particular solution with a guess of $x(t)= C \in \Bbb{R}$ which would have resulted in $c_2 = 0$ which I don't believe to be right.
Any help would be great!
Comment: $c_1 c_2 t$ is a particular solution.
Answer: $$
x_h(t)=A+B\mathrm{e}^{-t/c_1}
$$
is the general solution of the homogeneous equation
$$
x''+c_1x'=0.
$$
In order to find the general solution of the inhomogeneous one
$$
x''+c_1x'=c_2, \tag{1}
$$
you need first to find a particular solution of it. One such is
$$
x_p(t)=(c_2/c_1)t.
$$
Then the general solution of (1) is
$$
x(t)=x_h(t)+x_p(t)=A+B\mathrm{e}^{-t/c_1}+(c_2/c_1)t.
$$
Note. In general, if $x_h=c_1\varphi_1+\cdots+c_n\varphi_n$ is the general solution of
$$
x^{(n)}+a_{n-1}(t)x^{(n-1)}+\cdots+a_0(t)x^{(0)}=0,
$$
and $x_p$ is a particular solution of
$$
x^{(n)}+a_{n-1}(t)x^{(n-1)}+\cdots+a_0(t)x^{(0)}=h(t), \tag{2},
$$
then $x=x_h+x_p$ is the general solution of (2).
Answer: $$\frac{d^2x}{dt^2} + \frac{1}{c_1} \frac{dx}{dt} = c_2$$
For the particular solution try:
$$x_p'=A \implies A=c_2c_1$$
$$ \implies x_p=c_1c_2t+K$$
You can choose $K=0$. Note that you can integrate directly the DE:
$$\frac{d^2x}{dt^2} + \frac{1}{c_1} \frac{dx}{dt} = c_2$$
$$\frac{dx}{dt} + \frac{1}{c_1} x(t) = c_2t+K$$
Then it's just a first order differential equation that is easy to solve.


Gallery won't center to page

Question: I am trying to center my gallery array. I tried:

margin-left:auto; margin-right:auto
and
margin:0 auto;
and
-text-align:center;

and have had no luck?
Here is the link
Any help is greatly appreciated!
Thanks.
Comment: It looks centered to me. Tried it in FF, IE and Chrome. Or am I just not looking at the right thing?
Answer: This is your problem:
#content ul {
padding: 0 0 16px 30px;
}

It is center aligned, but you've got left padding on the ul (30px)
Changing this to 0px will center align the gallery:
#content ul {
    padding: 0 0 16px 0;
}

I'm not sure what implications this will have on other elements, so perhaps create a second class just for the gallery:
#content ul.gallery {
    padding-left:0;
}

Gallery won't center to page


How to figure out the "idea behind" proofs in analysis?

Question: I'm taking a course in Real Analysis, and for the most part I can follow the rote mechanics of a proof (e.g. manipulation to produce a chain of inequalities as desired, etc.), but I have difficulty figuring out the motivation for a lot of these or what the inequalities actually mean.
For example, I'm currently in Chapter 8 of Rudin, and have been trying to follow Theorem 8.2 for a while. I finally wrote out all of the steps in detail and I see how it all links up algebraically, but I'm not sure what any of it really means. Are the intermediate steps really just means to an end to get to an inequality you want?
Another example is that it took me about two quarters to realize that continuity intuitively could mean a function is almost constant in a small neighborhood. Insights like this help a lot, but I have difficulty following them.
How does one arrive at the "idea" of a proof?
Apologies if this is too vague of a question.
Comment: Can you tell us what theorem 8.2 is?
Comment: Forget the proof in the book and instead spend some time trying to prove it yourself. If you find your mind blank, try some of the strategies discussed in Polya's book "How to solve it". Then after a while of trying on your own, your mind will be more ready to absorb the proof in the book.
Comment: @NoahSchweber Suppose $\sum c_n$ converges. Put $$f(x)=\sum_{n=0}^\infty c_nx^n\qquad(-1<x<1).$$ Then $$\lim_{x\to 1}f(x)=\sum_{n=0}^\infty c_n.$$
Comment: Of course, though I just used it as an illustrating example. Theorem 8.2: Suppose $\sum c_n$ converges. Put $f(x) = \sum_{n=0}^{\infty} c_n x^n$ for $-1 < x < 1$. Then $\lim_{x \rightarrow 1} f(x) = \sum c_n$. It has to do with the continuity of a function at the endpoint of its interval of convergence.
Comment: In the ancient copy of Baby Rudin I have before me, theorem 8.2 says this: Suppose $\sum c_n$ converges.  Put $$ f(x) = \sum_{n=0}^\infty c_n x^n \qquad (-1<x<1). $$ Then $$ \lim_{x\to1} f(x) = \sum_{n=0}^\infty c_n. $$ However, it is possible that later editions have something else there. $\qquad$
Comment: Sometimes it's good to examine a proof backwards, to see how intermediate  results were used, which can sometimes give you an understanding of the motivations for the intermediate results.
Comment: A wholly personal view:  You study analysis, not in order to reverse engineer or memorize others' proofs, but to create your own.  When you've done enough proofs of your own (as solutions to exercises), some of the proofs in your textbook, the simpler ones, can be seen to have "ideas" like the "ideas" that let you get to the ones you devised.  Others will still leave you asking, how did the authors think of doing that?
Comment: It can help to look at different sources.  Rudin doesn't always bother to explain the intuition, even when good intuition is available.  Also you can try to identify tricks that are used repeatedly in analysis proofs.  Tao has listed some of these tricks in books and on his blog.  For example, [give yourself an epsilon of room](https://terrytao.wordpress.com/2009/02/28/tricks-wiki-give-yourself-an-epsilon-of-room/).  Also: great mathematicians worked obsessively to figure some of this stuff out; if it were easy to see how one might think of it, it wouldn't have been so hard to discover.
Answer: The real problem which many students face in "real-analysis" is that they fail to comprehend the inequalities involved. It is important to leave the algebraic manipulation of $+, -, \times, /$ and really appreciate the power of $<, >$.
Consider this simple theorem: if $f$ is continuous at $a$ and $f(a) \neq 0$ then $f$ has same sign as that of $f(a)$ in a certain neighborhood of $a$. The proof is simple: since $f$ is continuous at $a$ we can ensure that all of its values are close to $f(a)$ and if we get too close to $f(a)$ the sign of these values will be same as that of $f(a)$.
This proof is as rigorous as a proof can be and it is not the product of symbol shunting but based on the understanding of inequalities. The basic fact of inequalities which we have used here is that if $A > 0$ then all numbers very near to $A$ are also positive (similar result if $A < 0$). More formally there is a neighborhood of $A$ which consists of positive numbers only. This fact is too obvious to state explicitly and yet the very simple theorem mentioned in last paragraph does not appear to be that obvious.
I think the reason behind the problem of "comprehending inequalities" is the extreme focus on algebraic manipulation in high school curriculum.
BTW not all theorems in real-analysis are as simple as the one I mentioned earlier. Some are complicated but the fundamental theorems are almost always that simple. Another point apart from inequalities is the concept of a real number. Any student who wishes to grasp the proofs in analysis must have a clear idea of
1) how real numbers are different from rational numbers and
2) how real numbers can be defined in terms of rational numbers (similar to the fact that how rationals are defined in terms of integers)
Both these facts are totally non-algebraic in nature and it requires some serious study of real numbers. And also the algebraic notion of symbol manipulation has to thrown away for a while to make room for appreciation of order relations.
Coming back to the proof of theorem 8.2 in Rudin, you need to learn one technicality of many analysis proofs. Most of the problems in analysis boil down to showing that $|A - B| < \epsilon$ where $\epsilon$ is a given positive number, $A$ and $B$ are quantities which depend on certain variables. In many cases the difference $A - B$ needs to be split into multiple parts and we show each part to be less than $\epsilon / n$ where $n$ is number of parts into which $A - B$ has been split. The strategy to show that each part is less than $\epsilon / n$ is different for each part and this requires a bit of study of some common proofs and a little thinking on part of the student.


How to create mysql database backup using one file php script (system() is disabled)

Question: How to create a mysql database backup using one file php script?
system() is disabled.
I have no cpanel account details, from site admin panel I just can read and write php files.
Answer: I hope it help you
<code><?php
$DBUSER="";
$DBPASSWD="";
$DATABASE="";
$filename = "backup-" . date("d-m-Y") . ".sql.gz";
$mime = "application/x-gzip";

header( "Content-Type: " . $mime );
header( 'Content-Disposition: attachment; filename="' . $filename . '"' );

$cmd = "mysqldump -u $DBUSER --password=$DBPASSWD $DATABASE | gzip --best";
passthru( $cmd );
echo ('Proc is OK !');
exit(0);
?>
</code>
Comment: This helps!Thank you very much!


how to insert data in mysql( wamp) database through php?

Question: I have tried many times, connection is successful, but I can not insert the data please help me.
Following is my code, I have just added an if check, to see if the query does't adds any data to the database then it should give some kind of indication so its saying unable to post. When I see in database table from wamp database, no data is inserted or added to the table, please help me it will be much appreciated. thanks.
    <?php
    if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['semester']) && isset($_POST['section'])):
    $post_id = $_POST['id'];
    $post_name = $_POST['name'];
    $post_semester = $_POST['semester'];
    $post_section = $_POST['section'];

    $link = new mysqli('localhost','root','','registration');

    if($link->connect_error)
        die('connection error: '.$link->connect_error);

    $sql = "INSERT INTO student_info(student_id, student_name, semester, section) VALUES('".$post_id."', '".$post_name."', '".$post_semester."', '".$post_section."',)";

    //echo $sql;

    $result = $link->query($sql);

    if($result > 0):
        echo 'Successfully posted';
    else:
        echo 'Unable to post';
    endif;

    $link->close();
    die();
    endif;
    ?>
    <!DOCTYPE html>

Student Registration

      <form action="add.php" method="post">
        Student ID : <input type="text" name="id"/>

        Student Name : <input type="text" name="name"/>

        Semester : <input type="text" name="semester"/>

        Section : <input type="text" name="section"/>

        <input type="submit" value="create"/>
      </form>

Comment: insert echo $link->error; after the unable to post line and share the error message with us. Are you sure that the id field is to be populated manually?
Comment: The whole purpose of deprecating mysql and asking people to use mysqli is to avoid this kind of query: "INSERT INTO student_info(student_id, student_name, semester, section) VALUES('".$post_id."', '".$post_name."', '".$post_semester."', '".$post_section."',)";
Answer: There is an extra comma (,) in your SQL at the end. The correct one would be -
$sql = "INSERT INTO student_info(student_id, student_name, semester, section) VALUES('".$post_id."', '".$post_name."', '".$post_semester."', '".$post_section."')";

I was also able to see error 'Unable to Post' with your current code so that is working fine.
Answer: Try;
<?php
if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['semester']) && isset($_POST['section'])){
$post_id = $_POST['id'];
$post_name = $_POST['name'];
$post_semester = $_POST['semester'];
$post_section = $_POST['section'];

$link = new mysqli('localhost','root','','registration');

if($link->connect_error)
    die('connection error: '.$link->connect_error);

$sql = "INSERT INTO student_info(student_id, student_name, semester, section) VALUES('$post_id', '$post_name', '$post_semester', '$post_section')";

//echo $sql;

$result = $link->query($sql);

if($result){
    echo 'Successfully posted';
}else{
    echo 'Unable to post';
}

$link->close();
die();

}
?>

Comment: Even though your answer is correct, but however an answer is not just an answer by a code, you should also explain why he's code did not work, and why is yours working.


Let the matrix $A=[a_{ij}]_{n×n}$ be defined by $a_{ij}=\gcd(i,j )$. How prove that $A$ is invertible, and compute $\det(A)$?

Question: Let $A=[a_{ij}]_{n×n}$ be the matrix defined by letting $a_{ij}$ be the rational number such that $$a_{ij}=\gcd(i,j ).$$ How prove that $A$ is invertible, and compute $\det(A)$? thanks in advance
Answer: There is a general trick that applies to this case.
Assume a matrix $A=(a_{i,j})$ is such that there exists a function $\psi$ such that
$$
a_{i,j}=\sum_{k|i,k|j}\psi(k)
$$
for all $i,j$.
Then
$$
\det A=\psi(1)\psi(2)\cdots\psi(n).
$$
To see this, consider the matrix $B=(b_{i,j})$ such that $b_{i,j}=1$ if $i|j$ and $b_{i,j}=0$ otherwise. Note that $B$ is upper-triangular with ones on the diagonal, so its determinant is $1$.
Now let $C$ be the diagonal matrix whose diagonal is $(\psi(1),\ldots,\psi(n))$.
A matrix product computation shows that
$$
A=B^tCB\quad\mbox{hence}\quad \det A=(\det B)^2\det C=\psi(1)\cdots\psi(n).
$$
Now going back to your question.
Consider Euler's totient function $\phi$.
It is well-known that
$$
m=\sum_{k|m}\phi(k)
$$
so
$$
a_{i,j}=gcd(i,j)=\sum_{k|gcd(i,j)}\phi(k)=\sum_{k|i,k|j}\phi(k).
$$
Applying the general result above, we find:
$$
\det A=\phi(1)\phi(2)\cdots\phi(n).
$$
Comment: hi  your approach is so nice thanks
Comment: @MaisamHedyelloo Thanks. I've always liked this exercise.
Comment: I'll just add that the identity $m=\sum_{k|m}\phi(k)$ is proved [here](https://math.stackexchange.com/questions/194705/is-there-a-direct-elementary-proof-of-n-sum-kn-phik).
Answer: This is a nice result. We have
 $$ \det(A)= \phi(1)\phi(2)\dots\phi(n), $$
where $\phi$ is Euler's phi function, $\phi(n)$ being the number of positive integers $i\le n$ that are relatively prime with $n$. It satisfies
 $$ \sum_{j\mid n}\phi(j)=n, $$
which we use below.
Let's write $a_n$ for the determinant of the $n\times n$ version of $A$. The sequence $a_1,a_2,a_3,\dots$ begins $$ 1, 1, 2, 4, 16, 32, 192, \dots $$
which OEIS catalogs as $A001088$.
A cute short proof that only uses basic linear algebra (LDU decomposition) appears in a recent note,

Warren P. Johnson. An $LDU$ Factorization in Elementary Number Theory, Math. Mag. 76 (5), (2003), 392–394. MR1573717.

What one shows is that
 $$ A=L\Phi L^T $$ where $L$ is the $n\times n$ matrix whose $i,j$ entry
is $1$ if $j$ divides $i$, and is $0$ otherwise, and $\Phi$ is the diagonal matrix whose $i,i$ entry is $\phi(n)$. Note that $L$ is lower diagonal, with $1$s as entries along its main diagonal, so $\det(L)=\det(L^T)=1$, and the result follows once we prove that $A=L\Phi L^T$, as claimed. Johnson calls this Le Paige's result, who established it to compute $\det(A)$ (originally found by H. J. S. Smith around 1875, according to the references at the OEIS site).
To prove Le Paige's result, simply expand $L\Phi L^T$, and note that its $i,j$ entry is
 $$ \sum_{k=1}^n L_{ik}\Phi_{kk}(L^T)_{kj}=\sum_{k=1}^n L_{ik}\phi(k) L_{jk}=\sum_{k\mid i,k\mid j}\phi(k) =\sum_{k|{\rm gcd}(i,j)} \phi(k)={\rm gcd}(i,j)=A_{ij}, $$
where I use $B_{ij}$ to denote the $i,j$ entry of the matrix $B$.
Comment: I see this argument is the same as julien's. It is a cute example, I will have to use it in my linear algebra class.
Answer: Let $F\colon \{1, \ldots, n\}\to \mathbb{R}$ be a function.  The $n\times n$ matrix $A=(a_{ij}) = (F(\gcd(i.j)))$ is symmetric. It it possible to give its Cholesky decomposition. Indeed, let $g\colon \{ 1, \ldots, n\}\to \mathbb{R}$ such that
$$F(m) = \sum_{d \mid m} G(d)$$
The function $g$ is uniquely determined by the equation
$$G(m) = \sum_{d\mid m} \mu(d) F(\frac{m}{d})$$F
where $\mu$ is the Mobius function. We have
$$F(\gcd(i.j)) = \sum_{d=1}^n u_{d i} u_{d j}\, G(d)$$
where $u_{d i} = 1$ if $d\mid i$ and $0$ otherwise.
We see that we have the equality
$$A = U^t \cdot D \cdot U$$
where $U$ is the upper triangular matrix $(u_{ij})$, and $D$ is the diagonal matrix $(G(1), \ldots, G(n))$.
We conclude that $\det A= G(1) \cdots G(n)$.
Note: if $F(m) = m^{\alpha}$, with $\alpha > 0$, then $G(m)$ is always positive ( easy to see using the Mobius inversion formula). We conclude that all the Hadamard positive powers of the matrix $A$ are positive definite, with determinants that can be calculated explicitly.
This method works for other partial orders on the set $\{1, \ldots, n\}$, in particular the standard order. The bordered determinants are therefore easy to calculate.


Ideals generated and their inclusions

Question: Let $R=2\mathbb{Z}$, then $R$ is a ring without identity, and we consider the ideal generated by $4$, that is $$(4)=\{4(2j)+4\overline{k}\;|\;j,\overline{k}\in\mathbb{Z}\}.$$
I must prove that $(4)=4\mathbb{Z}$. Now, I proved that $(4)\subseteq4\mathbb{Z}$, in fact, let $x\in(4)$, then $x=4(2j)+4\overline{k}=4(2j+\overline{k})\in 4\mathbb{Z}$.
Can I prove that $4\mathbb{Z}\subseteq (4)$? Thanks!
Answer: Let $x$ be a multiple of $4$, so $x=4k$, with integer $k$. Then
$$x=4k=4(2\cdot0)+4k\in(4)$$

Ideals generated and their inclusions


Associating Custom LDAP Query with View

Question: Versions:
->Drupal 7.10
->LDAP Authentication/Authorization/Servers/Query/Views 7.x-1.0-beta5
->Views/Views UI 7.x-3.3

I'm attempting to configure a View via the Views UI module to support a custom LDAP query defined in the LDAP Query module. The example they provide depends on the existence of a query with the machine name of "ad_users", and does function when I define a query with that name, but there doesn't seem to be a way to alter this or point a view toward an arbitrary query.
I'm wondering if I'm overlooking something. It seems illogical that the Views plugin wouldn't let one point a View toward an arbitrary LDAP Query. The question is how to do this?
Answer: In the Advanced section of the view, click on Query Settings and choose your own LDAP Query from the select list that appears.
Comment: explain in detail.
Answer: Assuming that you have a successful connection to an LDAP server and you have added an LDAP Query to build your view on.
Just like cafuego said first make sure to select the LDAP  Query to use for the view in the view settings dialog.
Within the view add an "LDAP Query: LDAP Attribute" field and select the attribute to add from the LDAP Query Attribute Dialog.
If you are have issues then try changing the Query Settings and saving the view again. I had to do this in order for my view to start pulling correctly.

Associating Custom LDAP Query with View


Equality $f(T) = U^{*}f(S)U$ for continuous functions on operators

Question: Suppose $\mathscr{H}_{1}, \mathscr{H}_{2}$ are both Hilbert spaces, $T: \mathscr{H}_{1} \to \mathscr{H}_{1}$ and $S: \mathscr{H}_{2} \to \mathscr{H}_{2}$ are both linear self-adjoint (possibly unbounded). Suppose there is a unitary map $U: \mathscr{H}_{1} \to \mathscr{H}_{2}$ such that $T = U^{*}SU$, that is, $T$ is unitarily equivalent to $S$. My question is: given a continuous function $f: \mathbb{R} \to \mathbb{C}$, does it follow that $f(T) = U^{*}f(S)U$? I know this result holds for bounded Borel measurable functions, but I don't know about continuous functions.
This seems just an easy application of the functional calculus, but I am not sure. For instance, if $f$ is continuous then it is measurable and one can approximate it by simple functions, which are bounded and measurable. Let $\{f_{n}\}_{n\in \mathbb{N}}$ be such simple functions, such that $f_{n} \to f$, with $f$ continuous. Then, by the functional calculus $f_{n}(T) \to f(T)$, $f_{n}(S) \to f(S)$ and, because $f_{n}(T) = U^{*}f_{n}(S)U$, we get $f(T) = f(S)$. Is my argument correct?
Comment: This looks like a simple corollary of spectral theorem.
Answer: Let $E$ be the spectral measure of $T$ and $F$ the spectral measure of $S$. Then we have $E(A) = U^* F(A) U$ for any measurable $A\subset \mathbb{R}$.
This is because for any $x$ in the domain of $T$ and $y \in \mathcal{H}_1$:
$$
\int \lambda d \langle U^* F(\lambda) U x ,y \rangle = \int \lambda  d \langle F(\lambda) Ux, Uy \rangle = \langle SU x , Uy \rangle = \langle U^* SU x , y \rangle = \langle Tx, y\rangle = \int \lambda  d \langle E(\lambda) x ,y \rangle  .
$$
The assertion follows since the above uniquely specifies the spectral measure.


JOIN works on two tables individually, but not when used together

Question: Edit: nevermind, figured it out, answer below if you're interested.
Using Postgresql 8.4.
Here's the format of the query I need to run (names and faces have been changed to protect my paranoia.  they can be provided if necessary, but this is a direct copy of my query with simple substitution for schema, table and column names):
SELECT
    t1.field,
    SUM(v3.quantity) as current_qty
FROM
    schema1.child_table t1
        JOIN (SELECT DISTINCT t1key FROM schema2.child_transaction t2 WHERE datefield BETWEEN '2012-04-01' AND '2012-04-19') t2 USING (t1key)
        LEFT JOIN schema1.child_current_status v3 ON t1.t1key = v3.t1key
        JOIN schema1.parent_table t4 ON t1.t4key = t4.t4key
WHERE
    t4.criteria = 763
GROUP BY
    t1.field

... basically, I need the field from child_table when criteria matches my provided data in parent_table, and when there is at least one relevant transaction in child_transaction during the requested period.  If there are quantities in the child_current_status view, we want those as well.
t1.field can be considered a human readable equivalent to numeric key t4.criteria.
My problem is that the query as provided fails to provide quantity data from child_current_status even when there is data there.
Edit: to clarify, the above query returns field, NULL, where it should return field, current_qty
The problem is related to the t2 subquery, because when I change that to a LEFT JOIN, it returns the relevant quantity data:
SELECT
    t1.field,
    SUM(v3.quantity) as current_qty
FROM
    schema1.child_table t1
        LEFT JOIN (SELECT DISTINCT t1key FROM schema2.child_transaction t2 WHERE datefield BETWEEN '2012-04-01' AND '2012-04-19') t2 USING (t1key)
        LEFT JOIN schema1.child_current_status v3 ON t1.t1key = v3.t1key
        JOIN schema1.parent_table t4 ON t1.t4key = t4.t4key
WHERE
    t4.criteria = 763
GROUP BY
    t1.field

Edit: this modified query returns field, current_qty, but will do so whether there are transactions in child_transaction for the requested time period or not
... all I've done is turn the first JOIN into a LEFT JOIN, and that query returns with the relevant quantities in child_current_status.  If I change the child_current_status to an INNER JOIN, the query returns nothing.  The problem with making the first JOIN a LEFT JOIN is that I need it to only return results when there is data returned from the sub query, which there is in this case for the requested time period.
To muddy the waters, it works properly for some t4.criteria, 763 is just one that it fails on.
What am I missing here?

Short version: From the first query above, when the first JOIN is an INNER JOIN, it causes the LEFT JOIN to return nothing.  When it's a LEFT JOIN, the LEFT JOIN on child_current_status returns the proper data, but that negates the purpose of the first JOIN.
Edit: I've tried moving the LEFT JOIN to the end of the FROM clause, behind the INNER JOINs, with no change
Answer: Ugh, nevermind, I figured it out, the query is working properly and there's not enough data here for anyone else here to figure it out.  Basically, there is one transaction for one child in the child_table, and there are current quantities for other children in the child_table.  So the query appropriately indicates that there are no current quantities for any children for which there was a transaction during the specified time for the specified parent.
The problem came up because in processing the result of this query, I went back and asked for current data relating to all children (rather than just the ones with relevant transactions, like I should have), and got information even when this query (correctly) told me there was none.
Nothing to see here, move along.
Comment: Perhaps you should tick your answer as accepted in order for people not to stumble over the question only to find out there's nothing to see here.
Comment: Ah, I see, sorry. I knew there was some time limitation, just wasn't aware the wait period was that long.


Diferença entre instanciar classe e using

Question: Consigo instanciar uma classe de duas maneiras no C#, sendo elas:
HttpClient http = new HttpClient();

ou
using (var http = new HttpClient())
{
    //
}

Existe alguma diferença entre esses meios? Performance? Boa prática?
Comment: Você somente pode usar `using` em classes descartáveis.
Answer: A pergunta em si não faz tanto sentido porque em ambas está instanciando uma classe, exatamente da mesma forma a não ser pelo fato que uma delas está usando um var que poderia ter usado nos dois lugares.
A diferença é o using. Com ele você garante que o objeto chamará um método de encerramento da operação no final do bloco, aconteça o que acontecer, pode até ser quando dá um erro e gera uma exceção. Quando não faz isto tem que cuidar desse problema manualmente, o que é errado e muitas vezes quase impossível, mesmo sendo possível quase ninguém sabe fazer certo.
Isto só é necessário em objetos que precisam desse encerramento, portanto elas implementam a interface IDisposable que tem o método Dispose() que será chamado automaticamente pelo using no momento certo. Isto chama-se disposable pattern.
Tem muita coisa sobre o assunto aqui:

Bloco using e Exceções
Try catch pode ser substituido por using?
Quais tipos de recursos são liberados em uma declaração "using"?
É correto usar um bloco using dentro de outro bloco using?
Gerenciamento e liberação de memória
Liberar memória de objetos

O objeto continua disponível, ele teve um descarte da situação que opera naquele momento, a destruição do objeto só ocorre pelo garbage collector, então é possível até mesmo fazer uma ressurreição dele então é possível até mesmo fazer uma ressurreição dele (havia uma resposta que afirmava o contrário, provavelmente por isso eu recebi um negativo aqui).
Não existe essa de boa prática (que é só uma receita de bolo para quem não entende o que está ali), isto é usado quando é necessário, quando é o que precisa e deseja fazer. A performance do primeiro é ligeiramente melhor, mas é errado na maioria das situações, então não adianta comparar.
Coloquei no GitHub para referência futura.
Comment: Alguém viu algo errado na minha resposta? Ou o negativo foi dado por vingança?
Comment: Mas não falo do `Dispose()` em si, e sim chamar algum outro método que encerre. Mas pode ser o `Dispose()` se fizer errado porque se der uma exceção ele não será chamado (se fizer do jeito ingênuo) ou pode até chamar quando já foi chamado.
Comment: Não considero que seja errado usar o *Dispose()* directamente, pode dizer que é preferível usar o *using* sempre que possível. Há casos que é necessário ter o IDisposable num escopo maior que o de um método. É claro que nesses casos a classe que o usa deve/tem de implementar a interface IDisposable.
Comment: @ramaral não sei se entendi, aqui eu não falo isso, de qq forma é praticamente errado, porque quase sempre a pessoa vai chamar errado, e quase nunca tem alguma vantagem nem mesmo fazendo certo. Claro que não é errado  em 100% dos casos. E não sei se entendi o escopo do método, quer dizer que tem casos que o objeto *disposable* pode estar em uma campo e não localmente e aí o `using` não serve? Se for isso é algo que sempre quis escrever mas nunca teve uma pergunta específica. Eu falo por cima em algumas respostas inclusive a que dei hoje, mas não especificamente, fica sempre "no ar".
Comment: Refiro-me à frase: "*Quando não faz isto tem que cuidar desse problema **manualmente**, o que é errado e muitas vezes quase impossível*". Entendi, nela, que se referia à chamada **"manual"** do `Dispose()`. Há casos em que a interacção com o IDisposable requer que este esteja  "sempre" disponível e não apenas durante a chamada a um método.
Comment: Sim, eu entendo. O problema não é usar o Dispose() mas sim usá-lo sem saber o que se está a fazer. A forma de garantir que ele é chamado sempre, na altura certa e de forma correcta é usar *using*. Neste momento estou a usar uma API([SimConnect](https://www.prepar3d.com/SDKv4/sdk/simconnect_api/managed_simconnect_projects.html)] onde não é possível recorrer ao *using*. Isso obrigou-me a estudar a interface IDisposable e como implementá-la de forma correcta.
Comment: @ramaral sim, tem uns casos assim, embora na maioria das vezes é má implementação, não sei nada sobre esta não posso falar.
Answer: Nos dois casos você cria uma instância mas, utilizando o using, é criado um escopo que, ao final de sua execução, libera recursos automaticamente através do método Dispose().


Pegar corretamente qual div foi clicada

Question: Tenho algumas divs:

Estou tentando pegar qual foi clicado, assim:
$j('.filters__filter').click(function(){
    $j(this).click();
});

Só que fica dando erro de tamanho: Maximum call stack size exceeded
Eu queria que toda vez que eu clicasse ne uma dessas divs, eu pegasse qual foi clicado. Como faço isso corretamente? Ou melhor, por que está dando esse erro?
Comment: $('.filters__filter').click(function(){
    alert($(this).html());
});
Answer: Esta quase certo, mas o problema esta no click de dentro, você clica e depois chama o evento click de novo dentro:
$j('.filter__filters').click(function(){
    $j(this).click();
});

Você tem que definir o que você quer fazer, por exemplo, vamos supor que você queira pega o texto então:
$j('.filter__filters').click(function(){
    alert($j(this).text());
});

Assim você vai pegar o texto da div que foi clicada.
Comment: Foi isso mesmo, erro de lógica rsrs. Quando der o tempo marco como aceita!
Comment: Vc tem outro erro ainda atenção ao nome da classe no HTML e no jQuery, está escrito de forma diferente
Comment: @HelderPereira, verdade eu não tinha reparado nisto, realmente a classe deve ter o mesmo nome na tag e no jquery "filter__filters".
Answer: Basicamente você está no caminho, a questão é que você está tentando simular novamente o click na mesma div clicada anteriormente.

$(document).on('click', '.filter__filters', function(){
  $('.filter__filters').css('background', 'white')
  $(this).css('background', 'red')
})

a

b

c

Pegar corretamente qual div foi clicada


UIView size after transform

Question: I need to get the size of UIView after applying transform such as CGAffineTransformScale and  CGAffineTransformRotate .I use the below method to get the size of the view but i am not able to get the accurate size after applying CGaffineTransformRotate.
  CGSizeApplyAffineTransform(view.bound.size,view.transform)

I am using this method because view.frame becomes NULL after applying transform.As mentioned in apple docs. Thanks for help.
Comment: What is the accurate size vs what you're actually getting? What is the frame of the view before the rotation and can you be more specific about the transforms you are applying?
Answer: The notion of "size" has no obvious meaning after application of a transform, and especially a rotation transform. That is why you are not supposed to access the frame of a view whose transform is not the identity transform.  CGSizeApplyAffineTransform certainly does give accurate information under one interpretation of the notion of size (and so does frame, which gives a nonrotated bounding box). You might want to think further, though, about why you believe you need this information.

UIView size after transform


Laço For não inicia com o Array

Question: Sou novo no AS3, e estou tentando criar um jogo para um curso que estou fazendo, mas estou com problemas para iniciar um laço que deve testar a colisão entre dois objetos chamados pelo AS3.
Como os objetos são chamados dinamicamente pelo AS3, estou inserindo-os numa array para referenciá-los, e funciona bem quando os identifico pelo número fixo na array, porém quero que ele possa testar com todos os objetos na array, e o resultado é que o laço nem sequer inicia.
Como não queria que ele fizesse os testes sem necessidades, coloquei o laço após um if para verificar se existiam objetos na array, e achei que o if que não funcionava, então inseri alguns comandos trace, e logo percebi que ele entrava no if, mas simplesmente não iniciava o laço for.
Laço For que não está funcionando:

Resultado na saída:
Answer: Julgo que o problema está na declaração do for:
for(alvo = 0; alvo >= lastEnemy; alvo++)

julgo que deveria ser:
for(alvo = 0; alvo <= lastEnemy; alvo++)

ou:
for(alvo = 0; alvo < lastEnemy; alvo++)

alvo >= lastEnemy é falso logo na entrada do loop
Answer: Você parece estar não estar firme quanto à forma que o laço for funciona. Recapitulando:
for ( iniciação ; condição de permanência ; passo ao final ) { corpo }

iniciação: código a ser executado antes de iniciar o laço. Ele sempre executa, independentemente da condição estar ou não satisfeita.
condição de permanência: teste a ser executado antes de entrar no corpo. Ele sempre testa, inclusive antes de entrar no corpo pela primeira vez. Se o resultado for true, ele entra no corpo, se for false ele não entra e segue para a próxima instrução (i.e. aquela depois do for).
corpo: código que é executado múltiplas vezes, até que a condição de permanência se torne false ou que se saia abruptamente através de um break, return ou em caso de exceção.
passo ao final: código a ser executado depois do corpo. Se o corpo terminar normalmente, ou se a instrução continue for usada, esse passo será executado logo em seguida. Ele ocorre antes da condição de permanência ser testada de novo.

Vendo seu código, me parece que sua intenção é percorrer toda a lista de objetos, certo? Desse modo, seu alvo deve seguir do primeiro índice na lista até o último. Como já sabe, ActionScript, a indexação começa do zero, de modo que o primeiro índice (iniciação) está correto. O passo também está correto (incrementar um no índice) e o índice final (lastEnemy) também - pois ele é o tamanho da lista menos um. O problema está na condição de permanência, então.
Como sumarizado na resposta do @ramaral, sua condição de permanência (alvo >= lastEnemy) é falsa antes mesmo de iniciar o loop (já que a lista de objetos é maior que zero, confome testado por seu if - caso contrário você teria um loop infinito). Isso me leva a crer que você estava tentando criar uma condição de parada em vez disso, estou certo? De todo modo, essa condição de parada não estaria correta, uma vez que ele iria sair logo que alvo fosse igual a lastEnemy (e você quer que ele saia logo após isso). Ou seja, parar se alvo > lastEnemy.
A solução então é negar a condição de parada [corrigida], para se obter a condição de permanência. !(alvo > lastEnemy) que é equivalente a alvo <= lastEnemy. Dessa forma, ele vai continuar no loop enquanto alvo for menor ou igual a lastEnemy, e sair tão logo essa condição se torne falsa.

Laço For não inicia com o Array


Can I bundle the common module when bundling in webpack?

Question: Question about webpack. When bundling modules with webpack Runs the application based on location at the entry point. At this time, when the entry point is set to multiple, a file that is built by the number of entry points is created.
If bundles are bundled into Web packs on an entry basis, they can be bundled into bundles A and B. At this time, I used a module called HELLO in A bundle and a module called HELLO in B module.
At this time, when bundling with the web pack, only the modules used in common (HELLO module) are bundled separately.
Can I make A bundle, B bundle, H bundle? What I want to call H bundle in A bundle and make it available.
Below is my webpack code. I using multiple entries to multiple bundle
module.exports = {
    devtool: 'source-map',
    entry: ['./public/js/index.ts', './public/js/admin/member.ts'],
    output: {
        path: 'dist/public/js',
        filename: '[name].js'
    },
    module: {
        loaders: [{
            test: /\.tsx?$/,
            loader: 'ts-loader',
            options: {
                transpileOnly: true
            }
        }]
    },
    resolve: {
        extensions: [".ts", ".js"]
    }
};

Answer: module.exports = {
  devtool: 'source-map',
  entry: {
    A: ['./public/js/index.ts'],
    B: ['./public/js/admin/member.ts']
  },
  output: {
    path: 'dist/public/js',
    filename: '[name].js'
  },
  module: {
    loaders: [{
        test: /\.tsx?$/,
        loader: 'ts-loader',
        options: {
            transpileOnly: true
        }
    }]
  },
  resolve: {
    extensions: [".ts", ".js"]
  },
  plugins: [
     new CommonsChunkPlugin({
     name: 'H',
     minChunks: 2
   })
};

webpack will make A.js, B.js, and H.js where H.js will have shared modules that A and B use. But H would have to be included first via script tag before including A and B
Something like this?


Como usar os valores de uma coluna presente na Tabela A como parâmetro WHERE de um SELECT na Tabela B?

Question: É possível fazer com que a consulta SQL $professores seja feita com base no ID $row["id"] da 5ª linha do código abaixo?
Contextualizando: este código exibe uma lista com cursos presentes em um BD, imprimindo o nome e o ID do curso, com seu(s) respectivo(s) professor(es) - caso existam. Entretanto, essa consulta de professor deve ser feita com base no papel que um professor tem dentro de uma disciplina (o que é feito com o comando $professores, mas essa consulta só está funcionando se um valor manual de ID for acrescentado, sendo que o ideal é que tudo isso seja dinâmico, por isso o interesse em usar o $row["id"] como parâmetro).
Grato desde já!

$cursos = "SELECT id, fullname FROM mdl_course WHERE visible=1";
    $resultCursos = $conn->query($cursos);
    $row = $resultCursos->fetch_assoc();

        while($row = $resultCursos->fetch_assoc()) {
            echo '';
            echo '
'.utf8_encode($row["fullname"]).'
';
            echo '
 Professor: ';

            $professores = "SELECT firstname, lastname FROM mdl_user WHERE id IN(SELECT userid FROM mdl_role_assignments WHERE contextid IN (SELECT id FROM mdl_context WHERE

/* instanceid='ESSE VALOR DEVE SER IGUAL AO ID DO CURSO QUE APARECE NA 5ª LINHA' */

AND contextlevel=50) AND roleid=3)";
            $resultProf = $conn->query($professores);
            $row2 = $resultProf->fetch_assoc();

                if ($resultProf->num_rows > 0) {
                    echo utf8_encode($row2["firstname"]). ' '.utf8_encode($row2["lastname"]).", ";
                } else {
                    echo "Sem professor cadastrado.";
                }

            echo '
';
            echo 'Acessar';
            echo '';
        }
Answer: Acabei descobrindo como fazer isso!
Setei a seguinte variável:
$iddocurso = $row["id"];

E no comando SQL, usei:
instanceid='$iddocurso'

Funcionou!