Hide Fields Based on Role

Question:
Possible Duplicate:
Is it possible to assign permission to fields?

I have a contact type called contact form, and I want to alter the fields that are visible when adding that contact type, based on the user role. I want admin to be able to change the value of fields such as 'status', 'date completed' etc but I don't want these to be visible to the anonymous role.
Answer: Sounds like the function of Field Permissions module.

The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

Hide Fields Based on Role


Mostrar ruas e imagens no Type Satellite por default

Question: Estou querendo mostrar os nomes das ruas e estabelecimentos por default. Qual seria a opção? Estou fazendo assim:
var myOptions = {
    scrollwheel: false,
    center: new google.maps.LatLng(lat, centerLon),
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.SATELLITE
};

Answer: Nas opções do mapa não há propriedades para habilitar estas opções explicitamente, elas já vem com o tipo de visualização. Para exibir conforme você precisa, basta usar a visualização HYBRID, desta forma:
var options = {
    scrollwheel: false,
    center: new google.maps.LatLng(lat, centerLon),
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.HYBRID
};

Veja um exemplo completo abaixo:

var gm = google.maps;

function initialize() {
  var options = {
    zoom: 15,
    center: new gm.LatLng(-27.593427, -48.550686),
    mapTypeId: gm.MapTypeId.HYBRID,
    scrollwheel: false
  };

  var map = new gm.Map(document.getElementById("map"), options);

}

gm.event.addDomListener(window, 'load', initialize);
body {
    margin: 0;
}
#map {
  height: 600px;
  width: 100%;
}

Answer: Você tem que declarar o tipo do mapa como ROADMAP, que é a opção padrão da API do MAPS.
Deixe assim:
var myOptions = {
    scrollwheel: false,
    center: new google.maps.LatLng(lat, centerLon),
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};

Comment: o ROADMAP mostra o nome das ruas e estabelecimentos, é isso que eu quero mas utilizando o Satellite.


Force HTTP (no SSL) on a single page in a site where all pages are forced HTTPS

Question: I know that there exists several posts asking about the exact same thing. I asked the same question again, since I've read each and every one of them, and tried the solutions. Maybe they worked for the O.Ps'es codes, but unfortunately didn't work for mine.
I really need to disable HTTPS on a single PHP page called play.php, so that the page is accessible via direct HTTP, or redirect to HTTP if directly requested via HTTPS.
I need to change https://example.com/play/blabla to http://example.com/play/blabla, while the rest of the site is forced HTTPS.
Here is my full .htaccess  code:-
Header set Access-Control-Allow-Origin "*********"

ErrorDocument 404 /pagenotfound.php
ErrorDocument 403 /pagenotfound.php

Options -MultiViews
RewriteEngine on
RewriteBase /

Options +FollowSymLinks

RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

RewriteRule ^search/(.*)$ viewgames.php?search=$1 [L,QSA,NC]
RewriteRule ^category/(.*)$ viewgames.php?cat=$1 [L,QSA,NC]
RewriteRule ^users/(.*)$ users.php?action=$1 [L,QSA,NC]
RewriteRule ^play/(.*)/$ play.php?gn=$1 [L,QSA,NC]
RewriteRule ^play/(.*)$ play.php?gn=$1 [L,QSA,NC]

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^([a-z]+)/?$ $1.php [L,NC]

I have a script called play.php which is rewrited using .htaccess to /play/ i.e if someone requests example.com/play/foobar, the request will be sent to example.com/play.php?gn=foobar.
I'm very new to .htaccess. I will really appreciate your help.
[Edit] I have updated the above code to show my full .htaccess. I hope it helps. BTW, the stars (*) on the first line of code is to hide my actual website address.
Comment: _"Didn't you notice that some popular gaming sites don't enable HTTPS?"_ - I don't visit gaming sites so... no.
Comment: Just to properly understand the issue, why would you need this?
Comment: My website loads several games under an iframe. Some games cannot run on HTTPS, and cause mixed content issues. To prevent those issues, I want to disable HTTPS on that specific page. Didn't you notice that some popular gaming sites don't enable HTTPS?
Comment: @MagnusEriksson http://www.silvergames.com/en/stabbyio this game doesn't support HTTPS, so they disabled it. Then again, https://www.silvergames.com/en/deadwalk-io supports HTTPS, so they didn't remove HTTPS from this gameplay page.
Comment: You should either use a proxy with TLS or tell the game provider about letsencrypt, https://letsencrypt.org. Free certificate(s).
Comment: Can you show your full .htaccess in question?
Comment: @anubhava I've updated the post and included my whole .htaccess. Thanks in advance.
Answer: Here is full .htaccess with my comments:
Header set Access-Control-Allow-Origin "*********"

ErrorDocument 404 /pagenotfound.php
ErrorDocument 403 /pagenotfound.php

Options +FollowSymLinks -MultiViews
RewriteEngine on
RewriteBase /

# it is important to keep www removal rule as first rule to avoid multiple redirects
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]

# http->https if URL is not starting with /play/ or /play.php
RewriteCond %{HTTPS} !on
RewriteRule !^play(?:\.php|/.*)?$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE,NC]

# https->http if URL is starting with /play/
RewriteCond %{HTTPS} on
RewriteRule ^play(?:/.*)?$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE,NC]

RewriteRule ^search/(.*)$ viewgames.php?search=$1 [L,QSA,NC]

RewriteRule ^category/(.*)$ viewgames.php?cat=$1 [L,QSA,NC]

RewriteRule ^users/(.*)$ users.php?action=$1 [L,QSA,NC]

RewriteRule ^play/(.+?)/?$ play.php?gn=$1 [L,QSA,NC]

# make sure to check for presence of .php file before rewrite
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([a-z]+)/?$ $1.php [L,NC]

It is important to completely clear browser cache or use a new browser of testing the changes.
Comment: thank you SO much!! I couldn't solve this problem after searching for a straight week, and you did it for me. I'm rewarding the bounty to you :-)
Comment: Thank you so much. Your code works like a charm. But I am encountering a simple problem: When I access https://example.com/play/blabla, it redirects to http://example.com/play.php?gn=blabla. Is there any way to redirect to the clean URL? or will it always be like this?
Comment: exactly what I meant :-). The HTTP and HTTPS can change, but I really need the clean URL to remain cleaned.
Comment: after I uploaded the new code, the HTTP change does not occur anymore, i.e http://example.com/ does change to https://example.com, but https://example.com/play/blabla doesn't change to http://example.com/play/blabla
Comment: I've edited the question again to show exactly how I need the site URL to behave. Please help.
Comment: Got it, test my changes in a new browser again
Answer: You can disable https to your play.php URI using the following RewriteRule
RewriteEngine on
RewriteCond ℅{REQUEST_URI} play\.php$ [OR]
RewriteCond ℅{REQUEST_URI} /play
RewriteCond ℅{HTTPS} on
RewriteRule ^ http://℅{HTTP_HOST}℅{REQUEST_URI} [L,NE,R]

This will redirect https://example.com/play.php to its non SSL version.
Since your rule already checks http urls , you can also add a condition to your rule to exclude the play.php from HTTPS redirection something like the following :
 RewriteCond %{HTTPS} off
 #redirect all to https except /play and /play.php
 RewriteCond %{REQUEST_URI} !play
 RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

Comment: @SayanjyotiDas I have updated the Rules. This should now handle both URIs `play` and `play.php` . Please clear your browser cache before testing this updated code.
Comment: Your code does work when I call https://example.com/play.php?gn=xyz, but doesn't on a clean URL https://example.com/play/xyz. As I mentioned in my original post, I really need the code for the clean URL


I am not able to assign a group to a node while creating it

Question: We are using Drupal 7.39 and Services 7.x-3.12 .
We are also using organic groups 7.x-2.7 and while creating a node of type attendance (which is a group content). We are not able to assign a group to it.
We are passing the following parameters:
{
  "type": "attendance",
  "title": "Testing Attendance",
  "field_attendance_status":{
  "und":{
    "tid":3
  }},
  "og_group_ref":{
    "target_id":16
  }
}

Answer: I have tried posting group content but didn't work in all field widgets (select, checkbox or auto complete)
I see there exist an issue with that field og_group_ref take a look at that question have an answer with a patch hope to solve the issue.
Answer: Try this:
{
  "type": "attendance",
  "title": "Testing Attendance",
  "field_attendance_status":{
  "und":{
    "tid":3
  }},
  "og_group_ref":{
    "und": [
      { "target_id":16 }
    ]

  }
}

Either way, you should be able to verify the proper JSON to use by retrieving an existing node that has an og_group_ref.
For example, do a GET request (or just visit in a browser):
?q=[my-api-endpoint]/node/123.json
Then use a tool like jsonlint.com to inspect the JSON.
I'd also like to point out, that the JSON data you send to Services is sometimes dependant on the widget you have selected for the field's form element. See here for more details: https://drupal.stackexchange.com/a/159292/10645


configure Angular 2 Webpack App in Docker container environment specific

Question: We want to deploy our Angular 2 app using Docker images in different environments (staging/test, production, ...)
When developing locally we are connecting to the backend REST API via http://localhost:8080 but when we deploy in the different environments we want to use the same Docker image and connect to a different REST API endpoint.
What would be the preferred way to inject this configuration into the Docker container at runtime?
Is there a way to do this via environment variables?
Can we do this via a plain text file containing something like
{
    "BASE_URL": "https://api.test.example.com"
}

Comment: are you using angular-cli or a custom build?
Comment: we created the project based on https://github.com/AngularClass/angular2-webpack-starter/
Comment: Sorry, I am not proficient on how this is working with the werbpack-starter repo. angular-cli which we are using has the option you describe (environments).
Comment: as far as I am familiar with angular-cli those environments are used at build time and not at runtime, what we are looking for is a way to configure the app at runtime
Comment: You are right. But with your docker solution, wouldn't you build your app inside docker before running it anyway?
Comment: I would build it once inside Docker and then deploy the created image in multiple different locations. There has to be a way to configure an Angular 2 app at runtime!
Comment: Ok, got you. Sorry I am no help then.
Comment: This may do what you want: https://stackoverflow.com/questions/43234536/most-modern-way-to-externalize-angular-2-environment-configuration/43980985#43980985
Answer: After having some discussions in this post and on twitter it looks like there is no easy way to achieve what I want via Webpack. The files are only served as static files at runtime and it is not possible to exclude a file at build time and include it at runtime.
So I decided to go with the solution/workaround I had in mind: changing the static files when starting up the docker container.
I create my docker image by doing
npm run build:prod
docker build -t angularapp .

I am using the official nginx docker image as my base image and the Dockerfile looks like
FROM nginx:1.11.1

COPY dist /usr/share/nginx/html
COPY run.sh /run.sh

CMD ["bash", "/run.sh"]

The run.sh is used to modify the config file via sed and to start nginx afterwards:
#!/bin/sh

/bin/sed -i "s|http://localhost:8080|${BASE_URL}|" /usr/share/nginx/html/api.config.chunk.js

nginx -g 'daemon off;'

This allows me to configure the BASE_URL via environment variabel in my docker-compose.yml file (simplified):
version: '2'

services:
  api:
    image: restapi
  frontend:
    image: angularapp
    environment:
      BASE_URL: https://api.test.example.com

