Strange behaviour with a wiggle animation of a pill shaped UIButton

Question: My view has a UIButton which is pill shaped by setting the corner radius to half the view height. All good, but when its animated (wiggle by rotating), the corner radius seems to change, deforming the pill shape. When the animation ends all returns to normal:
Normal appearance:

Animating appearance (see corner radius):

A recording of this is shown here:
https://www.dropbox.com/s/xoowpfzdf0ijuql/Simulator%20Screen%20Recording%20-%20iPhone%2012%20-%202021-10-08%20at%2015.05.14.mp4?dl=0
The animation code (Xamarin c#) looks like:
public static void Wiggle(UIView view, double duration = 0.1f, float repeatCount = 3.0f)
{
    UIView.Animate(duration,
        () => view.Transform = CGAffineTransform.MakeRotation((nfloat)(-5f * Math.PI / 180f)),
        () =>
        {
            UIView.AnimateNotify(duration, 0.0f, UIViewAnimationOptions.Repeat | UIViewAnimationOptions.Autoreverse | UIViewAnimationOptions.AllowUserInteraction,
                () =>
                {
                    UIView.SetAnimationRepeatCount(repeatCount);
                    view.Transform = CGAffineTransform.MakeRotation((nfloat)(5f * Math.PI / 180f));
                },
                (animationFinished) =>
                {
                    UIView.Animate(duration, 0, UIViewAnimationOptions.AllowUserInteraction,
                        () => { view.Transform = CGAffineTransform.MakeIdentity(); }, null);
                });
        });
}

As seen in the video it does not happen always. Sometimes the pill shape remains. It happens on both simulator and real device. Any clues? Thanks
Answer: You don't show your "PillShape" code, but I'm assuming you are "setting the corner radius to half the view height" in LayoutSubviews()?
If so, the problem is likely that as you rotate the button its height is changing, and you no longer have a correct radius.
You may be better off using Layer animation, rather than rotating the view itself.
I don't use Xamarin / C#, so this is based off Objective-C code... hopefully it will get you on your way.
This uses a slow (0.5-second) animation to make it easy to see that the radius does not change during rotation. Tap the button to start/stop the animation:
using Foundation;
using System;
using UIKit;
using CoreAnimation;
using ObjCRuntime;

namespace QuickTestApp
{
    public partial class ViewController : UIViewController
    {
        public WigglePillButton btn { get; private set; }
        public bool isWiggling { get; private set; }

        public ViewController(IntPtr handle) : base(handle)
        {
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            // Perform any additional setup after loading the view, typically from a nib.

            btn = new WigglePillButton();
            btn.TranslatesAutoresizingMaskIntoConstraints = false;

            btn.SetTitle("Testing", UIControlState.Normal);
            btn.BackgroundColor = UIColor.SystemBlueColor;

            View.AddSubview(btn);

            // Get the parent view's layout
            var margins = View.SafeAreaLayoutGuide;

            btn.CenterXAnchor.ConstraintEqualTo(margins.CenterXAnchor).Active = true;
            btn.CenterYAnchor.ConstraintEqualTo(margins.CenterYAnchor).Active = true;
            btn.WidthAnchor.ConstraintEqualTo(120).Active = true;

            btn.AddTarget(this, new Selector("ButtonClickAction:"), UIControlEvent.TouchUpInside);

            isWiggling = false;
        }

        [Export("ButtonClickAction:")]
        public void ButtonClickAction(UIButton sender)
        {
            if (isWiggling)
            {
                btn.StopAnim();
            } else {
                btn.StartAnim();
            }
            isWiggling = !isWiggling;
        }

        public override void DidReceiveMemoryWarning()
        {
            base.DidReceiveMemoryWarning();
            // Release any cached data, images, etc that aren't in use.
        }
    }

    public class WigglePillButton : UIButton
    {
        public override void LayoutSubviews()
        {
            base.LayoutSubviews();
            var maskingShapeLayer = new CAShapeLayer()
            {
                Path = UIBezierPath.FromRoundedRect(Bounds, 12).CGPath
            };
            Layer.Mask = maskingShapeLayer;
        }

        public void StartAnim()
        {
            AddAnimations();

        }

        public void StopAnim()
        {
            Layer.RemoveAllAnimations();

        }

        private void AddAnimations()
        {
            CATransaction.Begin();

            Layer.AddAnimation(RotAnim(), "rot");

            CATransaction.Commit();

        }

        private CAKeyFrameAnimation RotAnim()
        {
            CAKeyFrameAnimation animation = CAKeyFrameAnimation.FromKeyPath("transform.rotation.z");
            double angle = 5f * Math.PI / 180f;
            animation.Values = new[] { NSNumber.FromDouble(angle), NSNumber.FromDouble(-angle) };
            animation.AutoReverses = true;
            animation.Duration = 0.5;
            animation.RepeatCount = float.PositiveInfinity;
            return animation;
        }

    }
}

Comment: To create the pill shaped button I was setting the UIButton's Layer.CornerRadius to half the button's height with code like:  button.Layer.CornerRadius = button.Frame.Height / 2; in the parent's view ViewDidLayoutSubviews() (so no subclassing of UIButton which would be better). By using your maskingShapeLayer, the animation now looks good! Thanks!


Como coletar texto quando não tem classe HTML de referência

Question: Estou tentando puxar os dados desse código da imagem. O que me interessa é a leta I onde está marcado de vermelho.
Já tentei dessa forma abaixo, mas não deu certo:
url = 'https://blaze.com/pt/games/football-studio'
html_page = requests.get(url)
html_source = html_page.text
soup = BeautifulSoup(html_source, 'html.parser')
dados_site = soup.find_all('text')
print(dados_site)
inserir a descrição da imagem aqui
Answer: BeautifulSoup tem suporte de seleção em CSS - use um metodos select() ou select_one():
soup = BeautifulSoup(html, 'html.parser')
elements = soup.select("#left-container > div.left-content > div > div > ul")

Certifique-se de usar a versão 4.7.0 ou superior para ter suporte para a maioria dos seletores CSS4.
Answer: Eu não sei em Python, mas se for em JS você pode usar a função querySelector
document.querySelector('g text');

a função querySelector como o nome já informa serve para selecionar um parametro. no caso acima eu selecionei o pai e o filho, então retornará o campo que você está querendo.
Também pode ser usado o querySelectorAll() que seleciona todos os elementos com esses parametros.
Comment: Vou fazer o teste e te falo se conseguir. Obrigado!!
Comment: Porque do menos -1 ?
Comment: cliquei errado.
Comment: É possível fazer essa coleta de dados usando o Python?


How-to install docker-compose on al2023

Question: The docker documentation states the compose plugin is installed automatically with the latest docker version.
I built a new EC2 instance running al2023 and installed docker. But received this error:
<code>$ docker compose --help
docker: 'compose' is not a docker command.
$ docker --version
Docker version 24.0.5, build ced0996
</code>
I'm guessing this could be a simple version problem.
Answer: I looked around for a while before finally tracking this down.
It's here for anyone who finds themselves in the same boat.
The plugin was not installed along with docker.  Here is a one-liner:
<code>sudo curl -L https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s | tr '[:upper:]' '[:lower:]')-$(uname -m) -o /usr/bin/docker-compose && sudo chmod 755 /usr/bin/docker-compose && docker-compose --version.
</code>
Comment: This should really be a part of AL2023

How-to install docker-compose on al2023


cfdisk quits with a fatal error in regards to the partition table

Question: fresh install. 'cfdisk /dev/sda' gives the following output:
"FATAL ERROR: Bad primary partition 2: Partition ends in the final partial cylinder"
what could be the reason for this to happen and what might be the solution?
this is the output of 'fdisk -ucl /dev/sda':
Disk /dev/sda: 61.5 GB, 61492838400 bytes 255 heads, 63 sectors/track, 7476 cylinders, total 120103200 sectors Units = sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x00030933

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1            2048     3905535     1951744   82  Linux swap / Solaris
/dev/sda2   *     3905536     5859327      976896   83  Linux
/dev/sda3         5859328   120102911    57121792   83  Linux

Comment: Does the machine boot properly?
Comment: yes, it does...
Answer: This is a known cfdisk bug, already fixed by some reports.  Partitions haven't needed to be aligned to track boundaries for almost two decades, if indeed ever at all; and most modern partition table utilities don't perform such alignment.  (Microsoft stopped doing it in its utilities, to much fanfare, several years ago.)
But cfdisk was checking that they were track-aligned anyway, and complaining (with a fatal error that need not have been fatal) if they weren't.  cfdisk clearly wasn't what your installation program used to partition the disc.  Partition tables created with tools that have dropped this nonsense track-alignment idea will of course give cfdisk cause for complaint, and that's what has clearly happened here.
Local fix: Don't use cfdisk.  Use gparted or parted or some such.  (As Rod Smith explains, they don't share a common codebase with the fdisk family, and so won't share this bug.)  Or bite the bullet and use GPT fdisk to switch to the EFI partition table format, which has none of this cylinders/heads/sectors residue at all.
Temporary and service fix: Get the fixed cfdisk from your operating system vendor.
Further reading

Jonathan de Boyne Pollard (2011). The gen on disc partition alignment..  Frequently Given Answers.


Guide for Building Audio Units in Xcode 5 on OSX 10.9

Question: I started reading the apple developer documentation for audio units here, but I realized that the docs are very outdated and there appears to be no audio unit template available in xcode 5. I looked for quite some time yesterday and today for an up-to-date guide on building audio units, but to no avail. If anyone has a guide for building audio units in xcode 5 on OSX 10.9 I would be eternally grateful. Even better, if someone knows how to get the old audio unit templates into xcode 5, that would be really helpful.
Answer: The best resource I've found is Adamson and Avila's book.
Highly recommended. You may need to tweak the code a bit to work in Xcode 5 but it shouldn't be too much work.


How can I combine two sql with not exists?

Question: I doubt it can be right to solve.
test_table:
id       |  name   |  value  |  date
---------|---------|---------|------------
1        |  john   |    32   |  2016-01-08
2        |  tom    |    590  |  2016-01-03
3        |  king   |    1903 |  2016-01-01
4        |  john   |    490  |  2016-01-02
5        |  gary   |    58   |  2016-01-18
6        |  cat    |    5    |  2016-01-10

sql1:
select name,sum(value) as val from test_table where val > 500 group by name;

sql2:
select name from test_table where  date >= DATE_SUB(CURDATE(),INTERVAL 1 WEEK) group by name;