With this solution/workaround I can deploy the docker image created by my jenkins job for a specific version deploy in all my environments (development, staging, production) by configuring the REST API endpoint used via environment variable when starting the docker container.
Comment: I tried all the solution you have produced here but failed so can you share your code with me please. I also should do the same.
Answer: The final solution here is completely dependency on what your CI / CD toolchain looks like but this solution can be molded into pretty much anything.
First step: Add something like https://github.com/motdotla/dotenv to your dependencies this will be handling your config values. There are other optiions & depending on your needs, rolling your own is easy enough.
Per the docs, load the config as early as possible in your app ( global app.module.ts is my personal choice as we want this to be globally available ).
Simply - Based on process.env.NODE_ENV you are going to load different configs per stack and to make the DX simple, I always give config values a default so my developers don't have to bother with the file.
For TESTING, STAGING, PRODUCTION - As an example, you want to set BASE_URL_STAGING & BASE_URL_PRODUCTION in the environment variables for whatever CI provider you are using.
As a part of your CI run & based on git branch, write your config values into a .env file and then add a COPY into your Dockerfile || docker-compose.yml to pull in the environment file you just wrote during your docker build.
After your validations, when you push your new docker image, the .env is part of your deployment package targeting what ever environment specific endpoints you need.
Comment: I understand, but the important part is that I do not want to build multiple docker images for different environments (staging, production, ...). I only want to run `npm run build:prod` once and package that created files up in a docker image
Comment: this does not lead to what I want: I want one docker image of a specific version that I can deploy to multiple environments with different configurations :(
Comment: The mechanism for passing the env variables doesn't really matter. Something like dotenv & it's associated webpack plugin just wire external environment variables to your application. You can just as easily pass something like `BASE_URL_STAGING` into your docker run command

`docker run -e ` or in your docker-compose like ..

`environment:
    - BASE_URL=${BASE_URL_FROM_ENVIRONMENT}
`

It's a two part problem. dotenv handles getting the external vars into your application, setting those vars is toolchain specific
Answer: I would have taken a slightly different, but in a way similar approach to your sed-shellscript.
I like the idea of the "plain text config file" that you mentioned, how about this:
Serve the config file from a known location, e.g. ./config?
Since your JS is already loaded from the current site, at least there you should be able to rely on a relative path.
Step 1: The shellscript starting up in the docker container writes the config parameters from the environment variables to the plaintext file and places it in the same folder as the packed angular code.
Step 2: In the main HTML file that loads the app there is some init code like this:
$(function() {
  $.get('./config')
    .then(function(res) {
      window.appConfig = res.data;
      // your bootstrapping call
      angular.bootstrap(....);
    });
});

Step 3: You use the global variables in your angular app, e.g. if you are using OpaqueToken:
import { OpaqueToken } from '@angular/core';

const CONFIG_TOKEN = new OpaqueToken('config');

export const THIRDPARTYLIBPROVIDERS = [
  { provide: CONFIG_TOKEN, useValue: window.appConfig }
];

Yes this is still a bit hacky & in your dev-env the node-proxy that you use for serving the ng-app also has to expose such a config endpoint.
Also this needs an additional request, but this could be easily avoided by extending the init-code a bit to cache the data in localStorage for example (given that this data won't really change over time).
But all in all I think this is a bit more maintainable than sed-ing some files of which you don't really know how they are layed out.
Let me know what you think!


Django - OperationalError after deleting migration files

Question: In the earliest days of my system, before i knew how to utilize django's built-in User model, i had my own class named myUser which i intended to use for the same purpose. i ended up deleting this one and instead using django's User model. all was fine for a while. then i tried to change the id of all my custom models to a UUIDField, and got the syntax wrong, which i unfortunately only realized after i ran makemigrations and migrate. i corrected it, but there was still a bug because the migration file of the wrongly-syntaxed UUIDField still lingered in migrations. that's what i understood from googling for a while, anyway. since i wasn't sure which migration file caused the error, i just deleted the last 5 migration files (in hindsight, not the best idea i've ever had). Unfortunately, one of those migration files were the one which covered the deletion of the myUser model.
now, whenever i try to migrate, i get the following error:
django.db.utils.OperationalError: no such table: phoneBook_myUser
it seems this error is stopping any of my new migrations to go through. i've googled for a while, and it seems my two options are to either dive deep down into django details and try to mess around until i fix it -which i had hoped to avoid, considering i've only been using Django for 2 weeks- or to reset everything and build the system from scratch. That is not too ideal either.
i have a backed-up version of the myUSer model. is reinstating it, migrating, deleting it and then migrating 'safe' or will it make an even bigger mess of things? Is there any other course of action i can take to fix this issue?
update:
result from python manage.py showmigrations:
<code>    admin
     [X] 0001_initial
     [X] 0002_logentry_remove_auto_add
     [X] 0003_logentry_add_action_flag_choices
    auth
     [X] 0001_initial
     [X] 0002_alter_permission_name_max_length
     [X] 0003_alter_user_email_max_length
     [X] 0004_alter_user_username_opts
     [X] 0005_alter_user_last_login_null
     [X] 0006_require_contenttypes_0002
     [X] 0007_alter_validators_add_error_messages
     [X] 0008_alter_user_username_max_length
     [X] 0009_alter_user_last_name_max_length
     [X] 0010_alter_group_name_max_length
     [X] 0011_update_proxy_permissions
     [X] 0012_alter_user_first_name_max_length
    contenttypes
     [X] 0001_initial
     [X] 0002_remove_content_type_name
    phoneBook
     [X] 0001_initial
     [X] 0002_auto_20210707_1306
     [X] 0003_informationrating_owner_ownerset_comments_connection/
         _numbermetadata_source
     [X] 0004_rename_comments_comment
     [X] 0005_auto_20210707_1632
     [X] 0006_auto_20210707_1634
     [X] 0007_auto_20210707_1637
     [X] 0008_alter_company_company_type
     [X] 0009_owner_owner_type
     [X] 0010_numbermetadata_published_at
     [X] 0011_auto_20210713_0957
     [X] 0012_auto_20210713_1014
     [X] 0013_connectionrating
     [X] 0014_informationrating
     [X] 0015_delete_informationrating
     [X] 0016_alter_owner_owner_type
     [X] 0017_alter_owner_owner_type
     [X] 0018_auto_20210713_1349
     [X] 0019_auto_20210713_1525
     [X] 0020_auto_20210713_1529
     [X] 0021_auto_20210713_1533
     [X] 0022_auto_20210713_1535
     [X] 0023_alter_numbermetadata_owner_set_id
     [X] 0024_auto_20210719_0948
     [X] 0025_auto_20210719_1555
     [ ] 0026_auto_20210720_1528
     [ ] 0027_connection_connection_status
    sessions
     [X] 0001_initial
</code>
my migration files:
<code>    0001_initial.py
    0002_auto_20210707_1306.py
    0003_informationrating_owner_ownerset_comments_connection/
    _numbermetadata_source.py
    0004_rename_comments_comment.py
    0005_auto_20210707_1632.py
    0006_auto_20210707_1634.py
    0007_auto_20210707_1637.py
    0008_alter_company_company_type.py
    0009_owner_owner_type.py
    0010_numbermetadata_published_at.py
    0011_auto_20210713_0957.py
    0012_auto_20210713_1014.py
    0013_connectionrating.py
    0014_informationrating.py
    0015_delete_informationrating.py
    0016_alter_owner_owner_type.py
    0017_alter_owner_owner_type.py
    0018_auto_20210713_1349.py
    0019_auto_20210713_1525.py
    0020_auto_20210713_1529.py
    0021_auto_20210713_1533.py
    0022_auto_20210713_1535.py
    0023_alter_numbermetadata_owner_set_id.py
    0024_auto_20210719_0948.py
    0025_auto_20210719_1555.py
    0026_auto_20210720_1528.py
    0027_connection_connection_status.py
    __init__.py
</code>
Comment: Can you update your question with output of `python manage.py showmigrations` and your migrations folder?
Comment: Which migrations file did you deleted?
Comment: none of these.. i wish i knew which ones - i wish i knew exactly what the migration folder looked like just before i deleted. i could have just reinstated them. i did a safe delete - will that let me search them up?
Comment: Did you use git ?
Comment: Yes - but the migration files in the previous git push (2 days old) and the migration files i have right now, are identical. Unfortunately, the files i deleted were created and deleted without being backed up.
Answer: i ended up creating a new version of the project, a perfect copy of all the files, but with a new database, and everything works as it should.
Answer: create a new folder call it "migrations" in your app and add an empty "init.py" file in it, then make migrations and migrate.
after all this make sure you create a new superuser to access admin page


Express $\arcsin(x)$ in terms of $\arccos(x)$. Solve the equation 2 arctan x=arcsin x + arccos x

Question: Express $\arcsin(x)$ in terms of $\arccos(x)$.
Using the same, solve the equation
$$ 2\,\tan^{-1}x  = \sin^{-1} x + \cos^{-1} x $$
I'm not sure if I am on the right track, but here is what i did:
$$\sin\left(\frac{\pi}{2}-x\right) = \cos(x)$$
$$\sin(x) = \frac{\pi}{2}-\cos(x)$$
Comment: The answer for first one is arcsin x =pi/2-arccos x, or sin^-1(x)=pi/2-cos^-1(x). And for the equation, it is 1. Someone please guide me through.
Answer: $$x = \sin(y)$$
$$x = \cos\left(\frac{\pi}{2}-y\right)$$
$$y=\arcsin(x)$$
$$\frac{\pi}{2}-y=\arccos(x)$$
Adding the last equations will give your identity:
$$\frac{\pi}{2}=\arcsin(x)+\arccos(x)$$
Now you can solve the equation:
$$2\arctan(x)=\arcsin(x)+\arccos(x)=\frac{\pi}{2}$$
$$\arctan(x)=\frac{\pi}{4}$$
I leave the rest to you.
Answer: HINT:
You don't need too much hassle as by definition, $$\sin^{-1} x + \cos^{-1} x=\dfrac\pi2 $$ for $-1\le x\le1$
Comment: Yes, i got part one. But now how will I solve the equation given above?
Comment: @MathSolver, So, we have $\arctan x=\dfrac\pi4\implies x=\tan\dfrac\pi4$
Answer: Solve the equation:
You can solve the above assuming that (I'll provide a proof below):

$arcsen(x)+arccos(x)=\dfrac{\pi}{2}$

Starting from this, we can add to the right side: $2 arctan(x)$
Obtaining:

$arcsen(x)+arccos(x)=\dfrac{\pi}{2}=2 arctan(x)$

We deduce:

$arctan(x) =\dfrac{\pi}{4}$

Solving,

$tan(arctan(x))=tan(\dfrac{\pi}{4})$ then $x=1.$

Proof of:

$arcsen(x)+arccos(x)=\dfrac{\pi}{2}$

Considering $u= arcsen(x)$ and $v=arccos(x)$, we have that $u  \in [-\dfrac{\pi}{2}, \dfrac{\pi}{2}]$ and $v \in [0, \pi]$ moreover:
$x = sen(u)$ and
$x= cos(v)$
so that:

$sen(u)=cos(v)$ (1)

Given that: $u  \in [-\dfrac{\pi}{2}, \dfrac{\pi}{2}]$, $v \in [0, \pi]$ and $cos(v)=sen(-v,\dfrac{\pi}{2})$ with $-v+ \dfrac{\pi}{2} u  \in [-\dfrac{\pi}{2}, \dfrac{\pi}{2}]$, we make sure that (1) we have $u$ and $v$ such that  $u=\dfrac{\pi}{2}-v$, i.e., $u+v=\dfrac{\pi}{2}.$


Is it possible to await async tasks during a button click?

Question: I have a refresh button in my app that uses some async methods to update the list of items displayed.  The problem is that I can't have a return type of Task for the event handler for the button click so I'm left with an async void method.  Thus, the user can hit the refresh button, then select an item while the list is being repopulated which will result in an error.
start of code that handles button click:
    private async void Button_Click_1(object sender, RoutedEventArgs e)
    {

        await ViewModel.CreateMessageCommand();

So is there anyway to properly await for this task to finish?
Answer: Since event handlers for controls typically return void, you need to handle this in a different manner.  This often means, in a scenario like yours, that you need to disable all or part of your UI while things are loading, i.e.:
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
    // Make the "list" disabled, so the user can't "select an item" and cause an error, etc
    DisableUI();

    try
    {
       // Run your operation asynchronously
       await ViewModel.CreateMessageCommand();
    }
    finally
    {
       EnableUI(); // Re-enable everything after the above completes
    }
}

Answer: You should simply disable all of the UI controls that the user shouldn't be interacting with at the start of the action, and then enable them at the end.
Answer: One way would be to wrap the View in a BusyIndicator from the WPF Toolkit
You would provide a bool property on your viewmodel and toggle the value at the start and end.
It puts up a UI element above all the other controls preventing user interaction but providing an animated busy message, which can be updated to say whatever you wish.
Comment: You can't use WPF controls in Windows Store apps.  Different platform, though still Xaml.  You'd need a 3rd party busy indicator port (or write your own)
Comment: I don't see why it shouldn't. Unless they restrict what 3rd part libraries you can use.
Comment: @ReedCopsey Since it is open source, you could download the source and recompile for the correct platform. Or only take the relevant BusyIndicator Control.
Comment: @ywm Unfortunately, moving from WPF to Windows Store is typically far more than a recompile.  The Windows Store API is far less feature rich than WPF's, so depending on what's used in the control, it may be difficult.  The version from the Silverlight Toolkit would likely be a far simpler port: https://silverlight.codeplex.com/SourceControl/latest#Release/Silverlight4/Source/Controls.Toolkit/BusyIndicator/BusyIndicator.xaml


What should I look for in a beginner guitar?

Question: I'm currently looking into buying an affordable and decent quality guitar, but I'm wondering what to look for? I noticed that there are 6-string guitars and 12-string guitars, which is best for a beginner?
I have been playing piano for four years and I want to play another instrument, I have learned up to a decent level of theory (level 7).
What should I look for when buying a guitar for beginners?
Answer: Yamaha are a reputable company who make musical instruments of almost every sort,in all price ranges.   But it sponds as if you're a long way from knowing enough about guitars to make a sensible choice.  Take your first lesson before choosing an instrument.  Ask the teacher's advice.
Answer: You definitely don't want to start off with a 12 string, which requires a lot more finger strength and dexterity. My thoughts would be to just go to your local guitar shop and buy something cheap. That's why I did anyway, 2 years later and I'm still playing on my crappy $120 steel string. You can also check out pawn shops. Gear doesn't matter much as a beginner.
Comment: What you say seems to make sense, except that I do not agree at all that _gear does not matter to a beginner_: if poor equipment makes it hard to play or unpleasant to hear, you will regret your purchase and may be put off playing. A lot depends on how much you can spend and how much you expect to play.
Comment: @PJTraill - yep.  Another thing that must be considered is that many cheap guitars (like cheap violins, etc) are set up so poorly- especially in having action way too high- that they're very difficult to play at all.
Answer: Yamaha do make some decent acoustics but I have found their very cheap ones aren't great, as they're mass produced in a factory which makes various other things, so as you can imagine they're not subject to the same quality control or craftsmanship as other companies are.
I've heard good things about Freshman guitars - they're very well trusted, as are a lot of Epiphones and Tanglewood guitars.
Some other things I'd want in a good acoustic - although this is arguably a matter of taste - is guitars with a satin finish on the neck. Some guitar necks have a lot of polycellulose lacquer on them which can make them sticky. You'll find it easier to play if you're not trying to work against friction from a highly polished neck.
As a user mentioned above, you definitely want to start with a 6 string, and not a 12, as they require some extra finger strength to press those extra strings and a slightly different playing style is required to play them successfully.
Answer: The entry level and bottom of the line guitars are junk, unless you know what you are doing.  It's worth spending $250-400 on your first guitar to get something that sounds decent, has a relatively nice fretboard action, etc.
Seagull and Washburn are some possibilities.  For a little more money, Blueridge makes a nice entry level guitar.  I don't have any experience with Yamaha guitars.  But, I've played their keyboards, and they have a very nice action.  Yamaha makes a wide range of musical instruments, and is well-known in the music business.
It's a LOT easier learning on a nicer instrument.  The guitar will be easier to play, and it's less likely that you will get discouraged, and quit.
You definitely want to purchase a 6-string guitar.


Compiler Error When Calling Base Constructor when both Base and Derived are Templated With Derived Type Parameter

Question: I am struggling to understand why the following code does not compile:
template <class T>
class Base {
    public:
        Base(int a){}
};
template <class T>
class Derived: public Base<T>  {
    public:
        Derived(int a): Base(a){}
};
int main(){}

On my compiler (gcc 5.4.0 with C++ 11) this outputs the error message
error: class 'Derived<T>' does not have any field named 'Base'
         Derived(int a): Base(a){}

I see that this is somewhat similar to Template base constructor call in member initialization list error, though that test case actually compiles for me while this one does not: The main difference seems to be that both Base and Derived use the same type parameter. Additionally, it compiles fine if I explicitly add the type parameters or I give an explicit scope for base, as in
template <class T>
class Base {
    public:
        Base(int a){}
};

template <class T>
class Derived: public Base<T>  {
    public:
        Derived(int a): Derived::Base(a){}
};

int main(){}

What's going on? Am I misunderstanding when injected class names may be used?
Comment: Why Not Derived:Base (a)?
Comment: Note that [it works as is with MSVC](http://rextester.com/DXHHO32475), because MSVC does name lookup differently than GCC.  Clang emits the same error as GCC, though, albeit worded differently.
Answer: The injected class name Base is a member of the class Base, and since the base class is dependent, its scope is not searched during unqualified name lookup. As such, using the name Base will only find the class template, not the injected class name of Base<T>. That is why you must write Base<T>.
Derived::Base works because it causes name lookup to be postponed until Derived is instantiated.


Comparison of a meta analysis pooled estimate to an estimate from primary research

Question: I  want to compare the pooled estimate (mean change in two time points) of a meta analysis that has been published, to the same estimate from a primary research that i am carrying out (on my own dataset).  Is there a  statistical test for this comparison or do i just compare overlapping of confidence intervals? Thanks in advance!
Answer: I would have thought a Wald-type test would work here.
$$
z = \frac{M_1 - M_2}{\sqrt{se_1^2 + se_2^2}}
$$
 where $M_1$ is the mean from the meta-analysis, $M_2$ is your mean and $se$ are the corresponding standard errors. You then have a $z$ to test.
Comment: Thank you very much indeed. This was actually my original thought, so it really good to know it makes sense not only to me. I just couldn't find any related references.


Slidershow Carousel

Question: Estou tentando fazer um carrossel como o abaixo, mas não estou conseguindo.
Alguém pode em ajudar por favor?
Comment: Teria que ser exatamente nesse estilo? Não serviria um slideshow?
Comment: Adicione na pergunta o código que você já fez.
Comment: Acho que consegui fazer com que desse certo. Vou fazer mais uns testes se der certo posto aqui. Muito obrigada!
Answer: Caso atenda à sua necessidade, você pode fazer um carrossel/slideshow como descrito nesse link. Nesse link há o código completo e ensinando como fazer.
Exemplo do link acima:

var slideIndex = 0;
showSlides();

function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides");
    var dots = document.getElementsByClassName("dot");
    for (i = 0; i < slides.length; i++) {
        slides[i].style.display = "none";
    }
    for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
    }
    slideIndex++;
    if (slideIndex > slides.length) {slideIndex = 1}
    slides[slideIndex-1].style.display = "block";
    dots[slideIndex-1].className += " active";
    setTimeout(showSlides, 2000); // Change image every 2 seconds
}
* {box-sizing:border-box}
body {font-family: Verdana,sans-serif;}
.mySlides {display:none}

/* Slideshow container */
.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

/* Caption text */
.text {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

/* The dots/bullets/indicators */
.dot {
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active {
  background-color: #717171;
}

/* Fading animation */
.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}

@keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}

/* On smaller screens, decrease text size */
@media only screen and (max-width: 300px) {
  .text {font-size: 11px}
}

1 / 3

Caption Text

2 / 3

Caption Two

3 / 3

Caption Three

Comment: É interessante você postar os trechos relevantes na resposta, pois o link pode quebrar ou o conteúdo pode mudar.
Comment: Post editado com o código do Carousel.

Slidershow Carousel


Alguém me ajuda por favor meu carrossel não muda de foto

Question:

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TPM-Home</title>
    <link rel="stylesheet" href="Home.css">
    <link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <button class="btn btn-outline-primary">Home</button>
    <button class="btn btn-outline-primary">Sobre nós</button>
    <button class="btn btn-outline-primary">Historias contadas</button>
    <button class="btn btn-outline-primary">Envie sua Historia</button>

    <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">

      Previous
    </button>
    <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">

      Next
    </button>

Answer: É preciso incluir o ficheiro JS do Bootstrap.

Existe um parâmetro para as imagens mudarem mais rapidamente.

Quando o cursor está por cima da imagem a imagem não muda.


Does the method post() of the object boost::asio::io_service uses the boost::coroutines for short tasks?

Question: Does the method post() method of the object boost::asio::io_service uses the boost::coroutines to perform queue of short-tasks performed in the handlers? This can save the resources spent on synchronization when using threads, but makes it impossible to move tasks to another thread. Or it makes no sense?
Comment: @Alex Could you elaborate on what advantages this would provide? While coroutines are excellent for constructing the asynchronous call chains within handlers (and part of the Boost.Asio 1.54 API), I'm having a hard time understanding the gains within the internal event loop dispatch.
Comment: Boost.Coroutine was accepted in Boost 1.53, Boost.Asio - in 1.35. Obviously, the latter doesn't depend on the former.
Comment: @Igor R. Does boost::asio haven't difference between 1.35 and 1.53 versions? Why not take advantage of new opportunities in the old library in its new version?
Comment: @Tanner Sansbury  I guess we mean the same thing. Do not to use coroutines in the method post(), but to use when you call handler of chain of tasks that have been set by the post(). And will be in boost::asio 1.54 an opportunity to control their use? For example, for short tasks - to use coroutines to reduce the overhead of synchronization, and for a long task - to use threads for load balancing.
Answer: As best as I could tell, Boost.Asio does not use coroutines.
From an implementation point of view, I would imagine using a coroutine, such as those provided by Boost.Coroutine, would introduce overhead when invoking posted handlers.  At the point in which the event loop knows what handlers can be invoked, it could simple invoke the handler rather than having to hoist the handler in a trampoline function so that it can be transparently invoked within the context of a coroutine.
Boost.Asio does not know the actual or expected runtime duration of handlers, so it must perform the same internal synchronization regardless of the handlers.  When the io_service is only being processed by a single thread, then synchronization overhead can be mitigated by providing a concurrency_hint during construction.  Other areas, such as the reactor, may still need to perform synchronization.
In the end, rather than imposing context of execution, Boost.Asio provides a robust toolkit and empowers the users to choose the best option for themselves.  The current Boost.Asio candidate for Boost 1.54 enhances this experience through its first-class support for:

Stackful Coroutines based on Boost.Coroutine.  Here is an example where do_echo executes within the context of my_strand as a coroutine.  Each async operation yields control back to the calling thread after initiating the asynchronous operation, and when the completion handler is invoked, control returns to immediately following the previous yield point.
boost::asio::spawn(my_strand, do_echo);

// ...

void do_echo(boost::asio::yield_context yield)
{
  try
  {
    char data[128];
    for (;;)
    {
      std::size_t length =
        my_socket.async_read_some(
          boost::asio::buffer(data), yield);

      boost::asio::async_write(my_socket,
          boost::asio::buffer(data, length), yield);
    }
  }
  catch (std::exception& e)
  {
    // ...
  }
}

Boost.Asio provides a complete echo_service example that uses Stackful Coroutines.
Stackless Coroutines have been promoted to the documented public API from the HTTP Server 4 example.  These are implemented as a variant of Duff's Device, but the details are cleanly hidden through the use of pseudo-keywords reenter, yield, and fork.  This following is roughly the equivalent of the above Stackful Coroutine example:
struct session : boost::asio::coroutine
{
  tcp::socket my_socket_;
  char data_[128];

  // ...

  void operator()(boost::system::error_code ec = boost::system::error_code(),
                  std::size_t length = 0)
  {
    if (!ec) reenter (this)
    {
      for (;;)
      {
        yield my_socket_.async_read_some(
            boost::asio::buffer(data_), *this);

        yield boost::asio::async_write(my_socket_,
            boost::asio::buffer(data_, length), *this);
      }
    }
  }
};

See the boost::asio::coroutine documentation for more details.

While I do not know if there are performance benefits to constructing asynchronous call chains with coroutines, I feel as though their greatest contribution is maintainability and readability.  I have found that being able to read and write asynchronous programs in a synchronous manner helps reduce the complexities introduced with inverted flow of control, as it is now possible to remove the spacial separation between operation initiation and completion.
Comment: @Alex: Depends.  When the `io_service` implementation uses windows I/O completion ports, the _concurrency_hint_ specifies the max, per [`CreateIoCompletionPort()`](http://msdn.microsoft.com/en-us/library/windows/desktop/aa363862%28v=vs.85%29.aspx).  For the non-Windows IOCP implementation, a _concurrency_hint_ of 1 is the only case where optimizations currently apply.
Comment: Thanks! A little question about concurrency_hint: if I created pool with 10 of thread, and in each of them I launch boost::asio::io_service::run, and then if I set concurrency_hint to 20, or to 5, how many threads will use io_service?


Calculus 2: Integrate Fraction with x Variable in Numerator and Denominator

Question: I'm stuck on the following question:

Originally I thought about let u = 3x -17 and using substitution but that doesn't seem to take me anywhere.
What is the right approach to this problem?  I'm new to calculus so a step through would be greatly appreciated.
Answer: You can long divide:
$$
3x-17= 3(x-5)-2
$$
Then you find
$$
\int \dfrac{3x-17}{x-5} \;dx= \int 3 - \dfrac{2}{x-5} \;dx
$$
Or you could make the $u$-sub $u= x-5$ and use the fact that $x=u+5$:
$$
\int \dfrac{3x-17}{x-5} \;dx= \int \dfrac{3(u+5)-17}{u} \;du= \int \dfrac{3u-2}{u} \;du
$$
which you can see is equivalent to the other method from this final integral.


Why chrome.bookmark.getTree() not return value

Question: This function not work correctly. How to make work this function? How to determine execute context this function?
function getFolderIdByName() {
    var test;
    chrome.bookmarks.getTree(function(bookmarkTreeNodes) {
        test = 123;
    });
    console.log(test); \\ undefined
}

Answer: function getFolderIdByName() {
        var test;
        chrome.bookmarks.getTree(function(bookmarkTreeNodes) {
            test = 123;
        });
        console.log(test); \\ undefined
}

is an asynchronous function
So order of execution is

var test;
console.log(test);
chrome.bookmarks.getTree(function(bookmarkTreeNodes) {
                test = 123;
});

So console.log(test); is undefined.
Reference.

Chrome Asynchronous function
Comment: How I'm can return any value from this function.
Comment: @stevvik: **`return`** as in?


rails+jquery confirmation message

Question: i am updating record through jquery, and once data is updated how can one display success/failure message.
i have used following code to update data through jquery,
<code>var data = {user_id:userId, user_type:$("#userType").val()};
 var url = "<%= url_for(updateUser_path)%>";

$.get(url, data)
</code>
thanks,
Answer: Respond with json once you update data, and then process normally with jquery, for example:
<code>$.get(url, data, function(resp_data){
    if (resp_data.status == 'ok') {
       alert(resp_data.ok_msg)
    } else {
       ...
    }
    ...
}, 'json')
</code>
Answer: In addition to the answer about json, if you want to integrate more tightly with rails you should check out unobtrusive javascript, and use it in conjunction with a :remote => true form.

rails+jquery confirmation message


How to switch entire XCode project to previous commit

Question: I am using Git and SourceTree with my project. I want to switch the whole project to a previous commit to trace where I have introduced a bug. When I do so (using SourceTree) XCode no longer thinks my project is a valid iOS project.
The scheme changes from:

to:

and I can no longer build.
What is going on here? Is XCode keeping some additional state that is preventing me from being able to switch the whole project to a previous version?
Comment: Is git giving you any errors?
Comment: *"I can no longer build"*: Why not? What errors do you see?
Comment: Generally you should be able to switch between commits with no problem. In the old version, perhaps you do not have a deployment target or base SDK selected?
Answer: There is no bug you just need to recreate the schemes. Click on your target "MyRecipeIndex" -> "Manage Schemes" - delete everything -> "Autocreate schemes now". You should be able to build the project after that.
Comment: Yes, you are right. The autocreate schemes worked. But why do the schemes not persist when I switch between commits?


issue involving ptr record when sending email on digital ocean server

Question: The Issue
We have a website that sends email using php mail function and sendmail. We frequently get email rejected response emails from several destination email servers saying that we have an issue with our ptr record.
Current Environment:
The mx record for the websites domain name points to the google mail servers and works fine for sending and receiving mail in smtp/pop clients.
When doing a reverse lookup using nslookup the ip does not resolve to any domain name.
Note: There are multiple websites hosted on the same server using the same ip address, and the servers MAIN domain name is serv1.rhinoagile.com
BUT
but when the website uses sendmail to send out email we get the resposne mentioned above about the reverse dns issue.
My Question: Can I... ?
can I leave the mx records as they are and add a ptr record resolving the websites ip address to serv1.rhinoagile.com (because the IP is used for multiple sites, I don't want to have the ip reverse to any specific websites domain name)
Not an option...
Configuring the website to use smtp is not currently an option. It is not currently built into the cms platform, and I do not have approval to add the ability to use smtp to the cms at this time
How
If you are famillilar with digital ocean, It would be nice if you could also advise me on how to do it in their interface, otherwise I will just google it.
Answer: Classic first suggestion:
Make sendmail at the web host send outgoing email via another mail server (smart_host).
The relay server will be able to use properly configured PTR-A loop.
You may use mailertable to set direct or via relay delivery on per destination domain basis.
mailertable file:
# send directly to example.net and its subdomains
example.net   esmtp:%0
# send via smarthost.example.com messages to example.org
# [] are used to diable searching for MX records
example.org   esmtp:[smarthost.example.com]
# default route - may be used instead of default smart_host for all outgoig mail
.   esmtp:[smarthost.example.com]

Comment: I'm choosing this answer because it would have been a good solution for me. However I did end up getting approval for development time so I just added smtp abilities to the cms using swiftmailer (php)
Comment: If I understand correctly, I would configure it to send through googles email servers by configuring sendmail. **If** id do that then would the other websites on the server, whom do no not use google as their email provider, then fail to send?
Comment: The suggestion above would do the same email routing for all hosted domains. It possible to make sendmail route outgoing messages based on SENDER email address but treat it as the last resort option. 1) Can you define email sending program on per hosted www domain basis? 2) Can you run every www domain script as different OS user? [It is possible with apache but it is usually avoided]


Java not recognizing objects that are created in a loop, outside of the loop

Question:     String nameFromFile;
    String colorFromFile;
    int capacityFromFile;
    int currentCountFromFile;

    while(inputFile.hasNextLine()){
        nameFromFile = inputFile.next();
        colorFromFile = inputFile.next();
        capacityFromFile = inputFile.nextInt();
        currentCountFromFile = inputFile.nextInt();

        MarbleSackOwner owner1 = new MarbleSackOwner(nameFromFile, colorFromFile,
                                    capacityFromFile, currentCountFromFile);

        nameFromFile = inputFile.next();
        colorFromFile = inputFile.next();
        capacityFromFile = inputFile.nextInt();
        currentCountFromFile = inputFile.nextInt();

        MarbleSackOwner owner2 = new MarbleSackOwner(nameFromFile, colorFromFile,
                                    capacityFromFile, currentCountFromFile);

        nameFromFile = inputFile.next();
        colorFromFile = inputFile.next();
        capacityFromFile = inputFile.nextInt();
        currentCountFromFile = inputFile.nextInt();

        MarbleSackOwner owner3 = new MarbleSackOwner(nameFromFile, colorFromFile,
                                    capacityFromFile, currentCountFromFile);

        nameFromFile = inputFile.next();
        colorFromFile = inputFile.next();
        capacityFromFile = inputFile.nextInt();
        currentCountFromFile = inputFile.nextInt();

        MarbleSackOwner owner4 = new MarbleSackOwner(nameFromFile, colorFromFile,
                                    capacityFromFile, currentCountFromFile);

    }
    String output = "Owners after creaton based on file read \n";
    output += "Owner1: " + owner1 + "\n";
    output += "Owner2: " + owner2 + "\n";
    output += "Owner3: " + owner3 + "\n";
    output += "Owner4: " + owner4 + "\n";

    output += "owner1's name is " + owner1.getName() + "\n";
    output += "like I said, owner1 has " + owner1.howManyMarbles() +
                " marbles in his sack.\n";
    output += "So lets take one away from him.\n";
    owner1.removeMarbles(1);
    output += "so now we see that he has " + owner1.howManyMarbles() +
                " in his sack.\n";
    output += "so lets give the darn thing back to him now.\n";
    owner1.addMarbles(1);
    output += "so now we see that he has " + owner1.howManyMarbles() +
                " in his sack.\n";

    //mess with owner4
    output += "so, maybe " + owner4.getName() +
                " has lost a marble or two, so lets give him back one.\n";
    owner4.addMarbles(1);
    output += "So now we see that he has " + owner4.howManyMarbles() +
                " marbles in his sack.\n\n";

    //test class method
    output += "the owner with the most marbles is " +
                bigOwner(owner1, owner2, owner3, owner4);

    //results
    JOptionPane.showMessageDialog(null, output, TITLE_BAR, JOptionPane.INFORMATION_MESSAGE);

}//main

I am getting errors on every call to a owner object outside of the while loop saying "owner# cannot be resolved to a variable". if I declare the objects before the loop, I get a duplicate object error on the objects created within the loop. I'm not quite sure how to make this work.
Comment: Welcome to Stack Overflow. Please say *exactly* what the errors are - and ideally, try to cut your code down to *just* a minimal example demonstrating the problem. See http://stackoverflow.com/help/mcve for more information.
Comment: You need to have a read up on *variable scoping*. Your owner variables are out of scope outside your while loop.
Comment: added a declaration line for all of them outside of the loop and initialized them to null. seems to have fixed the problem now. thanks Jon.
Answer: You have declared and initialized your variables owner1, owner2, owner3 at the same time inside while loop. What you can do is, First declare and initialize the variable before (outside) loop and create owner objects within while loop like this:
MarbleSackOwner owner1 = null;
...
while(..){
...
owner1 = new MarbleSackOwner(nameFromFile, colorFromFile,
                                    capacityFromFile, currentCountFromFile);
...
}

Similarly do this action for other two owner variables. Read through scope of variables for better understanding.
http://www.java-made-easy.com/variable-scope.html
If you are going to create multiple owner objects then you can create a list object above your while loop and add the owner objects to that list and retriev the added objects from your list while printing the values.
Answer: If you want access to these variables in and out of the while, you need to declare them outside. In your case, these variables are know only inside the while cause that's where they have been declared. Try reading up on variable scopes.
Try something like this:
MarbleSackOwner owner1 = new MarbleSackOwner(string.Empty, string.Empty, 0, 0),
owner2 = new MarbleSackOwner(string.Empty, string.Empty, 0, 0),
owner3 = new MarbleSackOwner(string.Empty, string.Empty, 0, 0),
owner4 = new MarbleSackOwner(string.Empty, string.Empty, 0, 0);

while(inputFile.hasNextLine()){
        nameFromFile = inputFile.next();
        colorFromFile = inputFile.next();
        capacityFromFile = inputFile.nextInt();
        currentCountFromFile = inputFile.nextInt();

        owner1 = new MarbleSackOwner(nameFromFile, colorFromFile,
                                    capacityFromFile, currentCountFromFile);

        nameFromFile = inputFile.next();
        colorFromFile = inputFile.next();
        capacityFromFile = inputFile.nextInt();
        currentCountFromFile = inputFile.nextInt();

        owner2 = new MarbleSackOwner(nameFromFile, colorFromFile,
                                    capacityFromFile, currentCountFromFile);

        nameFromFile = inputFile.next();
        colorFromFile = inputFile.next();
        capacityFromFile = inputFile.nextInt();
        currentCountFromFile = inputFile.nextInt();

        owner3 = new MarbleSackOwner(nameFromFile, colorFromFile,
                                    capacityFromFile, currentCountFromFile);

        nameFromFile = inputFile.next();
        colorFromFile = inputFile.next();
        capacityFromFile = inputFile.nextInt();
        currentCountFromFile = inputFile.nextInt();

        owner4 = new MarbleSackOwner(nameFromFile, colorFromFile,
                                    capacityFromFile, currentCountFromFile);

    }


Gemius AMP Tag implementation GTM

Question: Is there a way to use an  gemius-tag in GTM?
The Gemius Tag is allowed in amp pages as a hardcoded tag , but i can't figure out how to implement it using GTM. There is no template available and there is no way of using custom html.
Answer: SOLVED:
Gemius does not provide a GTM Template and after further investigation do not intend to do so, because they simply do not trust Tag Managers.

Gemius AMP Tag implementation GTM


rebuild jcarousel in colorbox

Question: I have jcarousel, I create it by  drupal module print it in hidden(diplay:none)element("main-content" it work correctly here), then I create colorbox with that
   $('.quicktabs-views-group  .frame-colorbox').colorbox({
        html: function() {
              return $(this).siblings('.main-content').html();
               },
        width:'950px',
        rel: 'group_0',
        opacity : 0.8,
});

but jcarousel not work in colorbox,I know it because of geting html and put it in colorbox, what is solution,how can I have jcarousel in color box?
Answer: http://jsfiddle.net/v7g0vy2d/
$('#test').colorbox({
    html: $('.main-content').html(), // get carousel html

    onComplete:function(){   //Callback that fires right after
                             //loaded content is displayed.

        initCarusel()        //Calls a function that creates

    }
});

function initCarusel()
{
       $('.jcarousel').jcarousel();
       ...                  // rest of the code
}

Comment: I try that but not worked.
tnx for your attention, I do it by create jcarousel completely after load in color box

rebuild jcarousel in colorbox


Removing the Text Format selection

Question: Every textarea gives you an option to use either Filtered, Full, or Plain Text. Is there a way to remove or hide it so the layout becomes more streamlined? I'm using CKEditor if it means anything.
Answer: You can change who has permission to use which input format under Settings (Site Configuration) -> Input formats for Drupal 6 or Configuration -> Text formats for Drupal 7.
If you uncheck all the other options (I'm assuming the one with the editor is set as default) then the option won't appear for those users who only have the default checked.
That's at least one way.
Comment: But it appears that all roles must have access to Plain Text?
Comment: correct. See this workaround: http://drupal.stackexchange.com/questions/2031/how-to-disable-plain-text-for-a-specific-role
Answer: You can also use CSS to hide the select box.
Comment: that's what I did. For reference, add this css to your custom style sheet or use "css_injector" module: .filter-wrapper {
display: none;
}

Removing the Text Format selection


$T : R^n \rightarrow R^n$ is a linear map

Question:
Given $T : R^n \rightarrow R^n$ is a linear map.

Prove that there exists a real number $\alpha$ that the linear transformation $\alpha I - T$ is isomorphism.
Well, a good start is: I can say that $T$ is a linear map from $R^n \rightarrow R^n$ so the dimensions are equal, but it is still not enough. I need to show something else, like if $\alpha I - T$ is injective.
Ideas?
Answer: The eigenvalues of $T$ are invariant under a change of basis, so just choose $\alpha$ such that $\alpha$ is distinct from all the eigenvalues of $T$. Then $\alpha I - T$ is an isomorphism. Alternatively, $T$ is invertible if and only if its characteristic polynomial only has non-zero roots. Check that if $\alpha$ is distinct from the roots of the characteristic polynomial (i.e. distinct from the eigenvalues of $T$), then the characteristic polynomial of $\alpha I - T$ has no zero roots.
Answer: I will show that there is an ${\alpha}\neq0$ that $I-\alpha T$ is surjective and this is equivalent to main problem.
for ${\alpha}=0$  , $I-\alpha T$ is surjective. now if you change $\alpha$ contiously from zero to positive values then image of every point will move countinously in $\mathbb{R}^n$.
if you have point like $v$ then
$$d(v, (I-\alpha T)v)\leq \alpha ||T||\cdot|v|$$
that $||T||$ is norm of $T$ as a linear map.
now get a cube like $[0,1]^n$ and set $\alpha \leq \frac{1}{1000||T||}$. if for this $\alpha$ , $I-\alpha T$ not be surjective then its image should be of dimention less than or equal $n-1$. now of you find distance between vertices of cube and their image it should be a vertex that it's image should be greater than or equal $\frac{1}{2}$ but by the follow inequality this distance should be less than or equal $\frac{1}{1000}$.
Answer: Since the domain is the same as the codomain, saying that a linear map is not an isomorphism is equivalent to saying it's not injective.
We'll show by induction that, for all $k\ge1$, there exists a linearly independent set $\{v_1,\dots,v_k\}$ in $\mathbb{R}^n$, where $T(v_i)=\alpha_iv_i$, and the numbers $\alpha_i$ $(i=1,2,\dots,k)$ are pairwise distinct.
This is a contradiction, because a linearly independent set can contain at most $n$ elements.
By assumption, $0I-T$ is not injective, so there is $v_1\ne0$ such that $T(v_1)=0$. The set $\{v_1\}$ is linearly independent and $T(v_i)=0v_i$.
Suppose now we are given a linearly independent set $\{v_1,\dots,v_k\}$ with $T(v_i)=\alpha_iv_i$ and the numbers $\alpha_i$ $(i=1,2,\dots,k)$ are pairwise distinct. Choose $\alpha_{k+1}\ne\alpha_i$ $(i=1,2,\dots,k)$, which is possible because $\mathbb{R}$ is infinite. Since, by assumption, $\alpha_{k+1}I-T$ is not injective, there is $v_{k+1}\ne0$ such that $\alpha_{k+1}v_{k+1}=T(v_{k+1})$. I claim that $\{v_1,\dots,v_k,v_{k+1}\}$ is linearly independent.
Suppose $c_1v_1+\dots+c_kv_k+c_{k+1}v_{k+1}=0$. We have
$$
0=T(0)=T(c_1v_1+\dots+c_kv_k+c_{k+1}v_{k+1})=
c_1\alpha_1v_1+\dots+c_k\alpha_kv_k+c_{k+1}\alpha_{k+1}v_{k+1}
$$
but also
$$
0=\alpha_{k+1}(c_1v_1+\dots+c_kv_k+c_{k+1}v_{k+1})
$$
Subtract the two relations to get
$$
0=c_1(\alpha_1-\alpha_{k+1})v_1+\dots+c_k(\alpha_k-\alpha_{k+1})v_k
$$
that, by the induction hypothesis, implies
\begin{align}
&c_1(\alpha_1-\alpha_{k+1})=0\\
&c_2(\alpha_2-\alpha_{k+1})=0\\
&\vdots\\
&c_k(\alpha_k-\alpha_{k+1})=0
\end{align}
and, since $\alpha_i-\alpha_{k+1}\ne0$ $(i=1,\dots,k)$,
$$
c_1=c_2=\dots=c_k=0
$$
which in turn gives $c_{k+1}v_{k+1}=0$ and so $c_{k+1}=0$. Therefore $\{v_1,\dots,v_k,v_{k+1}\}$ is linearly independent, as claimed.
Note This is modelled on the proof that eigenvectors relative to distinct eigenvalues are linearly independent. However it doesn't require the theory of eigenvalues and eigenvectors.


Como criar função modular cujo parâmetro é um operador?

Question: Supomos que eu quero criar uma função que troque o src de uma imagem por outra no índice de uma array, assim:
var arrayimgs = ["js/img1.jpg","js/img2.jpg","js/img3.jpg"];
var imagem = document.getElementById('imagemslide');
imagem.src = arrayimgs[0];
var count = 0;

function rodarslider(){
    imagem.src = arrayimgs[count+1];
    count++;
}

A função acima faz mudar o src da imagem subindo o índice do array a cada clique. Isso funciona, mas e se eu quiser usar a mesma função para decrementar o índice e ao invés de ser count+1 e count++ ser count-1 e count--?
Eu só consegui criando duas funções porque o Firebug não reconhecia operador como argumento na chamada.
Comment: Por que não passa o "incremento" por parâmetro? Seja ele positivo ou negativo.
Comment: @Wakim Eu tentei mas não deu :/
Comment: Como está chamando sua função?
Comment: http://jsfiddle.net/fgquw9j3/
Answer: Realmente não tem muito como fazer da forma como você está planejando. Tem algumas opções:

Alguns programadores tem a cultura de criar duas funções como você fez.

Outros criam uma passando um parâmetro que indica qual o operador será usado. Mas note que você não está passando o operador em si e sim algum indicador de qual operador deve ser usado. O parâmetro será um valor numérico, string ou algo específico. Dentro da função haverá um if para decidir de acordo com o parâmetro qual o código a ser executado.

Dependendo do seu caso é possível não se preocupar com o operador e mandar a informação pronta para qualquer caso, ou seja, você resolve a questão antes de chamar a função. Você manda como parâmetro o incremento ou decremento pronto. De acordo com as regras matemáticas, "mais com mais" dá "mais" e "mais com menos" dá menos", portanto dentro da função você só usa a adição.

Uma outra possibilidade nada recomendada é usar eval() para resolver isto. No fundo é uma variação do segundo caso mas neste caso não usaria o if e sim montaria a expressão como string e executaria ela. Coloquei só para mostrar caminhos variados. Esta opção tem problemas de performance, legibilidade dependendo do caso e segurança.

Como notas adicionais você pode simplificar o código atual da função e deixando ele apenas com uma linha:
imagem.src = arrayimgs[++count];

Assim você incrementa o contador antes de usar como índice do array.
Outro problema é que não é ideal acessar uma variável de fora da função, que tem escopo global. Faça o certo e passe o count como parâmetro e retorne ele incrementado. Vai lhe poupar problemas no futuro. Faça o mesmo com arrayimgs e imagem. Se é que realmente estas variáveis precisam existir fora desta função.
Já pensou porque você precisa acessar imagemslide com a função getElementById('imagemslide'); e não acessa a variável direto? Você precisa minimizar a área de risco (este não é o único motivo para usar esta função). Desta forma poucas variáveis globais precisam ficar expostas. document é uma destas poucas variáveis.
Estado global de uma maneira geral é problemático. Casos como o document até faz algum sentido porque realmente é um objeto global para uma aplicação rodando em um navegador. Mesmo assim há quem diga que mesmo ela não deveria ser acessada de forma direta.
Provavelmente eu faria algo assim:
function rodarSlider(contador, rolagem) {
    var arrayimgs = ["js/img1.jpg","js/img2.jpg","js/img3.jpg"];
    var imagem = document.getElementById('imagemslide');
    imagem.src = arrayimgs[contador + rolagem];
    return contador;
}

algumContador = rodarSlider(algumContador, 1); //próximo
algumContador = rodarSlider(algumContador, -1); //anterior

Coloquei no GitHub para referência futura.
Seria algo assim porque na forma como está o seu código ele não parece fazer muito sentido.

Olhando o código que você postou depois no comentário me faz pensar que ter duas funções é a melhor solução neste caso. Dá para transformar em apenas uma função mas o código ficaria tão complicado que eu acho que não vale à pena. Duas funções ficaria mais legível.
Me parece que você está querendo economizar código à qualquer custo. Eu fiz muito isto quando estava aprendendo. E na época até fazia algum sentido, eu comecei programar em computador com 2KB de memória e qualquer byte economizado era fundamental mesmo em código que era interpretado. Mas com o tempo aprendi que legibilidade é melhor.
Claro que atentar ao princípio DRY é muito bom e ainda é um das coisas que mais busco. Mas demora para entender quando deve duplicar alguma coisa ou não. Às vezes duplicar melhora o código. E mesmo quando é melhor ter uma forma canônica isto precisa ser feito sem incorrer em outros erros com o uso de variáveis globais.
Usar funções auxiliares, mesmo que seja apenas para pegar uma valor de uma variável que guarda um valor de forma forma global (estado global), é uma da formas de canonizar um conhecimento da aplicação.
Comment: enquanto eu leio suas explicações eu não entendo nada. só quando eu vejo o exemplo, haha. de todo jeito vou arquivar as duas soluções. obrigado denovo man.
Comment: eu acho que deveria funcionar simplesmente passando o operador nos parenteses. deveria funcionar.
Comment: as variáveis são globais para serem usadas nas duas funções ou até em funções que eu possa fazer posteriormente.
Comment: è que você está começando, e está tentando fazer coisas um tento complexas. Tem que dar um passo de cada vez. Quando entender por completo os princípios da programação vai entender porque quase nenhuma linguagem permite passar um operador como parâmetro. É algo possível de fazer em uma linguagem, algumas fizeram, mas traz mais problemas que soluções. Não use variáveis globais. Eu nunca uso. Nunca! No máximo eu uso a mesma técnica do `getElementById`. Eu crio uma função que me retorna um valor que vou precisar em mais de um lugar. Isto é DRY seguro.
Comment: poderia iniciar chat?
Comment: tem como falar com vc inbox?


Content types are missing in Features

Question: I am trying to create a Features module and include my content types but not all of them are showing when I select "Content Types: node".  I am seeing about 80% of them.  Why would this be?
Answer: If you are using a distribution, etc., it may be the case that there are content types that are provided by another feature or custom module.  These will not appear in the Features UI by default in order to prevent conflicts.
Comment: Feature located.

Content types are missing in Features


Voice-crossing in First Species Counterpoint

Question:
In two-part counterpoint, is it okay for the counterpoint and cantus firmus voices to cross?

Transferred from: Few Questions on Counterpoint in the Tradition of Johan Fux
Answer:
Generally, contrary motion is favored over direct or similar motion.
  Contrary motion is typically more interesting, and in some cases
  facilitates easier voice leading.  In such cases, it is acceptable for
  the voices to cross.

Transferred from: Few Questions on Counterpoint in the Tradition of Johan Fux
Answer: If you're going specifically from Fux's teaching he states that you should try not to have the voices cross unless both voices are heading towards each other and they absolutely have to cross to avoid breaking other rules like parallel perfect consonants and diminished 5ths.
I take this from The Study of Counterpoint, written by Fux himself


JPA pagination for different methods

Question: Is it possible to implement pagination for any other method except findAll(pageable) ?
For example, if I have my own method like findByNameOrAge:
public interface JPAPersonDAO extends JpaRepository<Person, Long> {
  List<Person> findByNameOrAge(String name, int age);
}

Answer: yes it is possible .
Page<Person> findByNameOrAge(String name, int age,Pageable pageable);

Comment: Thank you very much for your answer. I did not know that I can use such constructor. This is exactly what I need.

JPA pagination for different methods


how to fix black video streaming on ios - kurento

Question: i have a video conference app built in nodejs and kurento.
when i connect my camera on desktop/Android everything is ok.
when i connect camera on iphone, i can see the shared video on iphone (locally) very well, but the camera on other devices (receiving devices) in the room stays black and doesn't show up.
my client code:

const videoConstraints = {};
videoConstraints.facingMode = 'environment';
const constraints = {
  video: videoConstraints,
  audio: false
};

receiveMediaLocal(token, 'webcam', socket.id, constraints)
setTimeout(() => {
  iKurentoClient.sendMessage({ ...data, type: 'video', mode: 'webcam', id:         'connectMedia' })
}, 100)

function receiveMediaLocal(sender, mode, connId, constraints, mediaScreen = null) {

        var participant = new Participant(this, sender, mode, connId);
        if (!this.participants[sender]) this.participants[sender] = {};
        this.participants[sender][mode] = participant;
        var media = participant.getMediaElement();
        var options = {
            localVideo: media,
            mediaConstraints: constraints,
            onicecandidate: participant.onIceCandidate.bind(participant)
        }

        participant.rtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendonly(options,
            function (error) {
                if (error) {
                    this.socket.emit("error",error);
                    return console.error(error);
                }
                this.generateOffer(participant.offerToReceiveMedia.bind(participant));
            }
        );
    }

how can i fix this bug?
thank you.
Comment: Same here! Have you solved this issue?
Answer: You need put this in your client html

While implementations of WebRTC in browsers are still evolving due to varying levels of support for WebRTC features, we can avoid issues with compatibility by making use of the Adapter.js library.


Forcedeth - too many iterations (6) in > nv_nic_irq

Question: I'm having trouble with an onboard nvidia gigabit network, under times of heavy load on the network, I'm seeing this error logged:
"too many iterations (6) in > nv_nic_irq"
I'm running Hadoop DFS over these NICs and I see checksum errors build up until the whole thing just fails.
I'm running the 2.6.26-2-amd64 kernel, and my initial research seems to imply its a problem with the forcedeth driver.
Has anyone run into this problem before?
Thanks in advance if anyone can help!
Ryan
Answer: Yes, that is apparently quite common.   This question is several weeks old so you probably already found the answer, but if not the fix seems to be to add:
max_interrupt_work=N
to modprobe.conf, as in:
<code>options forcedeth max_interrupt_work=15
</code>
Even with this change, I have still had some intermittent problems with forcedeth during large network transfers, but I never again received the error message you listed.


Python: how is it possible to convert a symbolic expression into a function so that it can be numerically integrated?

Question: I've been working with symbolic expressions in Python, and have arrived at one which I am wanting to integrate over a definite interval. The expression contains pi.
The trouble is that I have not been able to figure out how to convert this expression to a function which can be input as an argument to scipy.integrate.quad. The relevant parts of my code are as follows:
from sympy import *
import numpy as np
import scipy.integrate as integrate
from sympy.utilities.lambdify import lambdify

# this defines the symbols that
# we will be using in our computations:
x, y, g, y1, a0, a1, a2 = symbols('x y g y1 a0 a1 a2')

# this defines what a0 and a1,
# and what y and y' are:

a0 = 2
a1 = -((2/pi)+(pi*a2))

y = a0+a1*x+a2*x**2
y1 = y.diff(x)

# this defines the integrand that
# here represents the Lagrangian:

L=sqrt((1+y1**2)/(2*g*y))

# this differentiates the above with
# respect to a2, to define the integrand:

difL = L.diff(a2)

It is difL which I am wanting to integrate. I have tried defining it as a function in the following way:
def integrand(a2):
    return difL

f = lambdify(x, integrand(a2))

to no avail. So my question is: how can I convert difL into a function which can then be integrated using scipy.integrate.quad?
And, as a disclaimer, I am new to Python, so if I've been employing terms incorrectly, let me know.
Answer: You do not need scipy, sympy is perfectly capable of numerical integration. Now, you have a lot of variables you are not defining (e.g. g) so I'll construct an easier example, and let you adapt to your question.
from sympy import *
from sympy.abc import x, a

# x is variable, a is parameter
y = x**2 + a

# integrate over x from 0 to 1; then evaluate with the value of the parameter
integrate(y, (x, 0, 1)).evalf(subs={a: -4})

Comment: thank-you for your response. The trouble with this method is that the integral must be computed symbolically prior to substitutions of numeric values being made (I think). This takes up a lot of computation time. What I'm wanting to do is numerically integrate so as to save time... which I should have made clear. (My integrand is incredibly complex, and there may not even exist an analytic antiderivative to it.)
Comment: No, you get symbolic simplification, but not evaluation. There's a difference between `integrate(y, x)` (symbolic integration) vs `integrate(y, (x, x1, x2))` (numeric integration). And anyway, profile it :) At lunch now but I think you can get a function using `lambdify(difL.evalf(subs={a2:..., g:...})), i think, which you can give to scipy.
Comment: Back from lunch. Scratch that lambdify, there's something that errors out (even when I don't mess up the argument structure - should've been `lambdify(x, difL...)`). This works: `def f(xx): return difL.evalf(subs={a2:4, g:3, x:xx})`.
Comment: I ended up (and this seems to be working) defining a function `f = lambdify((x, a0, a1, a2, g), difL, 'numpy')`, and integrating that function using `scipy.integrate.quad`. I'm going to try your method now and see if it works better.
Comment: I guess you might be right; sympy's integrate takes ungodly time (I didn't have patience to wait it out).


How do I use a vue.js nested for loop over two arrays with a v-for

Question: This was resolved and my parent view and child component code are now correct and functioning  Using Vue.js, I'm attempting to iterate analogous to a nested for loop to render a matrix table display.  To achieve this I'm attempting to use a nested v-for loop but couldn't get it to work originally.
The data I'm using to build the table exists as a schedule of dates, each coming from a schedule collection in MongoDB.  For each given day all the teams play a match against another team.  The match data for each team lives in a schedule array in each document.
To pare down the approach and accomplish this I've created a schedule table of all the teams' schedules in the parent view, and passed it off as a property to the child component to streamline the v-for coding.
The traditional pattern for what I'm attempting to do in the child component is logically:
for(const i=0; i<schedules.length; i++) {
for(const j=0; j<weeks.length; j++) {
  console.log("This match is " + schedule[i] + " on " + week[j])

On the child component I've tried the following two strategies to no avail:
1.) Wrapping a v-for in a div:

        <sui-table-cell v-for="(number, i) in weeks" :key="i">
        {{schedules[schedule][i].team}}
        </sui-table-cell>

2.) Wrapping a v-for in a template (this code doesn't compile):
<template v-for="schedule in schedules">
        <sui-table-cell v-for="(number, i) in weeks" :key="i">
        {{schedules[schedule][i].team}}
        </sui-table-cell>
</template>

The data should look like so (if you click on the image you can see where I cannot get this to iterate):
Correct View Of Data
Parent view template.
<template>

ACL

      CRIBBAGE SCHEDULE

    <sui-table id="standings" class="celled table center aligned">
      <inner-table :weeks="totalWeeks" :allPlayers="allPlayers" />
    </sui-table>

</template>

Child Component:
<template>

    <sui-table-header>
      <sui-table-row>
        <sui-table-header-cell></sui-table-header-cell>
        <sui-table-header-cell>TEAMS</sui-table-header-cell>
        <sui-table-header-cell v-for="(number, i) in weeks" :key="i">WK{{i+1}}</sui-table-header-cell>
      </sui-table-row>
      <sui-table-row>
        <sui-table-cell></sui-table-cell>
        <sui-table-cell></sui-table-cell>
        <sui-table-cell v-for="(number, i) in weeks" :key="i">{{ number.gameDate.substring(0,10) }}</sui-table-cell>
      </sui-table-row>
    </sui-table-header>
    <sui-table-row v-for="(player, i) in allPlayers" :key="i">
      <sui-table-cell>{{i+1}}</sui-table-cell>
      <sui-table-cell>{{ player.player1 }}&{{player.player2}}</sui-table-cell>
      <sui-table-cell v-for="(week, j) in weeks" :key="j">{{player.schedule[j]}}</sui-table-cell>
    </sui-table-row>

</template>

Comment: `{{schedule[i].team}}` or `{{schedules[j][i].team}}` should work
Comment: it would be a bit more helpful if you shared a snippet of what was in `schedules` and `weeks`
Comment: Appreciate your feedback.  I've gone ahead and sent a snippet of that data to the images above.  Essentially they are both arrays, weeks is an array of 10 dates.  Schedules is a table containing rows for each team's matches on a given date.
Comment: I agree that schedules[j][i].team should work.  I cannot get this to iterate however.  The template option just repeats everything in one cell.
Answer: Vue uses key property to differ between components and prevent unnecessary rendering. So from your code :key="i", Vue understands that all sui-table-cell with key i are the same. That's why you've got repeats. You should provide unique keys to avoid this.
This code would do, however I would not recommend to use index as a key and provide some better keying strategy.
<sui-table-row v-for="(player, i) in allPlayers" :key="i">
      <sui-table-cell>{{i+1}}</sui-table-cell>
      <sui-table-cell>{{ player.player1 }}&{{player.player2}}</sui-table-cell>

        <sui-table-cell v-for="(number, i) in weeks" :key="`${j}_${i}`">
          {{schedules[j][i]}}
        </sui-table-cell>

</sui-table-row>

Sample data:
{
    schedules: [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],[2,3,4,5,6,7,8,9,1]]
    weeks: [1/1,1/7,1/14,1/21,1/28,2/5,2/12,2/19,2/25,3/3]
}

The solution with template, will not really work, because template part is never rendered, it is used when you want to use v-for, for multiple internal elements such as:
<template v-for="...">

</template>

Comment: Hi Alex, thanks for helping yesterday! I figured out the problem.  I had too many v-for's originally and it was throwing things off.  I've updated the code above with the solution, and popped a picture in there so you can see how it looks.
Comment: Thanks a lot for your reply.  I popped that div in there and got the following error:

[Vue warn]: Error in render: "TypeError: Cannot read property 'team' of undefined"

I fiddled with it a bit to see if I could troubleshoot it and it wasn't readily apparent what is happening:
Comment: Fixed, try now `weeks[j].team`
Comment: Thanks again Alex, I tried it even though it looks exactly the same as what you told me to do previously:)  Same results...
Comment: Well, with some data it is better :) Try now
Comment: I changed the sample data to actually represent my data.  I've also modified my code that creates the schedules table to remove id, and just make it a simple array rather than an array of objects.  Now this renders more closely to what I need based on your input.  However, it puts all the data into the first column and repeats for all schedules into that column.  I've pasted a screenshot of what I'm talking about in my list of screenshots.  It's called "new screenshot".
Comment: Mind doing a codepen? You can start with this one https://codepen.io/alexbrohshtut/pen/oNXMYXz
Comment: I got one set up that illustrates what I'm attempting to do.  However, it does not have the stylesheet from semantic ui vue, nor the js.  Not sure how to add it.  The CDN links for the js and the css are at:  and , respectively.  My pen is at: https://codepen.io/AdamFHelm/pen/zYGLoaB
Note what happens when this code actually runs in the screenshot above in my initial outline, "new screenshot"
Comment: It is about semantic, try to do hard-coded html of whatever you need and then wrap it in v-for, I am not sure about how your inner table behave.
Comment: Great to hear that you did it! :)


How does string age affect intonation?

Question: I had a recent issue with my high e string where the saddle was adjusted as short as possible but the twelfth fret was still very flat. I read online that a new set of strings may fix this, and that turned out to be a perfect solution. My question now is, from a physical standpoint, why does string age affect intonation? I can understand why old strings won't hold their tuning as long, but I don't understand how age can throw a strings intonation off.
Comment: @Tetsujin Good point; aside from chemical corrosion, I wouldn't expect strings *that don't get played on* to go false just from age alone. But if it's true that the problem is from actual mechanical damage or deformity, then it makes sense that more "vigorous" technique might make them die sooner (though I don't know about "in an afternoon"!)
Comment: What was the string made of?
Comment: Nickel I reckon. The strings were on the guitar when I bought it. Standard electric guitar strings.
Comment: This is just a suspicion, so I won't put it as an answer yet:  As strings age, they stretch.  As they stretch, they become thinner.  Note that the lighter gauge strings have the saddle set shorter than the heavier gauge strings of the same type, though some of that has to do with the height of the action.
Comment: I would claim age in itself does not cause any intonation change. Crud buildup from grubby or sweaty hands does. There's also the bizarre, yet as far I I'm aware untested pseudo-science that one person can kill strings in days while another can keep playing them forever without them going "bad". I used to know a guy who, if you lent him your guitar for an afternoon, within days the strings would need changing. I've known lesser versions of this across many players. Some of my guitars have 15-year-old strings & no intonation or tuning issues [I like mellow on some ;)
Comment: I'd go so far as to say [with no real citation] that any change in density - adding crud or wearing away on frets - is going to create the issue [though possibly in opposite directions]
Comment: For context the strings were at least a year old, as they were on the guitar when purchased.
Comment: 1) A year is an awfully long time to stick with the same set of strings (it seems to me like guitarists who play regularly love to change strings every week or two; you're lucky they're so affordable compared to bowed-strings strings!). 2) If they were on the instrument when you bought it, and it was out in a music shop, you don't know how much use they got before you bought it. I'd say it's a miracle they lasted a year! (Though all this with the same disclaimer that it's not really *time* in the abstract, but how much use they get.)
Comment: @AndyBonner - just to play devil's advocate. On my Rikki bass when I used to play it all the time, I'd change strings every couple of weeks to keep the 'twang' in. My Strats, however, I don't like the sound until the strings have had at least a month to stop being so damn bright.
Answer: I've been curious about this too. I imagine this is the same phenomenon that violinists refer to as a string "going false." The effect is the location of pitches becomes inconsistent along the length of the string, especially noticeable on a fretless instrument; i.e. if you tried to play, on two strings, a pitch a perfect fourth higher than the open string, the placement would have to be slightly different on the two strings (which is of course impossible with frets). I've also noticed, especially with an unwound wire string like the violin's high E, that plucking a false string can produce "two pitches," as if an E and another slightly detuned E were being played at the same time.
This page simply says "A 'false' string is one with uneven thickness and mass along its length." It suggests that it involves the "flattening" of the round cross-section of the string. This discussion thread is rambly and largely speculative, but I imagine much of that speculation is true, that it also involves changes to the elasticity of the metal. The fact is, for a wound string, there are so many parts that there could be a lot of factors. The string's core is perhaps a number of braided steel wires, which could become inconsistent in thickness, shape, or elasticity, and the winding could become deformed or perhaps have its "coils" spread apart or together.
Of course, if the new strings hadn't solved the problems, there could be other suspects as well. The wood of fretboards wears grooves between the frets over time, and frets themselves could become worn and be inconsistent from one string to another.