I want combine two sql in one. The sql result name is not exists in sql2 name  result  collection.
update:
sorry for my confused describe.
The sql1 is scan whole the table, it aim to find out who's total value is greater than 500.
The sql2 is scan last week's data to find out who exists last week.
So, I Want combine two sql , to find out those people who's total value is greater than 500 but not exists last week.
sorry again for my poor English.
update - add example:
just like the table content,the result should be :
john,tom,king
because their total value is > 500,but not update last week
But how can I do it.
Thanks all.
Comment: what you are trying to say in this line -> The sql result name is not exists in sql2 name result collection.?
Comment: @VigneswaranS it means the sql result is not exists in sql2 result.I want to find out who not update lastweek but his value is greater than 500. Thank you,The problem describe already update
Answer: SELECT name, sum(value)
FROM test_table
WHERE value > 500
AND name NOT IN (
    SELECT name
    FROM test_table
    WHERE `date` >= DATE_SUB(CURDATE(), INTERVAL 1 WEEK)
)
GROUP BY 1

OR
SELECT name, sum(value)
FROM test_table
WHERE value > 500
GROUP BY 1
HAVING max(`date') < DATE_SUB(CURDATE(), INTERVAL 1 WEEK)

If you are trying to having sum(value) > 500, delete above lines
WHERE value > 500

And change AND to WHERE for the first SQL
And add this line at end of each of above:
having sum(value) > 500

Comment: Thank you for answer , but your sql result is to find out  the user who's value greater than 500 before last week. but i just want to find out who exists before last week.
Comment: I have simplified your question, i think my solution is exactly same as your requested
Comment: I add the example just now, for my table content,the result should be john,tom,king,but your sql result is just tom and king.so, I want who not update last week , not who last week value > 500 and not update.
Comment: because in your original SQL you said : where value > 500 , i thought you ignore any value <=500. are you actually try to say: sum(value)>500 ?
Comment: I just see that,sorry for my careless,and thank you for perfect solution,
Answer: It is really helpful to describe what you want, as well as providing SQL samples.  You seem to want the sum of values greater than 500 for names that have no row with date in the past week.
If so:
select name, sum(case when value > 500 then value else 0 end)
from test_table
where value > 500
group by name
having max(date) < DATE_SUB(CURDATE(), INTERVAL 1 WEEK) ;


Why won't my fieldtype plugin save the settings form values?

Question: I have a custom field. The FieldType plugin provides a settings form that adds a field to the form. The field is a group of checkboxes...think the paragraph types selection when adding a entity revisions field to a content type.
The form displays correctly. Two of the checkboxes are checked by default correctly. But the values don't get saved.
I've put a breakpoint where the settings are retrieved:
   $def = $items->getFieldDefinition();
   return $def->getSetting('allowed_schemes') ?? UrlItem::getSchemes();

which returns null, as does $def->getSettings(). I've also put a breakpoint in FieldItemBase where it retrieves the settings...also null.
It might have something to do with the schema method. I haven't figured out yet what I need to put there.
Here is my plugin.
<?php

namespace Drupal\url_text\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Defines the 'url' entity field type.
 *
 * @FieldType(
 *   id = "url",
 *   label = @Translation("URL"),
 *   description = @Translation("A field containing a plain string URL value."),
 *   category = @Translation("General"),
 *   default_widget = "url_textfield",
 *   default_formatter = "url"
 * )
 */
class UrlItem extends FieldItemBase {

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition): array {
    return [
      'columns' => [
        'value' => [
          'type' => $field_definition->getSetting('is_ascii') === TRUE ? 'varchar_ascii' : 'varchar',
          'length' => (int) $field_definition->getSetting('max_length'),
          'binary' => $field_definition->getSetting('case_sensitive'),
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty(): bool {
    $value = $this->getValue();
    return empty($value['value']);
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition): array {

    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function fieldSettingsForm(array $form, FormStateInterface $form_state): array {

    $settings = $this->getSettings();

    $element['allowed_schemes'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Allowed Schemes'),
      '#options' => $this->getSchemes(),
      '#default_value' => $settings['allowed_schemes'] ?? ['http', 'https'],
      '#description' => $this->t('Allowed URL schemes for the URL. If none are selected, then all are allowed.'),
    ];

    return $element;
  }

  /**
   * Provide an array of URL schemes to allow.
   */
  public static function getSchemes(): array {

    return [
      'http' => 'http://',
      'https' => 'https://',
      'ftp' => 'ftp://',
      'mailto' => 'mailto://',
      'sftp' => 'sftp://',
      'ssh' => 'ssh://',
      'tel' => 'tel://',
    ];
  }

}

Answer: Shortest way to answer is that my plugin was a mess.
Lesson (re)learned...try to find examples of each method in an exemplar that takes the mystery out of the method.
Sorry, I had pasted the plugin again, but as pointed out, nothing meaningful had changed in it. I believe the issue was that I did not have a schema for the settings.
I added the file url_text.schema.yml to src/Plugin/Field/FieldType
field.field_settings.url:
  type: mapping
  label: 'URL settings'
  mapping:
    allowed_schemes:
      type: string
      label: 'Allowed Schemes'

The values are now saved.
Comment: This answer does not explain anything in terms of the question.
Comment: Between the `propertyDefinitions()` implementation defined in the answer and the implementation of the same method shown in the question there are no differences, since they both return an empty array. In the answer, the method sets `$properties['value']`, but that is a local variable which will vanish once the method returns to the caller.
Comment: Subsequent to these comments and the downvote on my answer I edited the answer to correct it,


Best way to store inventory in a database : each item instance gets its listing, or each player has an "inventory" field?

Question: I'm making a browser MMO using PHP and MySQL. I'm hesitating between two ways to implement player inventories :

when crafted/dropped from a monster/found, an item creates a new row in the Items table, storing its type (instance of a dagger, of a potion...), its location (on the ground at tile X:Y ? in player Z's inventory ?) and maybe an additional field or two. An item's listing would look like this :
id=728 ; type=14 ; location="i426" ; special="e8"
(where "i426" would mean "in the inventory of player n°426", and "e8" would mean the item has the enchantment n°8).
Pros : I can store data about each individual item - enchantments, durability, previous owner... Also, the items are easily placed in any location; putting the items in, say, auction houses, comes for free with this system - not to mention crazy possibilities such as items inside items, etc.
Cons : with hundreds of players looting monsters and crafting all day, this quickly creates a huge table, and it seems pretty wasteful. I fear this might slow down the whole game (I'm using a lot of AJAX voodoo) anytime items are involved.
or : when a player puts an item in their inventory, that player's inventory field on the database is updated with the new item's type (an integer) being appended at the end, with a delimiter. A typical inventory field would look like this : "|11|8|27|58|58"
Pros : much less wasteful. An item instance is just a few digits and a delimiter.
Cons : no extra data on items; every instance is the same. Also, dropping an item on a tile means that tile needs its own inventory field - and so on for every possible location of an item. Besides, this method involves juggling with strings anytime an item has to be added/removed, rather than simply deleting a row from the table. Another thing is that a player's inventory can store a variable number of items, so this string has no predictable length.

In a previous project, I used the second method. The first method looks fun, but I'm not sure if it'll agree with our storage space and our server's speed. Which of those methods is most often used in MMOs ? Is it another one altogether ? Are there some pros or cons I've missed ? (I'm sorry if this question is a bit subjective !)
Comment: I'm guessing almost all systems use something more similar to type 1, since type 2 is an [antipattern](http://pragprog.com/book/bksqla/sql-antipatterns) named "Jaywalking". It stems from the fear of intersections.
Comment: I would not be overly concerned with storage throughput at this stage of development. Be wary of early optimizing. Assuming you're anticipating a high volume of transactions in a short period of time, you likely will be performing most of these transactions in a memory cache which will be flushed to the database as needed to not block player UI requests.
Comment: Is a player's inventory limited?  Do they have say, 10 slots available?  Or is it limited by weight or anything like that?
Comment: @MarcusAdams - darn ! And I thought I had found something clever.
Comment: @MichaelFredrickson - there are limits, but they aren't set. They can change from skills, bags, etc.
Answer: Your best design is a version of approach 1: every item has its own row and you put all the necessary information there. Don't worry about optimization yet - you'll have time for that later when you see how users use your system and where the bottlenecks are.
For now, you want to design for ease of programming and clean, unambiguous descriptions of state. You want a master items table for each "type" of item, where you keep information about what that item is and how it can be used. Then, when created (or instantiated), you put a row in the items table and describe the specifics of that instance of the item. When it moves, you can update the location information. It isn't wasteful, because you are storing -- once and in the right place -- only the information you need to manage the item.
By putting the right indexes on the table, you'll be able to manage millions of them easily and quickly.
Comment: Well it's decided then, that's what I'll be using !


Intersection of closed and bounded subsets of $\mathbb{R}$

Question: Let $\{ C_\lambda \}_{\lambda \in \Lambda}$ be a set of closed and bounded subsets of $\mathbb{R}$. Show that if $\bigcap_{\lambda \in \Lambda}C_\lambda = \varnothing$, then there is a finite subset $F$ of $\Lambda$ such that  $\bigcap_{\lambda \in F}C_\lambda = \varnothing$.
Remarks

For the Heine-Pincherle-Borel's Theorem, every closed and bounded subset of $\mathbb{R}$ is compact.
A consequence of the above proposition is the
Cantor's Theorem
If $C_0\supseteq C_1\supseteq...\supseteq C_{n+1}\supseteq...$ is a decreasing sequence of closed, bounded and not empty subsets of $\mathbb{R}$, then the intersection  $\bigcap_{n \in \mathbb{N}}C_n \neq \varnothing$.
Proof (Reductio ad absurdum)
If $\bigcap_{n \in \mathbb{N}}C_n = \varnothing$, for the proposition above, $\bigcap_{n \in F}C_n =\varnothing$ for some $F\subseteq \mathbb{N}$, $F$ finite; but, called $m=max$ $F$, it results $C_m =\bigcap_{n \in F}C_n =\varnothing$: absurd.

Thanks in advance for any hints or answers.
Comment: Do you know the definition of compactness (e.g., of a fixed $C_{\lambda_0}$) that every open cover has a finite subcover? Pass to complements.
Answer: Proof
$\mathbb{R}=\mathbb{R}-\varnothing=\mathbb{R}-\bigcap_{\lambda\in\Lambda}C_\lambda=\bigcup_{\lambda\in\Lambda}(\mathbb{R}-C_\lambda)$.Therefore, for $\mu\in\Lambda, C_\mu\subseteq\bigcup_{\lambda\in\Lambda}(\mathbb{R}-C_\lambda)$;
since $C_\mu$ is compact, there is $F_\mu\subseteq\Lambda, F_\mu$ finite, such that $C_\mu\subseteq\bigcup_{\lambda\in F_\mu}(\mathbb{R}-C_\lambda)=\mathbb{R}-\bigcap_{\lambda\in F_\mu}C_\lambda$, therefore $C_\mu\cap(\bigcap_{\lambda\in F_\mu}C_\lambda)=\varnothing$. Call $F=F_\mu\cup\{\mu\}$, so $\bigcap_{\lambda\in F}C_\lambda=\varnothing$.
Thank you @Jochen


Handle different "domains" without subdomains

Question: I have a server ("myserver") which only allows requests to the port 80 via HTTPS. Another limitation is that I cannot create subdomains, so I have to stick with "myserver".
Now, I have two applications: "frontend" running in port 8000 and "backend" in port 9000. Ideally, I would create two virtual hosts: "frontend.myserver" and "backend.myserver" using different document roots, server names, etc, but since it is not possible, I think I will have to work with paths such as "myserver/frontend" and "myserver/backend", for example.
Is it possible to do that? Do you know which configuration directive will allow me to do that? maybe using the alias directive?
Answer: Yes, you can use the subdomains with only a single IP address. In Apache, you will have to setup your virtual servers.
Check out the first example here: https://httpd.apache.org/docs/2.2/vhosts/examples.html
Notice that you setup each virtual server for each site you want to serve. Make sure you setup each of the following:

The listener for each virtual server as *:80
The DocumentRoot value pointing at your contect directories for each site
The ServerName value for each URL you want to serve
<code><VirtualHost *:80>
DocumentRoot /www/frontendcontent
ServerName frontend.myserver
</VirtualHost>

<VirtualHost *:80>
DocumentRoot /www/backendcontent
ServerName backend.myserver
</VirtualHost>
</code>

You may also need to use the ServerAlias directive if you want something like example.org and www.example.org to work. For that you would add ServerAlias just as you would the ServerName line, but specify the alias you want to work for that virtual server ServerName.
Here is the documentation on ServerAlias, but I suggest you get the above working, then work on the ServerAlias if necessary:
http://httpd.apache.org/docs/2.2/mod/core.html#serveralias
Comment: Thank you, but I cannot have subdomains or different server names. I think it won't work this way, or it will?
Comment: I've updated my original reply above to include a sample apache config... It will work. The key is the ServerName variable. You must type the ServerName value into your web browser. Apache will look at the request being sent, and decide which virtual server to send the request depending on the site name that the web browser has requested.


No fixed height in interface builder, constraint predicament

Question: The screen I'm trying to create is very simple. I have two UIViews stacked atop one another. The top UIView, topView, has height of 40px, and the UIView below, botView, takes up the rest of the screen. However, sometimes topView should not appear and I want botView to take up the entirety of the screen.
What I've tried is setting width, leading/trailing space on both views. Then topView gets distance to top layout guide, botView gets distance to bottom layout guide, and then an additional constraint for vertical spacing between topView and botView. But this results in xcode yelling at me that I haven't set a height or y constraint on one of the views. Of course, I can't set a height constraint because I do not want either of them to be fixed height.
I'm sure there must be an elegant constraint solution here that I just can't seem to figure out. Thoughts?
Answer: If topView should always be 40px height, then add a constraint for the height of topView.
As for botView, you can keep the current constraint that says its top has to be correlated with the bottom of topView. But add another constraint for bottom view with a priority lower than required that says it should be 0px away from the top of its superview. This way, when you remove topView from the containing view, botView's constraint related to topView will be deleted, and therefore will satisfy the lower priority constraint.
And if you want to push back topView in, recreate the botView to topView distant constraint with required priority.
Answer: There are a couple of ways to do this.  One option
In IB lay out your views.  Then pin top view 0 px from the top, bottom, left, and right. Specify a height constraint of 40 px as well.  To easily do this click on your view, then in the lower right hand corner click on the button that looks like | + |.  Click on the dotted red lines to specify the constraints.  See image:

Do the same for the other view.  Don't specify a height for this view because it's height is dependent on the 40 px view for its height.  Next find the height constraint for the 40 px view.  You can can use the assistant editor to control drag an outlet to you view controller just like you would with a UIButton or any other IB element.  When you want to hide your 40 px view set the variables constant property to 0.  When you want to show it again set it back to 40.
self.topViewHeightConstraint.constant = 0;

The other option you could go with is to pin the top view 0 px to the top, left and right.  Don't provide a bottom constraint but specify the height as 40 px.  For the bottom view add add a left, right, and bottom constraint of 0 px.  For the top constraint add a constraint of 40 px from the top superview.  Again add an outlet for the most recent top constraint and when you want the view to be larger set that constraint to be 0.
Answer: An alternative: In IB, add a distance to top layout guide constraint for BOTVIEW (it will be 40...) Then click-drag this constant to the VC to create a NSLayoutConstraint property.see also here
Now, upon the condition that hides topView, you set self.myConstraint.constant = 0; This will force botView to resize to meet the condition of being 0 from the top.
You may have to clear your current constraints to get rid of errors, but this should give the desired behavior.
As for "topView" like Tom Ahh suggests, go ahead and give it a height constraint of 40 and pin it to the top as you're already doing.


Toggle Class for each div that reaches top of page

Question: I'm trying to find a way to adding and removing a class to a fixed element when each div containing the class, '.dark', reaches the top of the page.
I've got a working example here that works for the first instance of '.dark'.
https://jsfiddle.net/wLqkb5yc/
But I can't seem to get it working for the second instance of the class.
The code:
jQuery(document).ready(function(){
var hieghtThreshold = $(".dark").offset().top;
var hieghtThreshold_end  = $(".dark").offset().top +$(".dark").height() - 25 ;
    $(window).scroll(function() {

            $('.dark').each(function() {

            var scroll = $(window).scrollTop();
            if (scroll >= hieghtThreshold && scroll <=  hieghtThreshold_end ) {
                $('header').removeClass('active');
            }
            else {
                $('header').addClass('active');
            }

            });
    });
});

Can anyone identify what I'm missing here?
Comment: Do you know how I would calculate other instances of .dark? Or point me in the right direction?
Comment: Well if those element positions never change, you could calculate them all upfront, and put them in an array, or store them as custom data on the elements in question themselves. But if something like an orientation change, window size, font size change or zoom changes any of those positions, you will of course have to re-calculate them.
Comment: You are calculating your threshold values for the first .dark element only ...
Answer: It may be easier to find an element with the required coordinates.
We will search for the element that is located just below the logo.
var searchClass = 'dark';
var logoHeader = $('header');
var height = logoHeader.height();
$(window).scroll(function() {
        var elem = document.elementFromPoint(0,height);
        var eClass = $(elem).attr('class');
        classes = (eClass == undefined ? [] : eClass.split(' '));
        (classes.indexOf(searchClass) > -1 ?
            logoHeader.addClass('active') :
            logoHeader.removeClass('active'));
    });
});

https://jsfiddle.net/wLqkb5yc/7/
PS. How to test? Here's the file, I added @media (max-width: 480px) to it, if the screen is less than 480px, then the header element will become 60px, the script will determine its height and also will correctly determine the coordinates.
https://www.dropbox.com/s/k2s8hz65g7xzeck/dark.html?dl=0
Comment: Updated comment, attached test file
Comment: Ah this looks a lot easier and is very close! Is there anyway to get it working with multiple classes? eg. class="bgWhite dark another-class"?
Comment: Ah damn - whilst this method works for desktop, on tablet and mobile the header element is expected to change so the coordinates are incorrect.
Comment: Coordinates can be worked separately for different forms factors
Comment: Nearly there I think! When you say form factors, do you mean like this?
 https://jsfiddle.net/wLqkb5yc/6/  - currently not working
Comment: You can determine the height at the start https://jsfiddle.net/wLqkb5yc/7/
Comment: Your latest comment works perfectly! :-) Thank you for the help, sorry it took so long, I've been looking into the different elements so I'm learning from it as well :-)


Abrir POST em arquivo php

Question: Por padrão sei que posso listar alguns artigos wordpress em uma página externa em php usando um  "require('../../wp-blog-header.php');".
Porém ao clicar em um desses artigos ele vai para página padrão que abre o Post completo.
Minha dúvida é a seguinte:
Como faço para que o POSt completo seja aberto em um arquivo (Ex. Postcompleto.php") separado, ao invés de abrir na single.php ?
Answer: Você pode usar o método de incluir require('../../wp-blog-header.php'); para carregar qualquer conteúdo. O que muda é a forma como você chama o conteúdo dentro do seu arquivo externo.
Por padrão quando você incluir wp-blog-header.php ele vai carregar todo o back-end do WordPress com os parâmetros básicos, ou seja, ele carrega a página inicial. Daí pra frente ele vai obedecer o que estiver no seu arquivo, então você pode criar uma segunda query pra pegar o conteúdo que te interessa:
// Pra buscar um arquivo de posts do tipo "artigos"
$query = new WP_Query( array( 'post_type' => 'artigos' /* etc */ ) );
if ( $query->has_posts() ) :
    while ( $query->has_posts() ) :
        $query->the_post();
        // exibe as informações aqui
    endwhile;
endif;

-
// Pra buscar um post pelo ID
$single = get_post( $id );
echo $single->post_title; // imprime o título

Agora, pra lincar de dentro do seu arquivo de posts para o php externo você provavelmente vai ter que filtrar as URLs que estão sendo exibidas. Algo assim é um caminho, mas existem outros dependendo do seu caso específico:
// em functions.php
add_filter( 'post_link', 'altera_link' ); // posts
add_filter( 'page_link', 'altera_link' ); // pages
add_filter( 'post_type_link', 'altera_link' ); // custom post types
function altera_link( $link ) {
    // altera os links de 'example.com' para 'domain.com';
    return str_replace( 'example.com', 'domain.com', $link );
}

mas: carregar wp-blog-header.php em geral é má ideia.
Eu pensaria bem na arquitetura desse sistema porque existem jeitos melhores de não usar o sistema de templates do WP, se esse é o caso. Existem wrappers pra frameworks PHP (tipo Corcel), ou mesmo pra front-ends em javascript (tipo NodeifyWP) e existe o bom e velho Ajax pra puxar só o conteúdo que você quer.

Abrir POST em arquivo php


Prove that the system $Ax = b, A \in \Bbb R^{m \times n}$ , has a unique solution if and only if rank $A$ = rank$[A \mid b] = n$.

Question: So I am trying to prove the above statement and wanted to see if my line of thinking is in fact correct.
So first, because there exists a  unique solution then rank$(A) =$ rank $[A\mid b]$. I then said suppose that rank $(A) \neq n$ and instead that the rank is in fact $k < n$. This means there are $n-k$ linearly dependent columns which means we have infinitely many solutions to $Ax = b$ because we can have $n-k$ arbitrary elements of $x$ because we can 'eliminate' the linearly dependent columns. Is this line of thinking correct?
Comment: Is it trivial that if the system has a unique solution then $\mathrm{rank}(A)=\mathrm{rank}(Ab)?$
Comment: Maybe I should qualify that with the statement that rank$(Ab)$ means the rank of the augmented matrix. So in fact it is trivial as if there is a solution, then $b$ must be in the span of $[a_1,...., a_n]$. Correct?
Comment: Correct. But I think it must be included in the proof.
Comment: What is $R$ here?
Comment: $R$? It is the symbol for the real numbers. @mfl is the rest of my proof sufficient?
Comment: I think your line of thinking is absolutely correct. However in my opinion can be written with more detail. Of course, that depends on the background knowledgde one is assuming.
Answer: You can simplify a bit the proof using a more general context:

Over any field $K$, the  linear  system $Ax=b$ has a solution if & only if $\operatorname{rank}(A)=\operatorname{rank}\bigl([A|b] \bigr)$ for the very reason you mentioned – that $b$ is in the span of the column vectors of $A$.
Using the rank-nullity formula,  you see this common rank is the codimension of the affine subspace of solutions. On another hand, the solution is unique if & only if the codimension is $n$ (which implies $m\ge n$).
Answer: I think the general idea (for one of the directions) is correct, but it can be worded for explicitly. The following uses reasoning from first principles only.
Forward direction. Suppose that there exists uniquely $x_0$ such that $Ax_0=b.$ If $A$ has rank less than $n$, then there is some $z\neq 0$ such that $Az=0$. But then $x_0+z\neq x_0$ is another solution to $Ax_0=b$. So $A$ has rank $n$. This actually implies $[A|b]$ has rank $n$ as well: rank $[A|b]$ cannot be less than $n$ (because $[A|b]$ contains $A$) and cannot be $n+1$ (because $b$ belongs to the column space of $A$).
Backward direction. If both $A$ and $[A|b]$ have rank $n$, then $b$ must belong to the column space of $A$, so there is $x_0$ such that $Ax_0=b$. Moreover, this $x_0$ must be unique: if there is another $\tilde{x}$ such that $A\tilde{x}=b$, then $A(x-\tilde{x})=0$, contradicting $A$ having full column rank.


What is the use of sync directory?

Question: I see in Drupal documentation about Configuration Management it is adviced to change the location of the sync directory in a production environnement.
But I can't find an explanation about the actual use of this directory. For what does Drupal use it ? (I expect a more accurate answer than "synchronizing", which I can formulate myself but is not very helping...)
And why is it unadvised to keep this directory accessible from the web ? What could be the consequences ?
Answer: It's where Drupal exports configuration (YAML files) to, and reads configuration from (for example using drush config-export and drush config-import respectively). The term "synchronising" refers to Drupal comparing the contents of those files to the site's active configuration, and applying any config that's changed.
You want to keep that folder out of the public web server for at least 2 reasons:

Those files could potentially contain sensitive data
You're potentially exposing the structure and configuration of your site to the world. Those details could be advantageous to an attacker.

Best to err on the side of caution and keep them away from prying eyes.
Comment: No it's used regardless of Drush; without Drush it's a slightly more manual process of going to the Admin -> Development -> Configuration page, exporting, putting the files in the sync folder manually, sending them to the remote server, then re-importing them through the UI again. Drush is generally preferable as you can at least partially automate it as part of the deployment process
Comment: Thanks. So this directory is used only if I use Drush ?
Comment: Ok. But using the UI, you don't have to put files in the sync folder, you can upload it directly on the UI.
I understand know you can also unzip the content of the full export archive in this sync directory.
Comment: Correct - many ways to solve the same problem. I guess that's why it's a bit confusing

What is the use of sync directory?


What do I call a set of datasets

Question: For training a Machine learning model,
I have 3 datasets:

Training
Validation
Testing

Normally I obtain there by dividing up the full dataset into pieces.
I've created a function in my code to return the 3 of them in a record (ie named tuple, ie structure)  an I need a name to refer to the grouping of the 3.
Currently I am using Learning_datasets,
but that isn't great.
Is there some kinda of commonly used phrase or term?
Like a set of trees is called a forest.
Answer: I believe there is not a specific name for this combination. You could name your function "data" (or just "dataset")  as it will return all the information available (train + validation + test).

What do I call a set of datasets


Kendall's W for a series of answers about the same phenomenon in different entities

Question: I have a question about the proper usage of Kendall's coefficient of concordance (Kendall's W). Suppose a series of questions were asked how democratic certain organisations are. Each question was the same for each organisation. There were five possible answers ranging from the most democratic to the most non-democratic. Can I in this case compute Kendall's W? If not, is there a technique that will measure the reliability of consensus that suits the case presented?
In every handbook I've checked there was no mention about such a case.
 Wikipedia's entry on Kendall's W is no different.
Answer: This sounds like a reasonable application of Kendall's W.
It's important to understand how the statistic works.  It is related to Friedman's test, and sometimes the examples for Friedman's test you'll find are more useful than for Kendall's W.
In the following example, the raters are labeled a thru h.  The result is a small p-value (which should be the same as that for Friedman's test), and a large Kendall's W (0.599).  This is because raters tended to rate Burning.man higher or equal than IKEA, and rated IKEA higher or equal to Disneyland.  Note that the statistic treats the raters as blocks, so, essentially, what's important is the rating for each organization within each rater, (not the absolute scores for each organization as if you had independent observation as if you were using Kruskal-Wallis).
A toy example in R:
<code>if(!require(DescTools)){install.packages("DescTools")}

Input =("
Organization     a  b  c  d  e  f  g  h
  Disneyland     1  2  3  4  5  6  6  6
  IKEA           2  3  4  5  6  6  6  6
  Burning.man    3  4  5  6  6  6  6  6
")

Matrix = as.matrix(read.table(textConnection(Input),
                   header=TRUE,
                   row.names=1))

Matrix

library(DescTools)

KendallW(Matrix,
         correct=TRUE,
         test=TRUE)

   ### Kendall's coefficient of concordance Wt

   ### data:  Matrix
   ### Kendall chi-squared = 9.5789, df = 2, subjects = 3, raters = 8, p-value = 0.008317
   ### alternative hypothesis: Wt is greater 0
   ### sample estimates:
   ###        Wt
   ### 0.5986842
</code>
Comment: Thank you very much for this example and your clarifications.


RHEL/Apache ssl.conf configuration issue

Question: We've got multiple subdomains, each with it's own virtualhost entry in httpd.conf and (for those supporting https) in ssl.conf as well.  Our main www subdomain has a GoDaddy cert associated with it.  The subdomain I'm configuring right now in our dev environment ("api.bulbstorm.com") has an ssl.conf virtualhost entry that looks like this:
<VirtualHost 172.16.247.153:443>
  DocumentRoot "/var/www/api"
  ServerName api.bulbstorm.com:443
  ErrorLog logs/api-error_log
  CustomLog logs/api-access_log common
  LogLevel warn
  SSLEngine on
  SSLProtocol all -SSLv2
  SSLCertificateFile /var/www/certs/api/server.crt
  SSLCertificateKeyFile /var/www/certs/api/server.key
  <Files ~ "\.(cgi|shtml|phtml|php3?)$">
    SSLOptions +StdEnvVars
  </Files>
  <Directory "/var/www/cgi-bin">
    SSLOptions +StdEnvVars
  </Directory>
  <Directory "/var/www/api">
    Options +FollowSymLinks
    RewriteEngine On
    AllowOverride All
    Order allow,deny
    Allow from all
  </Directory>
  php_value include_path "/var/www/inc"
  SetEnvIf User-Agent ".*MSIE.*" \
    nokeepalive ssl-unclean-shutdown \
    downgrade-1.0 force-response-1.0
  CustomLog logs/ssl_request_log \
    "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>

... the crt & key files in /var/www/certs/api/ were generated using openssl per instructions found here.
The api subdomain originally pointed to the godaddy cert for the www subdomain.  But even though I've changed the virtualhost entry associated with the api subdomain to point to the self-signed certificate/key pair (and have restarted httpd, completely cleared browser settings related to the previous exception for the godaddy cert, etc.) browsers are still throwing warnings saying that the cert is for the www domain.  When I look at the cert the browsers are pulling it looks like they're still getting the godaddy cert.
Higher up in the ssl.conf file there are these lines:
SSLCertificateFile /etc/pki/tls/certs/localhost.crt
SSLCertificateKeyFile /etc/pki/tls/private/localhost.key

This cert/key pair is different than the godaddy cert/key pair referenced in the virtualhost entry for the www subdomain, which looks like this:
SSLCertificateFile /etc/www.bulbstorm.com_ssl/www.bulbstorm.com.crt
SSLCertificateKeyFile /etc/www.bulbstorm.com_ssl/www.bulbstorm.com.key
SSLCertificateChainFile /etc/www.bulbstorm.com_ssl/gd_intermediate_bundle.crt

Any light that anyone can shed on the issue I'm having will be appreciated.
Comment: TL;DR.  What's the *actual* problem you're having, in amongst all those config files?
Answer: Make sure that the api.bulbstorm.com and www.bulbstorm.com vhosts are on DIFFERENT IP addresses.  Here are my vhost configs for 2 different subdomains with unique SSL certs:
/usr/local/etc/apache22/Includes/login.domain.com.ssl.conf
Listen 10.0.0.152:443

<VirtualHost 10.0.0.152:443>
ServerAdmin firstname.lastname@example.com
DocumentRoot /web0/cloud/login.domain.com/current
ServerName login.domain.com

ServerAlias www.login.domain.com login.domain.com

LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""
TransferLog /var/log/www/login.domain.com-access_log
ErrorLog /var/log/www/login.domain.com-error_log

<DIRECTORY /web0/cloud/login.domain.com/current>
Allow from All
OPTIONS Indexes Includes ExecCGI FollowSymLinks
AllowOverride ALL
</DIRECTORY>

IndexOptions FancyIndexing

AddType application/x-httpd-php .html

SSLEngine on

SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
SSLCertificateFile "/usr/local/etc/apache22/ssl.crt/login.domain.com.crt"
SSLCertificateKeyFile "/usr/local/etc/apache22/ssl.key/login.domain.com.key"
SSLCertificateChainFile "/usr/local/etc/apache22/ssl.crt/comodo.ca-bundle"

BrowserMatch ".*MSIE.*" \
         nokeepalive ssl-unclean-shutdown \
         downgrade-1.0 force-response-1.0

</VirtualHost>

/usr/local/etc/apache22/Includes/admin.domain.com.ssl.conf
Listen 10.0.0.151:443

<VirtualHost 10.0.0.151:443>
ServerAdmin email@example.com
DocumentRoot /web0/cloud/admin.domain.com/current
ServerName admin.domain.com

ServerAlias www.admin.domain.com admin.domain.com

LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\""
TransferLog /var/log/www/admin.domain.com-access_log
ErrorLog /var/log/www/admin.domain.com-error_log

<DIRECTORY /web0/cloud/admin.domain.com/current>
Allow from All
OPTIONS Indexes Includes ExecCGI FollowSymLinks
AllowOverride ALL
</DIRECTORY>

IndexOptions FancyIndexing

SSLEngine on

SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
SSLCertificateFile "/usr/local/etc/apache22/ssl.crt/admin.domain.com.crt"
SSLCertificateKeyFile "/usr/local/etc/apache22/ssl.key/admin.domain.com.key"
SSLCertificateChainFile "/usr/local/etc/apache22/ssl.crt/comodo.ca-bundle"

BrowserMatch ".*MSIE.*" \
         nokeepalive ssl-unclean-shutdown \
         downgrade-1.0 force-response-1.0

</VirtualHost>

Comment: @amishgeek - excellent.  thank you.  we actually already have multiple ip addresses resolving to this machine.  i should be able to adjust the dns record to run the api subdomain through one of the other ip's.
Answer: As amishgeek points out, and ping confirms:

    Microsoft Windows [Version 6.0.6002]
    Copyright (c) 2006 Microsoft Corporation.  All rights reserved.

    C:\Users\Owner>ping bulbstorm.com

    Pinging bulbstorm.com [18.104.22.168] with 32 bytes of data:
    Control-C
    ^C
    C:\Users\Owner>ping www.bulbstorm.com

    Pinging www.bulbstorm.com [18.104.22.168] with 32 bytes of data:
    Control-C
    ^C
    C:\Users\Owner>ping api.bulbstorm.com

    Pinging api.bulbstorm.com [18.104.22.168] with 32 bytes of data:
    Control-C
    ^C
    C:\Users\Owner>

You have the same IP address for both hosts. SSL happens before host names are sent. Host names are sent to Apache through the Host: header in HTTP requests. In OpenSSL 1.0, there will be support for TLS certificates, which may help with sharing an IP, but that's another ballgame, and more Googling.
LINKS:

A link from PositiveSSL, another SSL cert issuer
An entry from someone troubleshooting this same issue.
And, from the horse's mouth (Apache): http://httpd.apache.org/docs/2.0/ssl/ssl_faq.html#vhosts

WORKAROUNDS:
Per the Wikipedia entry on TLS: you should adjust your certificate to support multiple subject alternative names (GoDaddy has "UCC Certs"), or get a wildcard certificate.
Depending on your user base, you could ask users to support the CACert root certficate and get a subjectAltName certificate from them. (in fact, it looks like your current certificate has a subjectAltName for bulbstorm.com, AND www.bulbstorm.com). This saves you $70.00 per year. Put a link on your non-SSL page or on your SSL page which says something like

"Are you getting SSL browser errors? We use CACert SSL Certificates. Please follow this link to download their root certificates into your browser."
Comment: @mpbloch - this was what i was looking for, thank you!
Comment: Sure thing ;-)
Apache's config files can be beastly, and it's really amazing to switch between Apache, and then Abyss Web Server.
Spending some time with your own box, and setting up config files for virtual hosts, SSL, and directory permissions, etc, can be an invaluable way to spend a few hours. I often restructure my config files later, so that they make sense to ME. Removing the comments from sample config files can improve readability.
Also, I use Mercurial (hg) to keep directory snapshots and revision histories of my config files for when stuff changes, I can easily roll back.
Answer: To answer your question at the very end, this is how to generate a self signed SSL certificate.
First, this line will generate a private key that is used to generate a certificate signing request (CSR).
openssl genrsa -des3 -out server.key 1024

You will be prompted to enter a passphrase. This passphrase will encrypt the private key. This next line will generate the CSR using your private key.
openssl req -new -key server.key -out server.csr

You will then be prompted for the following questions (and your passphrase if you chose to use one above in the generation of your private key.)
Country Name (2 letter code) [GB]:
State or Province Name (full name) [Berkshire]:
Locality Name (eg, city) [Newbury]:
Organization Name (eg, company) [My Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:
Email Address []:
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

Edit: if you do generate a self-signed certificate for testing, the Common Name field above is where you want to put your domain (exactly as you want it, ie. with the www if you want that to be the address you use). After you've generated your CSR, you can self-sign it doing the following.
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Then you will have your private key (server.key) and your SSL certificate (server.crt) which you can install in Apache using the directives you've used above for the other certificates.
I'm not sure if this answers any of the questions regarding the apparent incorrect certificate being sent to the browser, but I would suggest perhaps removing all references to certificate files outside that VirtualHost directive to see if it still happens, since you're only really able to have one SSL host per IP address, and having multiple SSLCertificateFile directives could have an unusual effect.
Comment: Not the issue at hand.
Comment: I understand, however he asked at the end how to generate a self-signed certificate, so I have explained just that.
Comment: However, he's already "generated using openssl per instructions found here": http://www.tc.umn.edu/~brams006/selfsign.html. And needs to know "how to ... make the ssl.conf file adjustments necessary to get them to actually work"
Comment: But you take what he's saying out of context. Maybe you should read the first half of the sentence you actually quoted and omitted part of: "I'd really like to be able to know how to create self-signed certs and make the ssl.conf file adjustments necessary to get them to actually work."
Comment: So I explained how. I'm pretty sure it's a valid response, and I'm not sure why I've been modded down for it.
Comment: @james - +1 for the rundown.  mpbloch's answer was more of what i was needing, but confirmation on the cert generation process is also appreciated.


Can MLB players negotiate their contracts downwards?

Question: Consider the case where a player is signed to a contract and the amount he is due far exceeds his value.  He no longer has a starting job on his team and would like to be traded, but other teams won't pay his salary and his current team won't cover enough of the cost of his contract to facilitate a trade.
The player is willing to decrease his salary by a certain amount to increase his marketability to other teams.
Is this permitted?
Comment: Just to be clear, you're essentially asking about MLBPA policy?
Comment: @jerepierre That or any other official rule that would prevent this.  I can't think of anything other than MLBPA policy or something in the CBA.
Answer: Possibly yes.  I've only ever heard of players being willing to take less.  Here is a link to an article showing players from different sports who have taken pay cuts to stay with a team, or to be able to play one more year even if they might not be the player they used to be.
Here is another article from 2005 where Chipper Jones of the Atlanta Braves offered to take a pay cut so that the Braves would be able to keep Tim Hudson.

He was introduced to Jones, the Braves' highest paid player, who's owed $32 million over the next two seasons and has $15 million vesting clubs options in 2007 and 2008. He could restructure his contract to clear up funds for a Hudson offer.
"Maybe a little rebate so we can sign him," said Jones, the only non-catcher who showed up Wednesday, doing some hitting and pronouncing himself healthy.
"Whatever [it takes]," Jones said. "I'm game. I've made no bones about it - my family loves it here, and I love playing here. I've made sacrifices before, and I'm open to more if it'll help bring guys in or keep them. I want to win."

It is very uncommon that a player, especially one signed to a huge contract would ever take a pay cut to stay with a team, or be able to sign with a team who has a chance to go all the way.  It happens quite a bit in basketball, with older players who want to win a ring(reference my first article).

Lester even went so far as to admit that he would take a pay cut in order to stay in Boston and help his team win a consecutive World Series title. His inspiration for being so outwardly willing to take less pay in order to remain on the team he loves comes partly from his teammate Dustin Pedroia, who decided to leave a larger offer to stay with the Red Sox. As much as I dislike this team and their recent success, it enthralls me to hear this kind of talk in the offseason.

Here is another quote from this article that shows Jon Lester's willingness to take a pay cut to stay with the Red Sox, just as Pedroia took a lesser offer from the Sox to stay.
Comment: Thanks, and the Chipper quote is interesting.  However the other examples are about players who took (or talked about taking) less than market value for a contract extension - they weren't talking about renegotiating their existing contract downwards.

I have seen comments in message boards that imply that players are not allowed to do this (based on MLBPA rules).  Of course the teams would welcome it, but it may be the case that the union doesn't allow it.

I skimmed the CBA and didn't find anything...
Comment: I think what you'd usually see is a player extend his contract to reduce the year-to-year cost but keep the total value of the contract.
Comment: @New-To-IT Between wikipedia and Baseball Reference, it's clear he did restructure his contract after 2005; instead of a 16MM 2006 and options for 2007 and 2008 at 15MM, all three years were guaranteed at $12MM.
Comment: I made edits, because you're right, I don't really provide any proof that it can happen, just players that say they're willing.  I will do more research.
Comment: @Joe - do you mean tacking on an extra free (or close to it) year or two at the end in order to reduce the average annual value?  I've never heard of this happening.
Comment: Well, it happened in the example I provided just above.  Now, he did get a guarantee instead of a vesting option, so he did get something out of it.
Answer: It's certainly permitted. Here's a related situation. Suk-min Yoon signed with the Orioles ($5.75M / 3yr) in the 2013-2014 offseason out of Korea. His 2014 season went very poorly at AAA Norfolk [Baseball Reference stats]. Now he would like to return to Korea, and the Orioles would like to save the money on the contract. They are working out a buyout to allow Yoon to return to Korea [NBC Sports].
Comment: MLB contracts when not covered by the reserve clause are always fully guaranteed.  The only non-guarantee is when there is an option year.  As such, yes, the Orioles could just cut him entirely, but they'd still owe him $5.75MM (presumably around $4MM left); if they instead reach a buyout, they might be able to pay him substantially less.
Comment: I'm surprised contract stipulations do not allow the Orioles to cut bait easily. In other words, I thought there were ways teams can protect themselves from this if the player doesn't pan out.
Comment: I think this may be a bit of a special situation with a foreign player.  Also I believe Yoon signed in Korea for *more* money.  The MLBPA wants to be as friendly as possible to foreign players, so preventing a player from getting out of his contract when both he and this team wanted to, AND he could return home for more money doesn't seem to be in anyone's interests.


To gauge motivation score?

Question: In order to gauge the level of motivations of my respondents to connect in Second Life, I have proposed to them to answer (with a Likert scale - 7 points: from totally disagree to totally agree) to 16 statements (items) that I have categorized myself in four motivation categories.
For example the fulfillment motivations

The fact that my avatar gains a higher status (in terms of money, material possessions, reputation, etc) is important to me. (HIGH STATUS)
The fact that Second Life allows me to undertake and make money is important to me (START BUSINESS)
The fact that Second Life allows me to gain valuable knowledge in the virtual world (scripting language, etc) and / or in the real world (to follow courses in Second Life, etc) is important to me. (TO ACQUIRE KNOWLEDGE)
The fact that Second Life allows me to create whatever I want is important to me. (CREATE)
The fact that Second Life allows me to be altruistic (helping new residents, …) is important to me. (BE ALTRUISTIC)

I would like to compute the average score of each respondents the fulfillment motivation
<code>           HIGH STATUS|START BUSINESS|TO ACQUIRE KNOWLEDGE|CREATE|BE ALTRUISTIC|
Resp n°29        4             6             6          7         6        5,8
Resp n°30        2             4             6          6         4        4,4
Resp n°31        5             7             4          1         5        4,4
</code>
In place of computing a simple arithmetic average I envisage a principal component analysis
If I do a PCA for the 5 assesments of the fulfillment motivations :
Principal components/correlation                    Number of obs    =       373
                                                          Number of comp.  =         4
                                                          Trace            =         5
Rotation: (unrotated = principal)                    Rho              =    1.0000
<code>--------------------------------------------------------------------------
   Component |   Eigenvalue      Difference         Proportion      Cumulative
-------------+------------------------------------------------------------
       Comp1 |      2.72909            1.81017              0.5458            0.5458
       Comp2 |      .918928           .121757               0.1838            0.7296
       Comp3 |      .797171           .242364               0.1594           0.8890
       Comp4 |      .554806           .554806               0.1110           1.0000
       Comp5 |  4.44089e-16            .                       0.0000            1.0000
--------------------------------------------------------------------------
</code>
Principal components (eigenvectors)
<code>--------------------------------------------------------------------
    Variable    |   Comp1   Comp2  Comp3   Comp4 | Unexplained
-------------+----------------------------------------+-------------
Statut_Elevé    |   0.2544    0.8212   -0.4932    0.1330 |            0
Lancer_Bus      |  0.5549   -0.3110   -0.2713   -0.1475 |            0
Créer   |   0.4279    0.0046    0.4411    0.7889 |            0
Altruisme   |   0.3693    0.3637    0.6442   -0.5625 |            0
Acquérir_C      |   0.5549   -0.3110   -0.2713  -0.1475 |            0
--------------------------------------------------------------------
</code>
I was wondering if I could not sort my items in both components:
<code> Resp n° 29
 Comp1:     (0.2544*4)+(0,5549*6)+(0,4279*7)+(0,3693*6) + (0,5549*6) = 12,8875
 Comp2:   (0,8212*4) + (-0,3110*6) + (0,0046*7) + (0,3637*6) + (-0.3110 *6) = 1,7672
</code>
And after computing the mean of both components : 7,32735
Is this approach appropriate? If not, what can I do better than simple average items to calculate a score of achievement motivation?
Comment: Not sure I understand your description, you have 16 items but five components? Have you got four or five motivation categories? Incidentally, how many respondents do you have in total?
Answer: There are a number of problems in there and nobody will be able to tackle everything in a short answer or spare you the trouble of learning and reading about whatever techniques you end up using. Your description also raises many questions and is not entirely clear.
Generally speaking, it would seem common to directly analyze the original items (without "parcelling"), aiming at recovering the hypothesized dimensions (e.g. "be altruistic" or "start a business") and use and interpret the resulting scales scores. Also, since you seem to be trying to extract measures of some latent constructs like "altruistic motivation", factor analysis would seem more appropriate than PCA.
You can find a lot of relevant material on this site but Factor analysis of questionnaires composed of Likert items seems particularly relevant.
In any case the following paper should directly address the specific question you formulated at the end:

DiStefano, C., Zhu, M., & Mîndrilă, D. (2009). Understanding and Using Factor Scores: Considerations for the Applied Researcher. Practical Assessment, Research & Evaluation, 14 (20).

To gauge motivation score?


Quotient groups of direct products: $\left(G\times H\right)/G^*\cong H$ and vice versa.

Question:
If $G$ and $H$ are groups. Let $G^\star= \{(a, e_H)| a\in G\}$ and $H^\star=\{(e_H, b) |b \in H\}$. Show that
  $(G \times H)/G^\star$ is isomorphic to $H$ and $(G \times H)/H^\star$ is isomomorphic to $G$.

Guys I am stuck! Please help me as to what function should I use and how should I proceed?
Answer: Hint: Apply the first isomorphism theorem to the projections from $G \times H$ onto $G$ and $H$.
Answer: Given a group $G\times H$, I find it helpful to use the following notation: $$G\times 1 = \{(g,1)\in G \times H\}.$$ You might notice an obvious isomorphism $(g,1)\mapsto g$ between $G\times 1$ and $G$.  Similarly, writing $$1\times H = \{(1,h)\in G \times H\}$$
we see an isomorphism $(1,h)\mapsto h$ between $1\times H$ and $H$.
Now, you might notice that we could have instead defined a map from $G\times H$ to $G$ by $(g,h)\mapsto g$, or a similar map from $G\times H$ to $H$ by $(g,h)\mapsto h$.  These aren't bijective, but perhaps we can use them anyway.
$\hspace{22pt}{\rm \text{S}{\small \text{TEP }} 1.}$  Verify that $(g,h)\mapsto g$ and $(g,h)\mapsto h$ are homomorphisms.
$\hspace{22pt}{\rm \text{S}{\small \text{TEP }} 2.}$  What are the kernels of $(g,h)\mapsto g$ and $(g,h)\mapsto h$?  What are their images?

 $(g,h)$ is in the kernel of $(g,h)\mapsto g$ whenever $g=1$, so the set of such $(g,h)$ is$\ldots$

$\hspace{22pt}{\rm \text{S}{\small \text{TEP }} 3.}$  Can you compose the canonical homomorphisms given by the first isomorphism
$\hspace{22pt}$theorems with any of the other maps we've seen recently?
Answer: Hint: What are the cosets of $G^\star$ in $G\times H$?


Computing the Torsion Subgroup of $E(\mathbb{Q})$, where $E:Y^2=X^3 +2$

Question: I have to compute the Torsion Subgroup of $E(\mathbb{Q})$, where $E:Y^2=X^3 +2$ using Nagell-Lutz. So, if $(x,y) \in E(\mathbb{Q})_{\text{tors}}$ then $x,y \in \mathbb{Z}$ and either $y=0$ or $y^2 \ \vert \ \Delta = 4(0)^3 + 27(2)^2 = 108$
Clearly, if $y=0$, then $x \notin \mathbb{Z}$. So $y^2 \ \vert \ 108 \implies y=\pm1, \pm2,\pm3,\pm6$. Accomodating $x \in \mathbb{Z}$, we eliminate possibilities of $y$ to get the following points: $P=(-1,\pm1)$
I see that $2P$ does not have integer coefficients, is that enough to claim that the torsion subgroup is trivial?
Answer: The contrapositive of Nagell-Lutz tells us that if $Q = (x, y)$ are not integers, then $Q$ is NOT a rational point of finite order on $E$.
Since $Q = 2P$ (according to you) have coordinates which are not integers, then $Q$ is not a torsion point.
Now, given this, what if $P$ is a torsion point? Does something go wrong?
Comment: Right, if $P$ is a torsion point, then $P + P = Q$ is a torsion point, and we have a contradiction


Difference estimate & confidence intervals for $\chi^2$ test between 2 proportions

Question: I am using a chi-sq test between two proportions (http://statistic-on-air.blogspot.com/2009/07/comparison-of-two-proportions.html). I am using this over the z-test for proportions because I do not think my data is normal.
My question is how do I get the difference (shift) estimate & confidence intervals for this test.
For example,
Data1: 193/252=.77
Data2: 154/227=.68

P-value=.032 (I used the formula in the link above. I will also add my exact code below)
Shift Estimate: I assume its the difference between proportions, ie .77-.68=.09. Is this correct?
Confidence Interval: ??????????????????
Code for generating P-value (matlab):
% Pooled estimate of proportion
 p0 = (n1+n2) / (N1+N2);
% Expected counts under H0 (null hypothesis)
 n10 = N1 * p0;
 n20 = N2 * p0;
% Chi-square test, by hand
 observed = [n1 N1-n1 n2 N2-n2];
 expected = [n10 N1-n10 n20 N2-n20];
 chi2stat = sum((observed-expected).^2 ./ expected);
 p = 1 - chi2cdf(chi2stat,1);
 H=0; if(p<.05), H=1; end

Comment: The $\chi^2$-test for a 2x2-table is more or less based on the same normality assumptions than the z-test in your reference, so you can use either test (note it's not the data that has to be close to normal, it's the test statistic). The z-test has the advantage to provide straightforward approximate confidence interval for the true shift, so you might go with this version to make life easier.
Comment: Thanks Micheal! Are you aware of any confidence intervals for the  χ2-test?
Comment: Even in a 2x2 table you can look at 6 differences in probabilities but the chisquare test provides only a single test result. So there is no direct way to get such c.i.
Comment: The Chisquare test is however directly linked to c.i. for the population version of Cramer's V and approximately, in the 2x2 case, also of the odds ratio. Both measure the strength of association between the two categorical variables behind the table.
Answer: Just for  statistically intimidated people (wait, it should be 'intimidated by statistics') that can identify themselves with this joke:
A patient asks his surgeon what the odds are of him surviving an impending operation. The doctor replies that the odds are usually 50-50. "But there is no need to worry," the doctor explains.
"The first fifty have already died.
It is meant to be a quick reference for those confused with the terminology and overlapping tests - I am not addressing confidence intervals.
COMPARING PROPORTIONS BETWEEN SAMPLES:
I will use the following toy tabulated data:
Antacid <- matrix(c(64, 178 - 64, 92, 190 - 92), nrow = 2)
Antacid_marginals <- matrix(c(64, 178 - 64, 92, 190 - 92), nrow = 2)
    Antacid_marginals <- rbind(Antacid_marginals, margin.table(Antacid_marginals,2))
    Antacid_marginals <- cbind(Antacid_marginals, margin.table(Antacid_marginals,1))
    dimnames(Antacid_marginals) = list(Symptoms = c("Heartburn", "Normal","Totals"),
                                       Medication = c("Drug A", "Drug B", "Totals"))

This is what it looks like (with marginals):
           Medication
Symptoms    Drug A Drug B Totals
  Heartburn     64     92    156
  Normal       114     98    212
  Totals       178    190    368

So we have 368patients: 178 on Drug A, and 190 on Drug B and we try to see if there are differences in the proportion of heartburn symptoms between drug A and B, i.e. $p1 = 64/178$ vs $p2 = 92/190$.
1. FISHER EXACT TEST: There is a discussion on Wikipedia about "Controversies". Based on the hypergeometric distribution, it is probably most adequate when the expected values in any of the cells of a contingency table are below 5 - 10. The story of the RA Fisher and the tea lady is great, and can be reproduced in [R] by simply grabbing the code here. [R] seems to tolerate without a pause the large numbers in our data (no problem with factorials):
 Antacid <- matrix(c(64, 178 - 64, 92, 190 - 92), nrow = 2)
    fisher.test(Antacid, alternative = "two.sided")
    Fisher's Exact Test for Count Data
data:  Antacid
p-value = 0.02011
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
 0.3850709 0.9277156
sample estimates:
odds ratio
 0.5988478

2. CHI-SQUARE TEST OF HOMOGENEITY: Otherwise known as the goodness of fit Pearson's chi squared test. For larger samples (> 5 expected frequency count in each cell) the $\chi^2$ provides an approximation of the significance value. The test is based on calculating the expected frequency counts obtained by cross-multiplying the marginals (assuming normal distribution of the marginals, it makes sense that we end up with a $\chi^2$ distributed test statistic, since if $X\sim N(\mu,\sigma^)$, then $X^2\sim \chi^2(1))$:
                    Medication
Symptoms       Drug A                   Drug B
Heartburn     156 * 178 / 368 = 75      156 * 190 / 368 = 81
Normal        212 * 178 / 368 = 103     212 * 190 / 368 = 109

The degrees of freedom will be calculated as the {number of populations (Heartburn sufferers and Normals, i.e. 2) minus 1 } * {number of levels in the categorical variable (Drug A and Drug B, i.e. 2) minus 1}. Therefore, in a 2x2 table we are dealing with 1 d.f. And crucially, a $\chi^2$ of $1\,df$ is exactly a squared $N \sim (0,1)$ (proof here), which explains the sentence "a chi-square test for equality of two proportions is exactly the same thing as a z-test. The chi-squared distribution with one degree of freedom is just that of a normal deviate, squared. You're basically just repeating the chi-squared test on a subset of the contingency table" in this post.
The Test Statistic is calculated as:
$\chi^2=\frac{(64-75)^2}{75} + \frac{(92-81)^2}{81} +\frac{(114-103)^2}{103} + \frac{(98-109)^2}{109} = 5.39$
This is calculated in R with the function prop.test() or chisq.test(), which should yield the same result, as indicated here:
prop.test(Antacid, correct = F)

2-sample test for equality of proportions without continuity correction

data:  Antacid
X-squared = 5.8481, df = 1, p-value = 0.01559
alternative hypothesis: two.sided
95 percent confidence interval:
 -0.22976374 -0.02519514
sample estimates:
   prop 1    prop 2
0.4102564 0.5377358

or..
chisq.test(Antacid, correct = F)

Pearson's Chi-squared test

data:  Antacid
X-squared = 5.8481, df = 1, p-value = 0.01559

3. G-TEST: The Pearson's chi-test statistic is the second order Taylor expansion around 1 of the G test; hence they tend to converge. In R:
library(DescTools)
GTest(Antacid, correct = 'none')
Log likelihood ratio (G-test) test of
independence without correction

data:  Antacid
G = 5.8703, X-squared df = 1, p-value = 0.0154

4. Z-TEST OF PROPORTIONS: The normal distribution is a good approximation for a binomial when $np>5$ and $n(1-p)>5$. When the occurrences of successes are small in comparison with the total amount of observations, it is the actual number of expected observations that will determine if a normal approximation of a poisson process can be considered ($\lambda \geq 5$).
Although the post hyperlinked is old, I haven't found in CV an R function for it. This may be due to the fact explained above re: $\chi^2_{(df=1)}\sim \, N_{(0,1)}^2$.
The Test Statistic is:
$ \displaystyle Z = \frac{\frac{x_1}{n_1}-\frac{x_2}{n_2}}{\sqrt{p\,(1-p)(1/n_1+1/n_2)}}$ with $\displaystyle p = \frac{x_1\,+\,x_2}{n_1\,+\,n_2}$, where $x_1$ and $x_2$ are the number of "successes" (in our case, sadly, heartburn), over the number of subjects in that each one of the levels of the categorical variable (Drug A and Drug B), i.e. $n_1$ and $n_2$.
In the linked page there is an ad hoc formula. I have been toying with a spin-off with a lot of loose ends. It defaults to a two-tailed alpha value of 0.05, but can be changed, as much as it can be turned into a one tailed t = 1:
zprop = function(x1, x2, n1, n2, alpha=0.05, t = 2){
  nume = (x1/n1) - (x2/n2)
  p = (x1 + x2) / (n1 + n2)
  deno = sqrt(p * (1 - p) * (1/n1 + 1/n2))
  z = nume / deno
  print(c("Z value:",abs(round(z,4))))
  print(c("Cut-off quantile:",
    abs(round(qnorm(alpha/t),2))))
  print(c("pvalue:", pnorm(-abs(z))))
}

In our case:
    zprop(64, 92 , 178, 190)
    [1] Z value:          2.4183
    [1] Cut-off quantile: 1.96
    [1] pvalue:           0.0077

Giving the same z value as the function in the R-Bloggers: z.prop(64, 178 , 92, 190) [1] -5.44273
OK... Hope it helps somebody out there, and I'm sure mistakes will be pointed out...
Comment: In skimming over this (impressive) post, I found myself wondering just what distinction you are making between "non-parametrically" and "parametrically."  All tests (Fisher's Exact, $\chi^2$, and $Z$) generally apply to *non-parametric* models, with the latter two using $\chi^2$ and $Z$ distributions to *approximate* the null distribution. In no case have you actually specified a parametric model for the data, although you have alluded in passing to a "Poisson process." Clarification of this distinction would be helpful.
Comment: I'm not sure.  I guess I'm suggesting they might not adequately reflect the basis of your organization of this post, that's all.  I don't whether that means you would prefer to change the headings or to change the organization!
Comment: @whuber I post a lot hoping that my amateur mistakes will be pointed out, and over time become reasonable answers for people coming from applied sciences. So thank you very much for taking the time. I think I get your comment. You are saying that I am not trying to estimate a parameter _assuming_ a distribution, which would deserve the "parametric" label... Do you think I'd be better off erasing these headings?


Unable to delete a tempstore that contains an en dash or an em dash

Question: I am trying to delete a shared temporary storage for a key containing an en dash or an em dash.
$keyword = '2020–2021';
$tempstore = \Drupal::service('tempstore.shared')->get('my_module_name');
$tempstore->delete($keyword);

It throws this exception.

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[HY000]: General error: 1267 Illegal mix of collations (ascii_general_ci,IMPLICIT) and (utf8mb4_general_ci,COERCIBLE) for operation '=': DELETE FROM {key_value_expire} WHERE ("name" IN (:db_condition_placeholder_0)) AND ("collection" = :db_condition_placeholder_1); Array ( [:db_condition_placeholder_0] => 2020—2021 [:db_condition_placeholder_1] => tempstore.shared.my_module_name ) in Drupal\Core\KeyValueStore\StorageBase->delete() (line 52 of core/lib/Drupal/Core/KeyValueStore/StorageBase.php).

As far as I can tell, it's not an issue with the database, but rather with having the en dashes or em dashes in the storage key. I've tried escaping it with Html::escape() and utf8_encode(), but it didn't resolve the issue.
EDIT:
I checked what my local database collation is and it returns UTF8.

mysql> SELECT DEFAULT_CHARACTER_SET_NAME, DEFAULT_COLLATION_NAME
-> FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'drupal9';
+----------------------------+------------------------+
| DEFAULT_CHARACTER_SET_NAME | DEFAULT_COLLATION_NAME |
+----------------------------+------------------------+
| utf8                       | utf8_general_ci        |
+----------------------------+------------------------+

EDIT2:
Running the following queries fixed the issue:
ALTER TABLE `key_value_expire` CHANGE `name` `name` VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'The key of the key/value pair.';

ALTER TABLE `key_value_expire` CHANGE `collection` `collection` VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'A named collection of key and value pairs.';

Answer: That happens because the character set the database is using isn't utf8mb4 or the collation isn't utf8mb4_unicode_ci (or utf8mb4_general_ci). Check also which collation the single database tables and the fields they contain use, and change it when necessary.
Install Drupal / Step 3: Create a database suggests those values for the database used from Drupal.

Note: The database should be created with UTF-8 (Unicode) encoding (utf8mb4) and either the utf8mb4_unicode_ci or the utf8mb4_general_ci collation. The difference between the two collations relates to how fast they are in character comparison and sorting. utf8mb4_general_ci is slightly faster and utf8mb4_unicode_ci is more accurate for a wider range of characters. If you are unsure use utf8mb4_unicode_ci.

If you are using UTF-8 characters for values that are saved in the database, you will have issues, if the database is set to use ASCII as character code for its tables.
Comment: I checked the affected table and you are correct. The database itself was using UTF-8 but the table 'key_value_expire' was using ASCII for both the 'name' and 'collection' columns. Not sure how that happened.
Comment: I checked and it seems like my database is using utf8_general_ci. Added more details to the original post.
Comment: We usually speak of *database*, but effectively the collation can be changed for single tables and even for single table fields. It's not that setting the collation for the database changes the collation of the existing tables; it just sets the default collation for tables created after changing collation. I updated the answer to make that clearer.


Image zoom is working once the page load, after changing the gallery, image zoom is not working

Question: Once the page load, code is working fine, after trying to change the set of images through ajax within same div, without refreshing the page, then zoom is not working
I assigned a variable and set the zoom, then disable the zoom using destroy method, then again enabled the zoom..
<code>    $(function(){
    var zoom;
     zoom = $(".rtwpvg-wrapper").find("img").magnify();
     $(".swatchinput").each(function(){
         $(this).click(function(){
            zoom.destroy();
            $(".rtwpvg-wrapper").find("img").magnify();
         });
     });
});
</code>
zoom Images should work even after replacing the images within same div
Comment: How is the HTML structured and which elements are replaced by JavaScript?
Comment: Hello, here I am sharing the demo link, please check this link, after selecting the size, imagezoom is not working https://www.mediajenie.com/demosites/tonirossi/product/maverick/
Comment: It might help to include a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) that demonstrates the issue in your question.
Answer: <code>window.imageZoom.kill();
window.imageZoom = new ImageZoom(container,options);
</code>
Comment: While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply.


What to do about an IT director who doesn't satisfy their job description?

Question: I had originally typed up a pretty long-winded preface to this question, but decided to nix it and keep this as generic as possible.
Our previous director left few months ago and a new one was hired shortly after that.  We're a pretty small IT shop, with three technical staff supporting a Windows corporate environment of ~300 computers (workstations + servers).  The previous director worked very closely along side of us in day-to-day operations.  We each have our own roles (a tech, DBA and director/network engineer), but we all cross-trained pretty well and picked up knowledge from each other.
That worked really well and we were pretty productive.  This new director does not seem to fill that niche the previous director left (and that niche was specifically listed in the job requirements).  What's more is the new director has a very limited skill set, to the point of admitting the most IT experience they have is being senior tech for some number of years at a previous agency.
My question is how do we convince management that they made a bad decision?  At this point the new director is doing more harm than good (waste of money in these economic times) and the money would be better spent on a dedicated network engineer, or someone who was at least more well rounded who we could then split the duties with.  I've talked with our main contact with management and brought up these same points.  I've flat out stated that they don't have the skills to perform the job and that alone should be grounds for dismissal.  All I've been told in return is "just keep an eye on things and support them with whatever they're doing since that's your job."
It's been two months and, while I still really love my job, I find it hard to keep myself motivated when I'm constantly having to correct them or teach them how to do their job.
I hope this isn't too whiney, I'm just trying to find some support from like-minded IT pros.
Comment: Community Wiki?
Comment: I appreciate everyone's honesty thus far.  It sounds like I'm probably being more of a problem in the situation than anything else and need to adjust my attitude.  This has definitely helped, thank you.
Comment: Regarding community wiki, I have no idea.  My goal was to make this generic but after re-reading a few times it seems more personal.  I suppose I could edit it and clean it up a bit if anyone thinks it's worth it.
Comment: I hope it works out for you.  Just for grins, how about giving us an update in a month or so?
Answer: At my old job, I too once thought as you do.  Our old director left to join a family business, and our new one was definitely not as advertised.  We were a 3 full-time, 2 part-time employee IT shop with about 25 servers and 250 workstations to support.
At first I grated about the situation.  I complained to my other fulltime co-worker, with whom I had been friends for quite some time.  We talked about what to do to convince our ultimate superiors that this man had been the wrong choice.  Then we finally realized something: we had more technical freedom than ever.
We took this opportunity to push forward with initiatives that we had long talked about implementing but never before had the influence to make happen.  Because we were so technically valuable to our new, but under-skilled boss, he was very willing to listen to our ideas and champion our causes.  In turn, we helped him increase his skillset dramatically, and by the time I left that job to move cross-country to be closer to family, he had grown into one of the best managers I've ever had.
I'd either try to "take lemons and make lemonade" as we did, or consider another position for yourself.  If he's truly as bad as you say, then it will be exposed naturally.  Otherwise, you will be painted as a complainer, and you'll help get another man fired who, like you, is trying to make it through these tough times.
Bottom line: give the guy more than two months, be a team player, and find ways to make this situation beneficial for everyone involved, including your new boss.  If they wanted your approval, you would have been part of the hiring process.
Comment: Wow, our situations do sound a lot alike.  The other guy and I are good friends as well and we have been trying to work out a solution.  We certainly aren't hell bent on getting the new person fired.  What you guys ended up doing is pretty inspiring and I might just bright that up and see if we can roll with it.  Thank you.
Answer: You don't mention specifically what the new director is doing to be "more harm than good".  You also don't mention whether or not you've even spoken directly to this new director.  Could it be that management has hired an I.T. director with little to no I.T. experience?  It happens.  Is it good for I.T.?  It depends.
Perhaps they're filling a much needed business-end function that was missing in your previous director.  You probably aren't privy to all the management discussions affecting business.  All that you see is what affects you from the I.T. side of things.  Maybe this new director is good at translating business needs into technical solutions.
In all honesty, you don't sound like someone I'd like to work with.  Two months is not a tremendous amount of time to learn a new job, especially in light of "I find it hard to keep myself motivated when I'm constantly having to correct them or teach them how to do their job."  I would venture to guess that part of your job is training new employees.
I'm pretty sure the director isn't hired to satisfy your needs, but the needs of the company in general.  The way that you've stated what you've stated is rubbing me the wrong way.
Comment: Sorry, I had written in the first rendition that we have talked with the new director directly.  We've asked how they plan to address some of the network gaps now that the old director has left and I was told that since I had expressed interest in it that I should try and figure it out.  That was frustrating in itself.

I appreciate your honesty and reading these has helped me realize that my complaining isn't helping anything.
Answer: How to advance your Career, in Two Short Lessons

Make your boss look good.
Take care of your people.

Anybody who does these two things will have a pleasant and fruitful career.  You're about to screw up number 1 big time!
Answer: The short answer to the asked question is .. YOU CAN'T DO ANYTHING.
If the new guy is indeed lacking competence, management will figure it out soon enough.  If they valued your judgment about this position, they would have asked you before they hired him.  They didn't.  They certainly aren't interested in your second guessing their decision.
You have no idea why they hired this guy.  It could be that he is short of experience but is sharp, and will pick up what he needs to know on the fly.  It could be that he has some skill or experience the execs need that isn't on the job description.  It could be that he is engaged to the owners daughter, or is sleeping with someone important.  But whatever the reason, nothing good can come from badmouthing your boss.
My advice is to leave.  Quickly.
The single worst career move a person can make is to undermine their direct supervisor.  That you did so advertises that you lack loyalty, and that you can't be relied on to to watch your supervisor's back.  Who is going to want to work with you?  Your colleagues are wondering what you say about them when they screw up.  The new guy will find out that you tried to get him fired, and will shoot back.  He probably already knows, so your job is likely in jeopardy.  Were I the person you are discussing I would be interviewing for your replacement.
The only chance you have to salvage this situation is to support the new guy, above and beyond the call of duty.  Do your best to make him look good, follow his instructions, and do your own job exceptionally well.  If you have to clean up after him from time to time, or teach him things that you think he ought to know, do so quietly.  If you are asked by others about the new guy, say how you are getting to know him and are adjusting to him.  If you get asked about the previous comments, disavow them in the strongest possible way.  Beyond that, keep your mouth shut.
"It's better to stay silent and look a fool, rather than speak and remove all doubt." - Mark Twain
Good luck.
Comment: What you said about them not liking us second guessing their decision does make sense.  I was hoping we'd be able to reason with them somehow and they would value the opinion of the rest of the IT staff.
Answer: Short answer: You're probably screwed.
I'm not going to get into whether you're whining or not - w/out knowing more about how things were before the new IT Director came along and how they are now, it's impossible for us reading this to judge.  One way or another, though, things have changed and you have to figure out what you're going to do.
phoebus just posted an example of changing what started as a bad situation, and that sort of thing can be done, but it depends on the personalities: is the new guy willing to support his new team?  If he is, then it can be a temporary problem to have a boss  you don't think is very good.
On the other hand, if the new IT Dir. is not willing to listen to you and work with your ideas, then you are probably not going to be able to change the situation.  Convincing higher-ups that they've made a bad decision because you think it's bad is hard to do.  If they thought you should have input into the selection of the new guy, they would've asked you up front.  They might have picked someone that they feel they can talk to (maybe a guy w/ an MBA who knows how to talk to CEOs, CFOs, any other Cs...
I've had two similar experiences: the first one wasn't in my department, it was a new CFO who turned out to be a nutcase and the Pres/VPs who picked her realized it and got rid of her.  But it took several months.  It's not like they stuck their heads in the sand, but having picked her they felt they had to be sure they gave her ever chance to fit in and it wasn't until they'd tried that they dumped her.
More recently, during a merger, I had an IT Director "imposed" on me.  He'd been the IT Dir. from one of the merging companies as well as their communications director.  He had an MBA and had worked with their IT dept. for a few years.  Eventually, he re-organized the merged IT department and I would've been left in a clearly subordinate position, so I took the opportunity to get paid out and left.  His style was just too different from what I was used to, but it was re-assuring to upper management to have a guy w/ an MBA to talk to.  I wasn't alone in disliking his schmoozy style and a few others left as well.
Sorry, too much rambling...

If you can work with the new guy and he can appreciate your work, you might be able to forge a good working relationship with him.
If you can't work with him, I'd say it's unlikely that you can convince the higher-ups that hiring the guy was a mistake.
If you can't work with him, your choices are to stay and suffer or to leave.
Answer: Well, you don't want to be on management's watch list. And whether you perceive it or not, the IT director is management.
So, you can be certain that when they all sit around talking management talk and sipping their Johnnie Walker Blue Label, they talk about these things. The IT director will mention that you seem to be a bit something-or-other out of sorts, and someone else will mention that oh yeah, maik was in here with this list of complaints, yadda yadda yadda, what are we gonna do about this...
...and BAM!, maik is a complainer, not a team player, constantly questions management's decisions...
...at best, it's a good excuse to not give you a raise one year, at worst, well, President Obama just extended unemployment benefits again...
Seriously, you'll do a lot more for your company, your new IT director, and yourself if you'll make the effort to help the person grow into this new position. It will pay off in the long run. It sounds like the person isn't incompetent, but just lacks certain skills. The skills can be learned, and it sounds like the director is at least trying to do that. Give the person a chance.
Comment: We all know the skills can be learned, but our biggest complaint up to this point is that the skills aren't present.  It's frustrating in that they have to try to learn the skills to fulfill they job they were hired for.  It feels like we're working backwards after making so much forward progress previously.
Answer: First, a story.  Sometimes, you're just stuck.  That's what happened to me.  I worked in an IT department of 20 people.  Turnover had been, perhaps, 2 people per year.  But everyone enjoyed working there and the director was the kind of person who ASKED his subordinates for their opinions and, in fact, if I had an idea I thought could help the company, I could write up a proposal and bring it to him.  If he liked it, he'd try to get the money for it in the next budget year.  And helping the others in the department so that we each got some experience in another field - or few other areas - was common.
Then he left.  They promoted an internal person... but he stepped down after 6 months.  then for another 6 months, the two assistant directors (including the guy who stepped down) ran the department.  They finally hired another person who seemed ok... until he was fired (not sure why) about 6 weeks later.  Then another six months went by and they hired another guy... On paper, he looked great... in reality, well, we started referring to him as DH.  Not just me and a couple of other guys... but the ENTIRE department.  Not "designated hitter", but something similar to (but less kind than) "Department Head"... After 18 months I left.  I gave 3 weeks notice and once I did, he didn't say a word to me - not a good morning nor a goodnight and never asked me to do anything.  Under his watch, half the department left in 2 years.  He was finally removed (not sure the exact circumstance - some people say he was given a deadline to leave).  But he lasted there 4 years and, in my opinion (and most others who I knew who worked there), destroyed the department.
So... the moral?  You have to let him dig his own grave.  If it's unbearable, leave.  If not, cross your fingers and try to stick it out.
What COULD you do?  ANYTHING you do, tread VERY LIGHTLY.  I would suggest, if it bothers you as much as the guy I had to work for bothered me (but hopefully, the guy you're working for is less arrogant), you could talk to him.  NICELY.  "Mr. Smith, I was wondering... is there any plan to hire a more technically skilled person in the near future?  I'm concerned because, as you have expressed, your not as technically skilled as our previous director and we're having some difficulty keeping the level of service as strong as it was."
If he is arrogant, then I would suggest you start documenting EVERYTHING... because sometimes, people can get vengeful and documenting every move you make, while a pain and unpleasant, can help you keep your job if something happens later.  If nothing else, it helps you formulate your resume later because you can easily recall everything you did.