I can understand why old strings won't hold their tuning as long...

Actually, I would expect (and find, in practice) the opposite. New strings always have a "break-in period" during which they stretch and have to be retuned regularly (the period varies in length and intensity depending on the material), but once they've "settled in," they generally hold their pitch quite well (unless maybe eventually some mechanical flaw like we've been discussing impacts their stability).
Answer: tl,dr: Finger gunk.
It's the same reason why strings become dull over time. When playing. the oil, sweat and salt from your fingers interacts with the string and results in corrosion and accumulation.
This is more pronounced where you fret the most and this results in an uneven mass distribution and the center of gravity moves slightly away from the 12th fret. Hence it's out of intonation.
Comment: If you observe the 12th fret tone to be flat compared to the 0th flat, then the finger gunk theory would mean that more finger gunk accumulates in the upper half of the string than in the lower half.  As the left hand contributes more finger gunk than the right hand does, this would suggest that a lot of the playing was happening above the octave (which would strike me as unusual playing style).  So the outcome, a flat octave, would be a slightly unexpected consequence of finger gunk accumulation.
Comment: The finger gunk theory is testable.  Soak your strings in ethanol for 24 hours and see what happens with finger gunk gone.
Comment: @JirkaHanika, I suspect the physics is much more complex. Presumably, the effect of finger gunk is to cause differentials in dampening and tension across the length of a single string. Those effects probably interact with string use, such that higher use + finger gunk impacts the string differently than lower use + finger gunk. Another element to consider is the cumulative effect of many spots where the strings are degraded. I feel like the math would need to be worked out to show that this would *always* produce flatness in every instance. Soaking in ethanol won't reverse permanent damage.
Comment: @jdjazz - That's the point.  Cleaning the string lets you separate wear effects from gunk effects.  What will be the finding?  I don't know.  I do get your point about dampening versus weight.  Perhaps not about tension though, tension has to be constant even on an unevenly gunky string.
Comment: @JirkaHanika maybe I'm not familiar enough with the gunk theory. I thought it was proposing a mechanism that causes the wear on the strings. The physics is starting to go beyond my knowledge, but I thought the tension isn't constant (1) if the string has kinks, (2) if there's an applied force on the string (not really relevant in this scenario), (3) or if the string is accelerating different masses along the length. Without a ton of direct knowledge, I'd guess that the 3rd is most relevant here, since each bit of string is accelerating as it vibrates, and those bits can have different masses.
Comment: @JirkaHanika, in other words, I thought the final instance of differential tension along the string would arise when a string of non-constant density/ mass is accelerating (eg vibrating and producing sound).
Comment: @jdjazz - Our fingers are covered with keratin, oiled with sebum.  As new skin and nails grow, this substance (keratin dust soaked in sebum) sticks to what we touch.  A good place to look for the substance is under one's nails or along very old, never cleaned strings.  One potential effect of this is that the dirty part of the string could become heavier than the cleaner part.  Another effect could perhaps be some kind of a dampening effect, although I don't subscribe to that.  Tension isn't affected by kinks or material or even by the weight.  Ethanol dissolves sebum a keratin dust drops out.
Comment: @JirkaHanika, thanks for the background on finger gunk! I wonder if you're thinking only of massless strings? If a string has mass, simply hanging it vertically will produce more tension at the top than the bottom of the string. If there are differences in linear mass density along the length, then different parts of the string will undergo different accelerations when the same force is applied. To me, it seems like this would impact the vibrational frequencies in complex ways. See, for ex, [here](https://physics.stackexchange.com/a/156417) & [here](https://physics.stackexchange.com/a/460519).
Comment: @jdjazz - The physics of a vibrating string is indeed more complicated.  You can look at a vibrating horizontal guitar string to see the proportions of the forces: the vertical [restoring force](https://en.wikipedia.org/wiki/Restoring_force) is way bigger than the gravitational deformation (as the midpoint goes about as high above the horizontal as below it), but also much smaller than the horizontal tension.  And of course I'm talking about massive strings with potentially massive gunk.  A massless string has an infinitely high pitch and so it can't be heard.
Answer: Probably the already given answers are also right, in the sense that the mentioned factor physically modify the harmonic response of the string.
But I think soaking in ethanol for 24 hours will not make the string new, because of a physical phenomenon called "fatigue", that I guess plays the main role here.
As you know every material have his own elastic constant E (young modulus), in the case of steel it is around E=210 GPa.
The fatigue is a phenomenon that ""make the material weaker"" when the same point of material is subjected repeatedly to many cycles of the same load.
https://en.wikipedia.org/wiki/Fatigue_(material)
You can see that e.g. the "main" LA string goes 440 Hz (around? sorry i'm just half musician), so it does 880 cycles from minimum tension to max every second that it vibrate.
Every material have its own characteristic number of allowed cycles before suffering of fatigue (see Whaler function). From this number you can compute by simple division the number of seconds that the string can vibrate before suffering of fatigue.
This phenomenon modify the value of this Young coefficient E (and also others like Poisson coeff., more complicated, just doesn't matter, but the idea is the same).
But as you know the vibrating string doesn't have the same tension everywhere:
every harmonic have his own wavelength. Assuming the string is vibrating sinusoidally, in a full period we have one max and one min points (the one with horizontal tangent line, i.e. derivative 0, for those who knows a bit of math)
and those points will be the most strained ones. Instead, the nodes of the mode will be less strained ( this because the differential equation of the vibrating string is
Yxx=k*Ytt where k basically is modified by tuning. xx and tt are partial derivations). https://en.wikipedia.org/wiki/Normal_mode
To conclude, the string will fatigue not in a constant way, but differently in every point. If you add this to all imperfections (like that touching the string non uniformly will consume it non uniformly for example), after a while the string doesn't perform as new.

How does string age affect intonation?


Why is the last relation a function of $\eta$ and not a constant?

Question: In my notes there is the following:
$$U_{\xi \eta}(\xi, \eta)=0 \Rightarrow \frac{\partial}{\partial{\eta}} \left (\frac{\partial}{\partial{\xi}} U \right )=0 \\ \Rightarrow U_{\xi}(\xi, \eta)=a(\xi) \\ \Rightarrow \frac{\partial}{\partial{\xi}}\left (U(\xi, \eta)\right )=\frac{\partial}{\partial{\xi}}\left (\int_0^{\xi}a(s)ds\right ) \\ \Rightarrow \frac{\partial}{\partial{\xi}}\left (U(\xi, \eta)-\int_0^{\xi}a(s)ds\right )=0 \\ \Rightarrow U(\xi, \eta)-\int_0^{\xi}a(s)ds=B(\eta)$$
Why is the last relation a function of $\eta$ and not a constant??
Comment: can you see that  $u_{xy} = 0$ iff $u = f(x) + g(y).$ assume all the smoothness on $u, f, g?$
Comment: I see... Thanks!!! :-) @abel
$$$$
I am looking at the problem $$u_{tt}(x, t)-u_{xt}(x, t)=0 \\ u(x, 0)=f(x) \\ u_t(x, 0)=g(x)$$

Does it stand that $$u_{xt}=u_{tx}$$ ??
Comment: yes. for smooth functions $u_{tx} = u_{xt}.$  but here you have more: $0=\frac{\partial}{\partial t} (u_t - u_x) = u_{tt} - u_{xt}$  so $u_t - u_x = g(x) - f(x).$
Comment: So is $u$ a smooth function?? @abel
Comment: you have $u$ at least twice differentiable; or you will not be able to write $u_{tt} - u_{xt} = 0.$ it is true that $u_{xt} = u_{tx}.$
Comment: So that this equlaity holds it should stand that $$u \in C^{2,2}$$ right?? @abel
Comment: yes, i think so.
Comment: Do I have to write at the beginning "We assume that $u \in C^{2,2}$. ?? Or do I not have to ?? @abel
Comment: it is ok to write $u \in C^{2,2}$
Comment: Can we say: "Because $u \in C^{2,2}$ we have that $u_{xt}=u_{tx}$." ?? @abel
Comment: yes. it should be fine.
Comment: Ok... Thank you!!! :-) @abel
Answer: Because just the derivative with respect to $\xi$ must be zero (according to the second last line) and this is true even if $B$ depends on $\eta$:
$$ \frac{\partial}{\partial{\xi}}\left (U(\xi, \eta)-\int_0^{\xi}a(s)ds\right ) = \frac{\partial}{\partial \xi} B(\eta) = 0.$$
The same argument was already used in the second line.
Comment: Yes, this usually holds. Formally it depends on your requirements on $u$: If you just ask for second derivatives of $u$ to exist, it is not a priori clear that you can exchange their order. If you require $u \in C^2$ (i.e. also continuity of the second derivatives), which one usually does, you can apply [Schwartz' theorem](http://en.wikipedia.org/wiki/Symmetry_of_second_derivatives#Schwarz.27_theorem) to exchange the order.
Comment: If you want to be formal you have to assume $u \in C^2$, which is not an unreasonable requirement at all. If you can show uniqueness of the original pde and you can construct a $C^2$ solution of the $u_{tx}$-version you have shown that this is no assumption at all.
Comment: I understand... Thank you!!! :-)
$$$$

I am looking at the problem $$u_{tt}(x, t)-u_{xt}(x, t)=0 \\ u(x, 0)=f(x) \\ u_t(x, 0)=g(x)$$

Does it stand that $$u_{xt}=u_{tx}$$ ??
Comment: Do I have to write that we assume that $u \in C^{2,2}$ or is it known?? @Three.OneFour
Comment: Ok... Thank you!!! :-) @Three.OneFour


BMO2 1994 Question 3

Question: $AP, AQ, AR, AS$ are chords of a given circle with the property that $\angle PAQ = \angle QAR = \angle RAS$. Prove that $AR(AP+AR) = AQ(AQ+AS)$.
This was question 3 of the 1994 BMO2 (https://bmos.ukmt.org.uk/home/bmo2-1994.pdf). I can't seem to get a grip on the problem. Can anyone help me out by providing a starting point?
Answer: First of all consider $PAQ$ and $QAR$. We could get that : $AQ^2 + AR^2 -2AQ \cdot AR\cdot cos\alpha = AP^2 + AQ^2 -2AP \cdot AQ \cdot cos\alpha$, so $cos\alpha = \frac{AP + AR}{2AQ}$. And find the same angle in $RAS$ and $RAQ$ triangles we will have : $\frac{AP + AR}{2AQ} = \frac{AS + AQ}{2AR}$. That give us $AR(AR + AP) = AQ(AQ + AS)$
Comment: $\alpha$ is our equals angle.

BMO2 1994 Question 3


Chordal Analysis of Christian Petzold's Minuet in G (formerly attributed to J.S. Bach)

Question: The piece I am asking about is the well-known minuet that was originally attributed to J.S. Bach but has since been re-attributed to lesser-known composer, Christian Petzold.
My question concerns harmonic analysis: in measure fifteen, can beats two and three be considered as implying a I6/4 chord?
The page discussing the re-attribution can be found here.
The score can be found here.
Comment: PDF of score on muse score: http://static.musescore.com/52405/a8eec6ad1b/score.pdf
Comment: Current form looks good, I'll reopen and clean up comments.
Answer: My original response was put in a comment, but as the question has now been reopened, I'll post the answer here:
The passage in question does not imply a I6/4 chord. It outlines a V chord. The "B" on beat two is an upper-neighboring tone and the "G" on beat three is a passing tone - what could be seen as a 4-3 suspension.
Also, an analysis of I6/4 is incomplete as the cadence actually occurs on the downbeat of the following measure, and cadences do not occur in weird or asymmetric configurations at this point in music history.
Hope that helps.