How to use UIScrollView with complex picture

Question: I have a complex picture . It consists of several layers. Each layer is a picture .
for example , background picture -> man picture -> gun picture -> foreground picture
I want drag and use pinch gesture with complex picture .
Can i do it with UIScrollView ?
Answer: What happens if you make all the UIImageViews of your complex picture and put them in a UIScrollView (I'm assuming that you've tried this before asking your question?)
i.e from inside a view controller :
<code>- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    UIImageView *i1 = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"backgoround.png"]] autorelease];
    UIImageView *i2 = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"man.png"]] autorelease];
    UIImageView *i3 = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gun.png"]] autorelease];

    UIView *v = [[[UIView alloc] initWithFrame:[[self view] bounds]] autorelease];
    [v addSubview:i1];
    [v addSubview:i2];
    [v addSubview:i3];

    return v;
}
</code>
Comment: What i should return in this method ?                                  - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView


Solving $x$ for $y= 3^x-2^x$

Question: Is there a way to solve for $x$ given the function: $$y= 3^x-2^x$$ in terms of $y$?
I tried a lot of algebraic manipulations but I ended up nothing. Or, should we say it it impossible to do so?
Comment: It's $\rm\ Z^C - Z\: =\: Y\ $ for $\rm\ Z = 2^X,\:\ C = log_2 3$.
Comment: $x,y$ are what?  Natural numbers?
Comment: any positive real numbers
Answer: There is no expression for $x$ in closed form as an elementary function of $y$.
Comment: How come? is there a proof why it has no closed form? If not elementary, is there a closed form? thanks
Comment: These proofs aren't easy, and I certainly can't come up with one myself. Do a search for terms like "closed form" and "elementary function" and you may see what you are up against.
Comment: thanks. But, is there a form extending from elementary functions?
Comment: Not that I know of. But I could be wrong - not every function is my personal friend.

Solving $x$ for $y= 3^x-2^x$


Commerce Products Display Page Using Views

Question: The usual way to display Commerce products is
1. Create Products using Commerce Module Interface
2. Create a Content  Type for Products Line Items by referencing the products
But I have too many different products... should I have to create contents after adding each commerce Products??
I used two views for each products one to create a products listing and other for product display page using contextual filters and by passing the Product ID
Product Listing Page path : /products-list
Product Display Page      : /products/product1
By passing the product ID via URL.
Is this a write way to do it... Or is there anything efficient and meaningful than this method?
Answer: You can use this module "https://www.drupal.org/project/commerce_auto_product_display". then you can use Views to show the product display nodes.
Comment: Thanks for you advice.. This module works pretty cool.. :) But should I have to create a node page for each product.. That keeps disturbing me :(
Comment: yes, you can read some more about that here : https://drupalcommerce.org/user-guide/product-displays. Also here is a very good video explains it as well: https://drupalize.me/videos/adding-product-displays?p=1154


Is it possible to move the "Primary Hierarchy" Public Folder mailbox in Exchange 2013?

Question: We want to delete one of our mailbox databases but before doing that, all mailboxes need to be moved/migrated to a different database. One of these mailboxes is a Public Folder mailbox and it also happens to be the Primary Hierarchy.
I read somewhere that without the Primary Hierarchy, all secondary PF mailboxes will not be accessible and something happening to the primary could be disastrous.
Since the primary hierarchy is unique is it still okay to migrate it to a different database and will the migration cause any downtime for other PF mailboxes?
Answer: Yes, the migration will cause downtime which depends on the size of the public folder mailbox, the move may take several hours to complete. During that time, users won't be able to access the public folders. Users also won't have access to public folders for a brief period while the folder is in the "Completion in Progress" state. Details see: <code>[Move a public folder mailbox to a different mailbox database][1]</code>
Comment: Thanks for the response! Downtime is fine but moving the primary hierarchy can cause no other issues such as access corruption of the other public folders or something?
Comment: In theory, this will not cause any issue.


Where can I find the link between field answers and the user who submitted it?

Question: Noob here. I can't figure out how entity forms stores which user submitted each answer for it's fields on the database.
All I can see is a table for each field, and the columns within being: Entity_type, bundle, deleted, entity_id, revision_id, language, delta & Field_(the name of my field).
None of which tells me which user submitted each answer. Yet drupal and entity forms clearly knows which user submitted each answer, because when I go to (Administration > Structure > entityform types > my form > form submissions) I can see a table of every submission with the name of each user who submitted it, and I can see all their answers.
So where the heck is this being stored on the database? If it matters, my database was built with phpmyadmin.
Thanks in advance for your help, I really appreciate it. I'm sorry if my terms are all jumbled and wrong.
Answer: Look for "entityform" table - column "uid" gives you user id of the user who submitted the form.


MS O365 Outlook Api ambiguity when retrieving emails from emailbox

Question: I currently have wrote an application that retrieves messages from an O365 account and process them to my liking.  Currently I have stressed tested this application with up to 150 emails.  But I am very uncertain about the Api scalability when my application is processing more than 150 email in my specified folder.  For example how about 500 emails?  The documentation does not give me a vote of confidence that it will scale that high.
For Example:
<code>    OutlookServicesClient expenseEmailBox = Start_OutLook_Services();
        try
        {
            var Email_Box = expenseEmailBox.Users[emailAccountToUse].Folders[foldertoSearch].Messages.Where(m => m.HasAttachments == true).Expand(m => m.Attachments).ExecuteAsync();

            //what happens to stuff past the current page?
            var messages = Email_Box.Result.CurrentPage;

            foreach (var message in messages.OrderByDescending(m => m.DateTimeReceived))
</code>
what happens past the current page? does the current page only load 250? and then it stops reading the emails and drops them ?  What is currentpage actually meant to do? The Api doc has no explanation for this.
Answer: Actually the API scales as per your subscriptions. You have limited number of requests to execute per day or in other scenarios message, recipient, retentions limits and more. Read more on the link provided and make sure that you do not cross these limitation of your current o365 subscription.
https://technet.microsoft.com/en-us/library/exchange-online-limits.aspx
Hope this helps.


Alert Dialog not popping up in showbottommodoalsheet function

Question: I have a function showBottomModalSheet where the user enters data into a text field. I want to validate the text field to make sure its not empty when the user presses the button and if it is show an alert dialog, but for some reason my alert dialog is not showing up.
ElevatedButton(
    //button to confirm entry
    onPressed: () async {
        //if else check that none of the entries are empty
        if (_exercisenameController.text.isEmpty ||
            _totalweightController.text.isEmpty ||
            _totalrepsController.text.isEmpty) {
            print('Do you even lift');

            AlertDialog(
                title: Text('Do you even lift'),
                content: SingleChildScrollView(
                child: ListBody(
                    children: const <Widget>[
                        Text('All Input fields must be filled.'),
                    ],
                ),
                actions: <Widget>[
                    TextButton(
                        child: const Text('OK'),
                        onPressed: () {
                            Navigator.of(context).pop();
                        },
                    ),
                ],
            );
        } else {
            //Save new journal
            if (id == null) {
                //if the item doesnt exist
                await _addItem();
            }

            if (id != null) {
                //if it exists update it instead
                await _updateItem(id);
            }
        }

        // Clear the text fields
        _exercisenameController.text = '';
        _totalweightController.text = '';
        _totalrepsController.text = '';

        //closing the popup
        Navigator.of(context).pop();
    },
    //the text of the button change depending on if its new or updating an existing
    child: Text(id == null ? 'Create New' : 'Update'),
)

I was expecting it to show an alert dialog and when you click okay it goes back to the showBottommModalSheet.
Answer: Try something like this, where instead of just returning the AlertDialog you call showDialog on it inside your button's onPressed:
showDialog(
            context: context,
            builder: (BuildContext context) {
                return AlertDialog(
                    title: Text('Do you even lift'),
                    content: SingleChildScrollView(
                    child: ListBody(
                        children: const <Widget>[
                            Text('All Input fields must be filled.'),
                        ],
                    ),
                    actions: <Widget>[
                        TextButton(
                            child: const Text('OK'),
                            onPressed: () {
                                Navigator.of(context).pop();
                            },
                        ),
                    ],
                );
            });

fyi: I don't have an IDE with me, so I'm guessing syntax, but I'm pretty confident there's a function that's called this or very similarly named to this that works and pops up a dialog :D


Mule Embedded: how to run application

Question: I have a simple Mule application that runs on a standalone Mule server.
Is it possible to create a jar file for that application that would be possible to run without necessity of installing a standalone Mule server i.e. just on JRE?
Is it called mule "embedded"?
How to do it if so?
Answer: It is possible to embed mule into java application and a web application. Check here for more details - https://docs.mulesoft.com/mule-user-guide/v/3.7/embedding-mule-in-a-java-application-or-webapp
Update:
How to get jar for embedding?

You can checkout the Mule Community code and build the jar - https://github.com/mulesoft/mule/tree/mule-3.7.3/distributions
Download embedded jar from https://developer.mulesoft.com/download-mule-esb-runtime.

You can then add this jar to classpath of your application jar.
Remember from document -

Before running Mule in embedded mode in either a Java application or a Web app, be sure to manually update all the required dependencies for your application. The Mule ESB Embedded   Single .jar contains all Mule classes, but you need to include the dependencies manually.

So you might have to play around dependencies (I didnt get chance to try it out myself).
Once you have jar on class then you can follow instruction on https://docs.mulesoft.com/mule-user-guide/v/3.7/embedding-mule-in-a-java-application-or-webapp for how to start/stop/use flows.
Comment: Yes, I've seen the link already. It doesn't quite answering my question however. So, I have the app. What exactly needs to be done to make an embedded jar that would run it?
Comment: I edited my answer to add some more information. I didnt get chance to try this out but I think it might help you.
Comment: Yeah, the tricky thing is getting the dependencies. I've failed to do this manually. I hope there is way to do this using Maven with a help of mule plugin.
Comment: Try with maven pom of mule 3.7.0 at http://search.maven.org/#artifactdetails%7Corg.mule%7Cmule%7C3.7.0%7Cpom. It has dependencies there. If it works, dont forget to update back here :)

Mule Embedded: how to run application


Merge more than 2 dataframes

Question: I have 23 dataframes that I need to merge. I have read that you can merge them by putting them into a list. All of the sheets have the same column names but somewhat different rows. I would like to merge them on the column 'RowNo'. Not all the rows in the sheets will merge on 'RowNo' though. I would like the leftover rows to be included in the merge as well. I believe this is called an outer join.
Example of df:
Row No   Horse    Weight
112               55
115      Winx

Example of another df
Row No   Horse    Weight
112      Black
115      Winx     54
117      Pharlap  51

Desired output:
 Row No   Horse    Weight
 112      Black    55
 115      Winx     54
 117      Pharlap  51

Answer: Using functools:
import pandas as pd
from functools import reduce

dfs = [df1, df2, df3, df4, df5, ...]
df_final = reduce(lambda left, right: pd.merge(left, right, on="RowNo"), dfs)

Merge more than 2 dataframes


What is the justification for the vector $(b, -a)$ being orthogonal to $\mathbf{V}=(a,b)$?

Question: I am currently studying the textbook Partial Differential Equations: An Introduction, second edition, by Walter A. Strauss. Chapter 1.2 First-Order Linear Equations says the following:

Let us solve
$$au_x + bu_y = 0,$$
where $a$ and $b$ are constants not both zero.
Geometric Method The quantity $au_x + bu_y$ is the directional derivative of $u$ in the direction of the vector $\mathbf{V} = (a, b) = a \mathbf{i} + b \mathbf{j}$. It must always be zero. This means that $u(x, y)$ must be constant in the direction of $\mathbf{V}$. The vector $(b, -a)$ is orthogonal to $\mathbf{V}$. The lines parallel to $\mathbf{V}$ (see Figure 1) have the equations $bx - ay = \text{constant}$. (They are called the characteristic lines.) The solution is constant on each such line. Therefore, $u(x, y)$ depends on $bx - ay$ only. Thus the solution is
$$u(x, y) = f(bx - ay), \tag{2}$$
where $f$ is any function of one variable.

What is the justification for the vector $(b, -a)$ being orthogonal to $\mathbf{V}$? And I mean this in terms of proving/justifying the one-sided implication "something implies that the vector $(b, -a)$ is orthogonal to $\mathbf{V}$" (so $\text{something} \Rightarrow \text{the vector $(b, -a)$ is orthogonal to $\mathbf{V}$}$), rather than the converse implication "the vector $(b, -a)$ is orthogonal to $\mathbf{V}$ implies something" ($\text{the vector $(b, -a)$ is orthogonal to $\mathbf{V}$} \Rightarrow \text{something}$). Furthermore, I'm looking for a justification that starts without knowledge of $(b, -a)$, and then derives $(b, -a)$ itself.
Comment: Then you solve the equation $(a,b).(x,y)=0(\iff ax+by=0)$. One solution is $(x,y)=(b,-a)$.
Comment: The fact that $(a,b).(b,-a)=0$ implies that $(b,-a)$ is orthogonal to $(a,b)(=\mathbf V)$.
Comment: @JoséCarlosSantos Oh, that's true. But I was looking to start without knowledge of $(b, -a)$, and then deriving $(b, -a)$ itself, if that makes sense.
Comment: @JoséCarlosSantos Ahh, yes, you're right. That answers my question. Thanks!
Comment: It was not clear to me that this is what you wanted. I have posted it as an answer.
Answer: The vectors which are orthogonal to $(a,b)(=\mathbf V)$ are the vectors $(x,y)$ such that$$(a,b).(x,y)=0(\iff ax+by=0).$$And a solution of $ax+by=0$ is $(x,y)=(b,-a)$.


MYSQL join and group by five field per store

Question: I'm trying to get a complex (at least to me) MySQL query, and I can't get the result that I want.
I have one DB with 2 tables:
stores

id, name

products

id, store_id, hardware, name, price, url, notify

I want to get 3 products per store_id with notify = 1, hardware = 'gpu' and order by price asc.
So if I launch this SQL sentence:
SELECT s.name as store, p.id as id, p.name as name, p.hardware as hw, p.price as price, p.url as url, p.notify as notify
FROM products p JOIN stores s
ON p.store_id = s.id
AND p.hardware='gpu'
AND p.notify = 1
GROUP BY store
ORDER BY p.price asc;

I only get one product per store_id, and I'd like to get (maximum) tree elements per store_id. Something like next example:

store
id
name
hw
price
url
notify

store1
1
name1
gpu
price
url
1

store1
2
name2
gpu
price
url
1

store1
3
name3
gpu
price
url
1

store2
8
name8
gpu
price
url
1

store2
12
name12
gpu
price
url
1

store3
22
name22
gpu
price
url
1

And so on...
How can I do that?
Example data
stores
CREATE TABLE `stores` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(50) NOT NULL,
  `afiliate` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;

products
CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `store_id` int(11) NOT NULL,
  `hardware` char(50) COLLATE utf8mb4_unicode_ci NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `price` decimal(10,2) NOT NULL,
  `notify` tinyint(4) NOT NULL
  PRIMARY KEY (`id`),
  KEY `Store_id_to_products` (`store_id`),
  CONSTRAINT `Store_id_to_products` FOREIGN KEY (`store_id`) REFERENCES `stores` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1961 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

select id, name from stores;

result

id
name

1
Amazon

2
Ebay

3
BestBuy

4
Target

select * from products;

result

id
store_id
hardware
name
price
notify

1
3
gpu
EVGA GeForce RTX 3070 FTW3 Ultra Gaming 8GB GDDR6
949.00
1

2
3
gpu
Zotac Gaming GeForce RTX 3090 Trinity OC 24GB GDDR6X
2259.00
1

3
3
gpu
EVGA GeForce RTX 3090 FTW3 Ultra Gaming 24GB GDDR6X
2749.00
1

4
3
gpu
Asus TUF Gaming GeForce RTX 3090 OC Edition 24GB GDDR6X
2549.00
1

5
1
gpu
Gigabyte GTX 1660 Super OC 6G
489.00
1

6
1
gpu
Asus TUF GTX 1660 Super OC 6GB
428.99
1

8
1
gpu
GIGABYTE RTX 3060 GAMING OC 12GB
689.00
1

9
1
gpu
Gigabyte RTX 3080 Aorus Master 10GB
1398.99
1

10
2
gpu
Asus ROG Strix RTX 3080 OC 10GB Blanca
1312.00
1

11
2
gpu
Gigabyte RTX 3080 Gaming OC 10GB
1258.99
1

12
2
gpu
Asus ROG Strix RTX 3090 OC Gaming 24GB
2599.00
1

13
4
gpu
Asus TUF Gaming Radeon RX 6800 OC 16GB
1078.99
1

14
4
gpu
GIGABYTE RX6800XT GAMING OC 16GB
450.00
1

15
4
gpu
Gigabyte GeForce GTX 1660 Ti OC 6G
499.95
1

16
4
gpu
ZOTAC GeForce GTX 1660 SUPER Twin Fan
529.95
1

I'm trying to do a SQL sentence that get 3 cheapest products per store. This is the result that I want:

id
store_id
hardware
name
price
notify

1
3
gpu
EVGA GeForce RTX 3070 FTW3 Ultra Gaming 8GB GDDR6
949.00
1

2
3
gpu
Zotac Gaming GeForce RTX 3090 Trinity OC 24GB GDDR6X
2259.00
1

4
3
gpu
Asus TUF Gaming GeForce RTX 3090 OC Edition 24GB GDDR6X
2549.00
1

5
1
gpu
Gigabyte GTX 1660 Super OC 6G
489.00
1

6
1
gpu
Asus TUF GTX 1660 Super OC 6GB
428.99
1

8
1
gpu
GIGABYTE RTX 3060 GAMING OC 12GB
689.00
1

10
2
gpu
Asus ROG Strix RTX 3080 OC 10GB Blanca
1312.00
1

11
2
gpu
Gigabyte RTX 3080 Gaming OC 10GB
1258.99
1

12
2
gpu
Asus ROG Strix RTX 3090 OC Gaming 24GB
2599.00
1

14
4
gpu
GIGABYTE RX6800XT GAMING OC 16GB
450.00
1

15
4
gpu
Gigabyte GeForce GTX 1660 Ti OC 6G
499.95
1

16
4
gpu
ZOTAC GeForce GTX 1660 SUPER Twin Fan
529.95
1

Thanks in advance!!
Comment: Could you add the example datas that provide your expected result and  tables `products`, `stores` description as well ?
Comment: Which version of MySQL? (The "cheapest three per store" is *much* easier in MySQL8, but it looks as though you're using 5.x?)
Comment: @MatBailie mysql  Ver 15.1 Distrib 10.3.29-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2
Answer: If your MySQL version is lower than 8+ you could use :
SELECT
      t1.id,
      name,
      hardware,
      price,
      notify
FROM (
        SELECT
              id,
              store_id,
              hardware,
              notify,
              price,
              @rn := IF(@prev = store_id, @rn + 1, 1) AS rn,
              @prev := store_id
        FROM products
        JOIN ( SELECT @prev := NULL, @rn := 0) AS vars
        where hardware='gpu' and notify=1
        ORDER BY  price ASC
    ) AS t1
INNER JOIN   stores st on  t1.store_id=st.id
WHERE rn <= 5
ORDER BY   id asc ;

Demo
In MySQL 8+
WITH my_table  AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY store_id ORDER BY  price ASC ) AS rownum
  FROM products
)
SELECT my_table.id,st.name,hardware,my_table.name,price,notify
FROM my_table
INNER JOIN  stores st on  my_table.store_id=st.id
WHERE  rownum <= 5
order by my_table.id asc;

Demo
Comment: @jask updated both queries
Comment: I love you sooooo much !! hehe thanks a lot
Comment: are there any way to return store name instead of store_id ?
Comment: You are the best !!!


I ufw deny 53, but an nc scan reports a successful connection

Question: Why is an nc scan able to successfully connect with port 53 when I've denied it through ufw?
I noticed port 53 is listening:
<code>$ sudo ss -tulpne

Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
udp UNCONN 0 0 0.0.0.0:5353 0.0.0.0: users:(("avahi-daemon",pid=514,fd=12)) uid:115 ino:18620 sk:1 <->
udp UNCONN 0 0 127.0.0.53%lo:53 0.0.0.0: users:(("systemd-resolve",pid=356,fd=12)) uid:102 ino:15766 sk:2 <->
udp UNCONN 0 0 10.0.2.15%ens3:68 0.0.0.0: users:(("NetworkManager",pid=538,fd=19)) ino:21287 sk:3 <->
udp UNCONN 0 0 0.0.0.0:51675 0.0.0.0: users:(("avahi-daemon",pid=514,fd=14)) uid:115 ino:18622 sk:4 <->
udp UNCONN 0 0 0.0.0.0:631 0.0.0.0: users:(("cups-browsed",pid=571,fd=7)) ino:18922 sk:5 <->
udp UNCONN 0 0 0.0.0.0:43745 0.0.0.0: users:(("systemd-timesyn",pid=355,fd=16)) uid:100 ino:41918 sk:6 <->
udp UNCONN 0 0 [::]:5353 [::]: users:(("avahi-daemon",pid=514,fd=13)) uid:115 ino:18621 sk:7 v6only:1 <->
udp UNCONN 0 0 [::]:38831 [::]: users:(("avahi-daemon",pid=514,fd=15)) uid:115 ino:18623 sk:8 v6only:1 <->
tcp LISTEN 0 128 127.0.0.53%lo:53 0.0.0.0: users:(("systemd-resolve",pid=356,fd=13)) uid:102 ino:15767 sk:9 <->
tcp LISTEN 0 5 127.0.0.1:631 0.0.0.0: users:(("cupsd",pid=487,fd=7)) ino:18380 sk:a <->
tcp LISTEN 0 5 [::1]:631 [::]:* users:(("cupsd",pid=487,fd=6)) ino:18379 sk:b v6only:1 <->
</code>
So I close that port through the ufw:
<code>$ sudo ufw deny 53

$ sudo ufw status verbose

Status: active Logging: on (low) Default: deny (incoming), allow (outgoing), disabled (routed) New profiles: skip

To Action From

53 DENY IN Anywhere
53 (v6) DENY IN Anywhere (v6)
</code>
And when I do an nc scan, I see a successful connection with the port:
<code>$ sudo nc -zv 127.0.0.53 50-53

nc: connect to 127.0.0.53 port 50 (tcp) failed: Connection refused
nc: connect to 127.0.0.53 port 51 (tcp) failed: Connection refused
nc: connect to 127.0.0.53 port 52 (tcp) failed: Connection refused
Connection to 127.0.0.53 53 port [tcp/domain] succeeded!
</code>
I expected the firewall to prevent this connection
Why is the firewall not preventing the connection? Please help me correct my thinking
SIDENOTE: I know port 53 is used by dnsmasqd and that there are many good reasons to keep the port open. But in this question, I am solely concerned with the effective closing of ports through the firewall. I also know I can prevent this port from listening by editing /etc/systemd/resolved.conf
Answer: ufw does not block any localhost connections. These are always allowed.


String skip on guitar

Question: I am fairly new to playing the electric guitar and my question is:
How do I play something like this?
This is an example of one of Rise Against songs, Injection.
The x means do not play that string.
<code>|-------------------
|-------------------
|-16-16-16-15-15-15-
|--x--x--x--x--x--x-
|-14-14-14-13-13-13-
|-------------------
</code>
How can I play the two notes simultaneously without playing the one in between?
Is there some kind of a technique for playing this?
Thanks a lot in advance, guys.
Cheers.
Comment: **Welcome to Music.SE!** Yes, we have had quite a few posts about this before. The x tells you to damp that string, in order to play octaves. I'll have a look through our posts and try to point you in the right direction. In the meantime, you could try searching for "octaves on guitar", "damping" etc.
Comment: Damping is also called "muting" by some.
Comment: Well, I know what palm muting is and I can easily do it. However, this is something different.
Answer: This TAB notation shows a typical way to play octaves on guitar. As it is not possible to play an octave on adjacent strings (because the stretch would be too big at 7 or 8 frets) an octave is typically played on a pair of strings which have an unplayed string between. This is easy to do fingerstyle, when playing classical guitar, for instance, but is more difficult with a pick, as you have to make sure the string between the notes you want doesn't sound.
So, you have to damp (or choke, or mute) this string. This is what the 'x' denotes. This is actually pretty easy to do; you use what I call "lazy technique" when describing it to my pupils! Usually, when playing chords on the guitar, you want to try not to touch adjacent strings with your left-hand fingers when fingering chords, in order not to stop any notes sounding (barre chords being an obvious exception). And so, you usually try to keep your left-hand fingers pointing straight towards the fretboard. In order to mute the string between the octave notes, though, you let your left-hand fingers flatten slightly (approaching the string at a 45 degree angle, or even flatter) so that they damp the muted string. Usually, this means that the index finger on the left-hand will damp the string between the octave notes (the string with the 'x' marks).
However, you can actually damp the string below the bottom note of the octave with the tip of your index finger; you can also damp any strings above the top note of your octave with either a combination of fingers, or just the finger playing the top note of the octave, so you can actually strum all the strings! This gives a great, percussive sound, and means you can really go for it with your strumming.
I'm a bit lazy, so I use fingers 1 and 4 for octaves most of the time, whether I'm stretching over 3 or 4 frets. In the picture below, I'm damping string 6 with the tip of my index finger, damping string 4 with my index finger, damping string 2 with my pinky and damping string 1 with the first joint from the hand of my index finger. And this is done while playing the octave notes on strings 5 and 3, with index and pinky fingers respectively.

Sorry it's a bit hard to see what I'm doing in the picture, I'm not very good at taking pictures of my hands while fretting! (At least you get to see my cat, though...)
So, the octave I'm fretting above can actually be written like this:

Just to be clear, you only actually need to damp the string between the octave notes, but this does mean you need to play reasonably carefully with the pick, so that you only strum three strings. If you damp more strings, you can go mad with your strumming, Pete Townshend style (windmill away...!)
Comment: I personally would use my ring finger instead of my pinky finger, but  besides that I completely agree.
Comment: Yeah, like I say, I'm lazy. I think I use 1 and 4 by default as it feels close to the R 5 8 "power chord" shape. I tend to use 1 and 3 if changing a lot between the three fret and four fret octave shapes, though (e.g. string 5 root to string 4 root). And then I would, of course, use 1 and 4 for the four fret shape...

String skip on guitar


Can a ii° built on ^2 of the harmonic minor scale with an added 6th function as a fully dimished 7 chord?

Question: The added raised ^7 from using harmonic minor allows for a chord that is enharmonic to a fully dimished 7th
chord but built on ^2 not ^7. Can this chord be used as a fully diminished 7th chord?
Comment: That's the thing - ii°4/2 and vii°7 are enharmonically equivalent, so what is preventing me from interpreting your (however inverted) ii°7 chord as a (however inverted) vii°7 chord instead? (Hint: the harmonic function.)
Answer: You're asking the question the wrong way round!   How DOES a dim7 chord function?  The main feature of a dim7 chord is that it can function in all sorts of ways. It's the ultimate multi-purpose pivot chord!  One contrived in the way you describe can lead the harmony off in many directions.
Answer: It is a full diminished chord in its own right, so, yes.
Answer: Yes and no. Fully diminished seventh chords, because they are enharmonically equivalent, are often used interchangeably. That is to say, they are frequently used as pivot chords, spelled according to one key, but used dually.
The chord built on ^2 would be spelled ^2 ^4 ^b6 ^b8, and the chord built on ^7 would be spelled ^7 ^2 ^4 ^b6. The ^2 version would, by default be viio7/iii and the ^7 version would be viio7, but in a highly chromatic setting, they would essentially be equivalent, and the spelling would depend on usage and clarity.
Comment: Aaron, why would the chord built on 2 have a ^b8?, wouldn't it be a raised 7? Or would it be spelled as b8 because it is in the key of iii?
Comment: @armani One of the basic ideas in music theory is that chords are made up of thirds. A chord spelled with ^6 and ^7 would contain a second; a spelling with ^6 and ^1 would be a third. So ^b6 - ^b8 is a minor third; ^b6 - ^#7 is an augmented second, which would signal a chord inversion rather than root position.


$\operatorname{Proj}k[x,y,z]/(xz,yz,z^2)$ isomorphic to $\mathbb{P}^{1}_{k}$

Question: While dealing with the Proj construction, I encountered with this seemingly-simple question, but somehow I can't get the point at this moment.

Is the scheme $$\operatorname{Proj}k[x,y,z]/(xz,yz,z^2)$$ isomorphic to the projective line $\mathbb{P}^{1}_{k}$, where $k$ is a field?

I considered the morphism
$$k[x,y,z]/(xz,yz,z^2)\to k[x_{0},x_{1}]$$ given by the evaluation $$(x,y,z)\mapsto(x_{0},x_{1},0)$$ and its induced morphism $$\mathbb{P}^{1}_{k}\to \operatorname{Proj}k[x,y,z]/(xz,yz,z^2)$$ which should be well-defined in this case. But I don't know what to do to check this is indeed an isomorphism.
Any help or hint will be appreciated!
Comment: look at the radical of the ideal.
Comment: Taking the radical loses information.
Answer: Hint: The surjective homomorphism $f^\# : k[x,y,z]/(xz,yz,z^2) \to k[x,y]$ (with $z \mapsto 0$) of graded algebras is an isomorphism when localized at $x$, $y$ or $z$ resp. the images.
More details: Let $X=\mathrm{Proj} k[x,y,z]/(xz,yz,z^2)$ and let $f : \mathbb{P}^1 \to X$ be the closed immersion induced by $f^\#$. Since the graded algebra is generated by $x,y,z$, we have $X=D_+(x) \cup D_+(y) \cup D_+(z)$. Therefore, it suffices to prove that $f^{-1}(D_+(a)) \to D_+(a)$ is an isomorphism for $a \in \{x,y,z\}$. But this precisely means that $$(f^\#)_{(a)} : k[x,y,z]/(xz,yz,z^2)_{(a)} \to k[x_0,x_1]_{(f^\#(a))}$$
is an isomorphism of rings, where $(a)$ denotes homogeneous localization at the element $a$. In fact, we have an isomorphism on the whole localization  $(f^\#)_a : k[x,y,z]/(xz,yz,z^2)_{a} \to k[x_0,x_1]_{f^\#(a)}$: For $a=x$ we have $$k[x^{\pm 1},y,z]/(xz,yz,z^2)=k[x^{\pm 1},y,z]/(z,yz,z^2) = k[x^{\pm 1},y].$$
For $a=y$ we have
$$k[x,y^{\pm 1},z]/(xz,yz,z^2)=k[x,y^{\pm 1},z]/(xz,z,z^2) = k[x,y^{\pm 1}].$$
For $a=z$ we have
$$k[x,y,z^{\pm 1}]/(xz,yz,z^2)=0=k[x,y]_{f^\#(z)}.$$
Global solution. Projective schemes have a beautiful description via their functors of points. $\mathbb{P}^1$ represents the functor which takes a $k$-scheme $T$ to the set of (iso-classes of) tuples $(\mathcal{L},x,y)$, where $\mathcal{L}$ is an invertible sheaf on $T$ and $x,y$ are two global sections of $\mathcal{L}$ which generate $\mathcal{L}$. Also, $X$ represents the functor which takes a $k$-scheme $T$ to the set of tuples $(\mathcal{L},x,y,z)$, where $\mathcal{L}$ is an invertible sheaf on $T$ and $x,y,z$ are two global sections of $\mathcal{L}$ which generate $\mathcal{L}$ and which satisfy the relations $x \otimes z = 0$, $y \otimes z = 0$, $z \otimes z = 0$ (these are global sections of $\mathcal{L}^{\otimes 2}$). Now our task is simply to prove $z=0$! Since $\mathcal{L}$ is invertible, it suffices to prove that $\mathrm{id}_{\mathcal{L}} \otimes z : \mathcal{L} \to \mathcal{L} \otimes \mathcal{L}$ is zero. Since $(x,y,z) : \mathcal{O}_T^3 \to \mathcal{L}$ is an epimorphism, it suffices to prove that the composition $\mathcal{O}_T^3 \to \mathcal{L} \otimes \mathcal{L}$ is zero. But this is precisely what the relations $x \otimes z = 0$, $y \otimes z = 0$, $z \otimes z = 0$ tell us!
Comment: I think I figured out how to do this: we have to check that the topological part morphism and a sheaf morphism are isomorphisms, and to do that we have to use the principal open sets of the target. Then the problem is reduced to check the localized morphisms are isomorphisms at each homogeneous element, and this is doable (although still I don't know why those three elements are enough).
Comment: There is no need to go into the topological and the sheaf part. But your idea is correct. I have added some details.


Unable to install SSIS on SQL Server 2016 due to SQL Server 2012 Native client error

Question: I am trying to add SSIS to SQL Server 2016, but I keep getting the error message:
"An installation package for the product Microsoft SQL SERVER 2012 Native Client cannot be found. Try the installation again using a valid copy of the installation package 'slincli.msi'".
I downloaded slincli.msi file from Microsoft website and tried to install it but this time I got this error message:
"Installation of SQL Server 2012 Native Client failed because a higher version already exists on the machine. To proceed, uninstall the higher version and then run SQL Server 2012 Native Client Setup again."
I cannot uninstall Native Client because I don't want to make trouble with the SQL server 2016 database that already has been installed and is working.
I also tried to install SQL Server 2016 SP2 but it didn't install Native Client too.
I am so desperate now as I have spent more than a day to resolve this problem.
Does anyone have any idea how to fix it?
Thanks.
Answer: I finally uninstalled the Native client and installed SSIS. Fortunately, it didn't break anything and the database is up and running.


Is there a way to properly invert the y-axis in Python's 3DAxes plot_surface without it interfering with the x-axis?

Question: I'm using 3DAxes in Python to plot a surface plot. Im trying to manipulate the y-axis to go from [25 - 0] instead of going from [0-25] in the plot itself. So far I've tried to just use ax.invert_yaxis(), but my problem is that this changes the x-axis to have the same numerical values as the y-axis. My suspiscion is that this is because I use np.meshgrid earlier in the code.
Does anyone know how to invert just the y-axis?
I have this:

I want to change so the y-axis goes from 25 to 0, and naturally the surfaceplot will change as well then.
But when I use invert_yaxis I get this:

Which is wrong cause the x-axis is changed in numerically values as well...
CODE:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

Tcm_0 = 17.9 #K

def t(T):
    return T/Tcm_0
my_0 = 1.25663706212e-6
Hcm_0 = 29.7 / my_0 #A/m

def Hc2(T):
    return Hcm_0 * (1 - np.power(t(T),1.52))

def h(H, T):
    return H/Hc2(T)

C_1 = 350e3 #AT/mm^2

def Jc(H, T):
    return (C_1/(my_0*H))*(1 - np.power(t(T),1.52))*(1 - np.power(t(T),2))*np.power(h(H,T),0.5)*np.power(1-h(H,T),2)

fig = plt.figure()

ax = plt.axes(projection='3d')

T = np.linspace(0,17,100)

B = np.linspace(0.1,28,100)

H = B/my_0

T, H = np.meshgrid(T,H)

J = Jc(H,T)

B = H*my_0

surface = ax.plot_surface(T,B,J, cmap='winter', linewidth=0)

ax.set_xbound(0, Tcm_0)

ax.set_xlabel('Temperature [K]')

ax.set_ybound(0, Hcm_0*my_0)

ax.invert_yaxis() <- This us what I dont get to work.

plt.show()

Answer: You can do it by manually setting the limits for the axis, no need to invert anything.
ax.set_ylim(25, 0)


What is the best way to build a subclassed object of an abstract superclass with required and optional parameters in Java 9?

Question: There's various ways to build an object in Java. For my use case let's just assume that I have an abstract Person class with private attribute fields and a subclass called Tom.
1. Getters/Setters
A no-arg constructor, setters, and getters in the Person class. Can be simplified by using Project Lombok's @Data annotation.
Tom tom = new Tom(); // Subclass of Person
tom.setName("Tom");
tom.setAge(42);

I've read that unless working with a framework, this method should be avoided.
2. Parameterized Constructor
Builds the object using constructor parameters. Excessive constructor overloading for big objects with various optional and required attributes. Can also be simplified using Project Lombok's various constructor annotations.
Tom tom = new Tom("Tom", 42);

Then, Tom's constructor would make a call to super("Tom", 42). In Person, you could make use of constructor overloading if there are many optional parameters.
3. Builder Pattern
Because constructor overloading can get real messy real fast, Josh Bloch presented the Builder Pattern. Again, this can be simplified with Project Lombok's @Builder annotation. This is how it would look with a non-abstract Person class:
Person person = new Person.Builder().name("Tom").age(42).build();

Trying to use the builder pattern together with inheritance is difficult (but not impossible) as others have said before me.

I'm sure there are many more ways to build an object, but I only listed the ones I am familiar with.
My question is: Using Java 8 or even Java 9 functionality, what is the absolutely best way to build a an object that is a subclass of an abstract superclass with required and optional attributes?
A lot of tutorials and questions on SO are outdated, and probably do not enforce what is considered as best practice nowadays.
Answer: What is best practice is unfortunately very subjective in Java and OO, but I try to list some mostly objective criteria:

Whether the class is a subclass or not should not influence the API of that class at all, including how its constructor should look like.
An object should be ready for use after construction. That means all of its public methods should be working after the constructor. This disqualifies your option #1. (Unless forced by unfriendly frameworks).
Have one "main" constructor that does the work, and have all other constructors call this one. Unless you have a superclass that also has many constructors in which case things get more complicated, you most likely have to mirror what the superclass wants.
It should be easy and straight forward to use. This means, it is preferable to use constructors vs. builders unless using them becomes difficult. If there are many parameters (for me more than 3-4), or there are just too many combinations of them possible (again, for me more than 3-4), or there is a depth of construction (has to construct other objects first), then I would use a builder.
Don't under any circumstances use Optional as arguments.
Don't use Lombok. It may make your (the writer's) life easier, but will mess with all those who have to read the code. Remember, we read code much more often than write! (This may be a debatable point)
Inheritance is tricky and should be avoided if at all possible. Don't use it to share code, that is an anti-pattern. That is true for builders too. You can write a builder that can return different implementation classes, but it does not have to (should not) subclass other builders to do that.

I possibly forgot some rules, but other than these, there is no new groundbreaking syntax in Java 8 and 9 to simplify construction.


Redirect links to nodes of past events to the up-to-date version

Question: On a event-centered site we have a lot of recurring events, but there's no pattern like every first monday etc. So the editors just clone the event with node-clone and with pathauto we generate a date-token that is appended to the url.
After the date is gone, these events are deprecated and get unpublished (by Rules). But still people find links to these events via search engines and the like.
How can we automatically redirect links of past events to a up-to-date one?
Right now the url looks like this:
www.mydomain.com/events/eventname-300518 (which would be today the 30th of May)
I could add a "basic" event without the date token if that would help. So if a event gets unpublished a redirect to the basic node could take place.
Can you point me in the right direction?
Answer: Rules and Redirect
Since you're already using Rules to automatically Unpublish past events, you could try adding an Action that creates a Redirect from the unpublished node path to the latest one. You'll need a Redirect module that provides Redirect actions. I haven't tried this but I expect Redirect module to have that.
Match Redirect
Or you could use the standalone solution Match Redirect.
Server side Redirect
Redirects don't have to be handled within Drupal. You could create Rewrite rules in your server configuration too.
But this all might be the solution for the wrong problem.
Better structure within Drupal
If the original event information doesn't change, and you only change the times, maybe you should structure it with 2 different content types, Event and Event instance or something that makes more sense.
The Event would hold everything except the times, and the Instances would only hold times. Then use Entity references to connect Instances to their Events.
Use Views to display Instances information on Events (Block or Attachment), you can use Views to filter out only future dates to display on Event nodes. And when marketing your event only ever share link to the Event node, that will always be showing correct relevant dates through the power of Views.
You can set your robots.txt to not index Instance content nodes on search engines, and in general don't link to them or show them to the users, only use the Instance information on Event nodes.
Or if you have per-date relevant information for the event (comments or similar), store it on the Instance node, and then again with the power of Views you can list past event info on the Event node itself, if anyone wants to read, look at past image gallery or similar.
That way you'd have both the future and past info available to be displayed how you want them, and only one Event link for marketing that would probably even be beneficial for SEO ranking.
Comment: He could also add the dates field to the Event content type with an unlimited limit. He could hide the field and using Views and EVA he could add a view to the page that gets the NID (from url) and shows the event dates that are greater than today's (at 00:01 probably).
Comment: That's a great idea @rovr138! Why not add that as your answer?
Comment: I wanted to get something out. I can probably add that today and expand on it. I've used a similar approach on some sites.
Comment: Thx, great input, i just came back to this issue eventually...!
Comment: that is not lost that comes at last :)


Eigenvalues of a rank-one update of a matrix

Question: Let $\lambda_1,\dots,\lambda_n$ be the eigenvalues of the symmetric matrix $A \in {\Bbb R}^{n \times n}$. Consider a rank-one perturbation $$B=A+\rho\,uu^T$$ where $u \in {\Bbb R}^n$. Is there an analytical expression for the eigenvalues of $B$, exploiting the known eigenvalues of $A$?
I'm thinking something similar to the Sherman-Woodbury formula for the update of the inverse could work, but I have not succeeded. I found some related results:

Bunch–Nielsen–Sorensen formula

A stable and efficient algorithm for the rank-one modification of the symmetric eigenproblem (1994)

But both seem to require that $u$ is an eigenvector of $A$. Here, I am considering a more general statement, where $u$ need not be an eigenvector of $A$.
Comment: For posterity, the BNS formula does **not** assume that $u$ is an eigenvector of $A$.
Comment: This is not true. Suppose $A = \lambda_1 uu^T + \lambda_2 vv^T$ with $\lambda_1 > \lambda_2$. Then then $B = A + uu^T = (\lambda_1 + 1) uu^T + \lambda_2 vv^T$
Comment: Thanks. For posterity, BNS = Bunch–Nielsen–Sorensen (https://en.wikipedia.org/wiki/Bunch–Nielsen–Sorensen_formula) ... I had to look it up :)
Answer: I doubt there is an analytic expression for all but the smallest matrix dimensions. However, there is an inexpensive way to compute the eigenvalues of rank-one update.  The following comes from Demmel's Applied Numerical Linear Algebra subsection 5.3.3.
For any symmetric matrix $\mathbf{A}$, we can use the eigendecomposition $\mathbf{A} = \mathbf{V}^\top \text{diag}(\mathbf{d})\mathbf{V}$
to determine the eigenvalues of $\mathbf{B} = \mathbf{A} + \rho \mathbf{u}\mathbf{u}^\top$ as equivalently the eigenvalues of a diagonal plus rank-one matrix $\mathbf{V}\mathbf{B}\mathbf{V}^\top = \text{diag}(\mathbf{d}) + \rho (\mathbf{V}\mathbf{u})(\mathbf{V}\mathbf{u})^\top$.
We can then compute the eigenvalues through the roots of the determinant $\det(\mathbf{B}- \lambda \mathbf{I})$; in particular, if $\lambda$ is not an eigenvalue of $\mathbf{A}$ we have
$$ \det(\mathbf{B} - \lambda \mathbf{I}) = \det(\mathbf{A} + \rho \mathbf{u}\mathbf{u}^\top -\lambda \mathbf{I})
= \det(\mathbf{A} - \lambda \mathbf{I})\left[1+ \rho \sum_i \frac{(\mathbf{e}_i^\top \mathbf{V}\mathbf{u})^2 }{d_{i} -\lambda}
\right]
$$
where $d_{i}$ are the original eigenvalues of $\mathbf{A}$ and $\mathbf{e}_i$ is the $i$th column of the identity matrix (cf. eq. (5.14)). This bracketed term is called the secular equation and its roots are the eigenvalues of $\mathbf{B}$. Finding these roots can be challenging numerically, but a robust algorithm is implemented in LAPACK in xLAED4.
Answer: This isn't a complete answer, but maybe can be a starting point.
A symmetric matrix has eigen-decomposition $A = U\Lambda U^T = \sum_i \lambda_i u_iu_i^T$.
Essentially we can view this as the stretching of a sphere along the directions $u_i$. To compute $Ax$ we can compute the projection of $x$ is on each of the $u_i$, scale these projections by $\lambda_i$, and add them back together.
Now, when we compute $Bx = Ax + uu^Tx$ we additionally compute the projection of $x$ onto $u$ and add this in with the previous projections. If $u$ is in the direction of one of the $u_i$ that means that direction alone will be scaled by an additional amount. More precisely, if $u = c u_j$ for some $j$, then $uu^T = c^2 u_ju_j^T$ so
$$B = A+uu^T = (\lambda_j + c^2)u_ju_j^T + \sum_{i\neq j} \lambda_i u_i u_i^T$$
That is, the eigen value in the direction $u_i$ changes by $c^2$.
Now let's consider what happens if $u$ is in the span of $u_i$ and $u_j$. First, note that the action of $A$ on everything outside of this span is the same as that of $B$. So none of the eigenvalues in the directions other than $u_i$ or $u_j$ will change. More generally, only the eigenvectors who are not orthogonal to $u$ will change.
Consider $u = c_1u_1 + c_2u_2$. Then $uu^T = c_1^2 u_1u_1^T + c_2^2u_2u_2^T + c_1c_2 u_1u_2^T + c_1c_2u_2u_1^T$. So now we see that while the update does contribute to the directions $u_1$ and $u_2$, it also "skews" the original image.
If we viewed the image in this plane as an ellipse, we now get a new ellipse. I'm guessing there is a way to write down the new axes of this ellipse which is the 2d version of your question.
Unfortunately, I'm not exactly sure how to do this.


Difference between case class and case object?

Question: I am learning Scala and Akka and in my recent lookup for a solution, I found something like
 case class TotalTaxResult(taxAmount:Double)
 case object TaxCalculationTimeout

What is the difference between the two?
When should I use one over the other?
Answer: A case class can take arguments, so each instance of that case class can be different based on the values of it's arguments.  A case object on the other hand does not take args in the constructor, so there can only be one instance of it (a singleton, like a regular scala object is).
If your message to your actor does not need any value differentiation, use a case object.  For instance, if you had an actor that did some work, and you, from the outside, wanted to tell it to do work, then maybe you'd do something like this:
case object DoWork

...

def receive = {
  case DoWork =>
     //do some work here
}

But if you wanted some variation in how the work is done, you might need to redefine your message like so:
case class DoWorkAfter(waitTime:Long)

...

def receive = {
  case class DoWorkAfter(time) =>
    context.system.scheduler.scheduleOnce(time.milliseconds, self, DoWork)

  case DoWork =>
     //do some work here
}

Answer: A case object is a singleton case class. They are used kind of like enumeration values. It can be used in pattern matching just like any other value:
TaxCalculationTimeout match {
  case TaxCalculationTimeout => println("hello")
}

When you define a case class, you are creating a template for instances of that class. TotalTaxResult(1.0) and TotalTaxResult(2.0) are two different values of the same type. Whereas there is exactly one TaxCalculationTimeout value.
Answer: In simple words, Scala is a Object Oriented and Functional programming language. It have features of functional programming like pattern matching with pure object oriented methodology.
Some times, we need to create singleton object without any value like passing some signal for pattern matching. If scala have not concept of case object we just to need to use enum or equals some string value in matching. But this is not a readability in pure Object Oriented language.. In that scenario we are using Case Object
Case classes are used when we need to create multiple objects with different values.
Answer: You can think of these two to be just like a class and an object in general.
When you do a case class ClassName(params list) it creates a blueprint for making objects and case object defines a singleton object in the scope in which it is declared.
Starting with Scala 2.10, you should always use case objects instead of case classes with no arguments.
So when you want to do a pattern match on some values which need arguments you should go for a case class, but if your values don't take arguments then you should use a case object.


can't remove google chrome's default search engine

Question: when i was installed a driver i have installed a spam and thats changed my chrome settings then i have removed the spam app and searched my folders and cleaned the app but unfortunately i could not remove the default search engine
even after reset the chrome settings and re-installed. please help me how to remove that Default search engine
the thrible dot button is not working
Answer: This is happened because the chrome says when i try to change my default search engine  "This setting is enforced by your administrator" policy under a search engine in Google Chrome, then my computer is infected with a browser hijacker.
here is the solution:
Remove "This setting is enforced by your administrator" from Chrome


Qual a diferença de /bin/bash e /usr/bin/env bash?

Question: Não tenho muito conhecimento de script shell, sempre usei /bin/bash, todavia notei outras variações:

#!/usr/bin/env bash
#!/usr/bin/bash
#!/bin/bash

Qual a diferença entre elas?
Até aonde li isso é devido a portabilidade entre diferentes sistemas (ou kernels), gostaria de saber como chamar declarar o tipo do script de maneira que funcione em sistemas unix-like, como sistemas baseados em Linux, Mac OS X e sistemas baseados em BSD.
Answer: Antes de mais nada, o #! em um shell script é conhecido como shebang ou hashbang. Ele tem o formato de um comment (linhas iniciadas com # normalmente são ignoradas pelo shell), mas o ! logo em seguida serve para indicar qual é o executável que vai processar aquele script.
Quando você diz:
#!/usr/bin/bash

ou
#!/bin/bash

está chamando o executável bash para interpretar seu script. Poderia ser o python ou outro interpretador.
O problema é que de distro para distro, o lugar do bash (ou do python, por exemplo) pode ser diferente. Quando você faz assim:
#!/usr/bin/env bash

está executando o comando env com o parâmetro bash. O env serve para criar um ambiente novo, e o parâmetro a seguir é o comando que será executado pelo env neste ambiente.
Como o env usa o path do sistema, o bash será executado sem que você tenha que definir seu caminho exato.
Este artigo resume bem isto (en):

http://www.cyberciti.biz/tips/finding-bash-perl-python-portably-using-env.html

Agora, resta saber se é realmente verdade que o env vai estar sempre em /usr/bin :)


Confidence interval on chi-squared values

Question: I am doing a grid search for model fits to data. At each point of the grid (let's say a 2d parameter space) I have a value for the statistic
$\chi^{2} = \sum_{i}\frac{(O_{i}-E_{i})^{2}}{dO_{i}^{2}}$
where $O_i$ are observed data points, $E_i$ the model values and $dO_i$ the (generally different) errors on the observed values.
How do I find a confidence interval (let's say the 68% interval) around the minimum value that I find?
To my understanding, standard $\chi^{2}$ only works if the errors are approximately Poissonian.
Comment: I think that the assumption is that $O_i$ is Poisson and $\chi^2=\sum_i \frac{(O_i-E_i)^2}{E_i}$?
Comment: Right. But what if that condition is not met? I'm supposing one has to resort to sampling methods.
Comment: Your formula for $\chi^2$ is very different from the one in my comment, the denominator is very ''strange'', it should be $E_i$.  Usually, if the $E_i$ are all over 5 then the variable can be approximated well by $\chi^2$.
Comment: If the denominator is replaced by $\mathrm{Var}(O_i)$ it would be more general. My question is whose confidence interval you want to get?
Comment: Ultimately a confidence interval for the two estimated parameters. This should follow from a contour in the $\chi^{2}$-space as in the following paper, the only difference being that the errors in the paper are manifestly Poissonian and mine are not: http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1976ApJ...210..642A&data_type=PDF_HIGH&whole_paper=YES&type=PRINTER&filetype=.pdf
Comment: They don't have to be Poissonian, the point is that it is a sum of squares of standard normal variables.  In the case of a Poisson random variable $\frac{O_i-E_i}{\sqrt{E_i}}$ is  (asymptotically) standard normal. So if you subtract the mean and devide by the standard deviation and then sum these squares, then you have asymptically a $\chi^2$, also for non-Poisson (you have to find out the degrees of freedom).  @a_statistician made a simiar remark. So your confidence interval will look like an ellips in the two-dimensional case.
Answer: $\chi^2$ is a valid statistic for any data where you expect the errors to be normally distributed. It is commonly used for counting data, where you expect poisson errors of order $\sqrt{O_i}$ (which become gaussian in the large count limit), but as @a_statistician notes the more general formula is
$$\chi^2 = \sum_i\frac{(O_i-E_i)^2}{Var(O_i)}$$.
Restating your problem, it sounds like you have some model parameters, let's call them $\alpha$ and $\beta$, which are used to predict $E_i(\alpha,\beta)$, and some observed values $O_i$, along with some prediction about the size of errors, $Var(O_i)$. Therefore you can calculate $\chi^2(\alpha,\beta)$ as a function of $\alpha$ and $\beta$.
You have then (correctly) estimated $\alpha$ and $\beta$ by minimizing this function, and now want to obtain the confidence intervals for these estimates. As the paper you linked explains, one way to do this is to consider the parameters themselves to be free, and lookup to corresponding cumulative-probability function for a chi-squared distribution with that number of degrees of freedom (using one of the many handy tables available online).
For the example you gave, with two parameters, the 95% cumulative probability point is 5.991 (corresponding to (2,0.05) on the linked table). Therefore, one would call the 95% confidence region the set of all points $(\alpha, \beta)$ in parameter space such that
$$\chi^2(\alpha,\beta) - \chi^2_{min} < 5.991$$
For a good, well-constrained model, this should give you something fairly nice, like an ellipse. This ellipse corresponds to the covariance matrix for your parameters, as this article nicely explains, and therefore standard errors and other commonly used measures of uncertainty.


Gerando identificador único utilizando time()

Question: Criei um algoritmo para gerar um identificador, que consistem em um valor aleatório com 24 caráteres não sequencial. O objetivo basicamente é capturar a hora atual usando time() e concatenar com notas musicais(letras de 'a' a 'g'). haha
Algoritmo:
<?php
    $reduce = substr(date('YmdHis', time()), 2);
    $arr_date = str_split($reduce);
    $arr1 = str_split("cdefgab");
    $uid = "";
    for($i = 0; $i<12; $i++){
        $uid .= $arr1[rand(0, 6)];
        $uid .= $arr_date[$i];
    }
    echo $uid;

Veja funcionando aqui no ideone.
Resultado:
e1d6e1c2e1g1g0f8f5f4a2a0

Pretendo usar esse valor como ID único com chave privada em uma tabela de usuários no meu banco de dados MySQL. Basicamente é criar um ID único(não sequencial) no lugar de um ID único inteiro que auto incrementa (sequencial) numa tabela de usuários.
Gostaria de saber se usando este algoritmo haveria alguma problema futuro ou se existe algo que torne essa minha solução inviável?
Comment: Basicamente está desperdiçando entropia. 24 bytes podem armazenar até 192 bits de informação. Seu algoritmo gera aproximadamente 60 bits de informação, o que é pouco para o tamanho da string. Para fins de comparação, mesmo que precisasse de algo legivel por um humano, se usasse 16 bytes em base 64, para dar os 24 caracteres, já teria ao menos 128 bits, o que é absurdamente muito menos chance de colisão que seu método. Tudo bem que 60 bits ainda é um set bastante extenso de possibilidades, mas à medida que for tendo mais e mais registros, a chance de colisão aumenta.
Comment: Na verdade, é melhor ainda. Em 24 caracteres base 64 cabem 18 bytes, não só 16. O que dá 136 bits, e não 128 como eu mencionei anteriormente..
Comment: @Bacco (rs sumiu o chat) Na verdade, na verdade eu não entendi o que você disse que "...é melhor ainda". Você está sugerindo usar TO_BASE64 é isso?
Comment: Eu marquei como obsoleto, pra moderação limpar pq estava ficando muita informação já resolvida no post. Quis dizer que se você usar base 64, pode usar até 18 bytes completamente aleatórios, ou seja, uma variedade razoável de combinações. Se fizer uma sequência de 24 caracteres com rand(0, 63), sendo os 63 caracteres da base 64 (ou os que escolher no lugar destes), dá 136 bits de informação. (2,23 * 10^43 )
Answer: O que pode afirmar sobre o código apresentado é que a cada século as chances de colisão serão maiores pois está cortando os dois primeiros números referente ao ano.
A função date() formata a data e hora (2016-12-11 08:54:20), resultando nisso: 20161211085420
Na sequência remove os dois primeiros números, ficando assim: 161211085420
Aqui temos um pequeno problema pois quando chegar no ano 2116, daqui a 100 anos, terá mais chances de colisões mesmo embaralhando randomicamente com letras de A a G (ABCDEFG), que aliás, é pouco para garantir maiores combinações. Claro, é ridiculo se preocupar com isso, mas já que perguntou onde teria algum problema. Basicamente deve pensar em chances óbvias de colisão.
No seu exemplo, gerou isso: e1d6e1c2e1g1g0f8f5f4a2a0 e é muito fácil de entender a sequência apenas removendo as letras.
Você pode argumentar que 100 anos é muito tempo, ninguém aqui estará vivo e provavelmente o sistema que está criando nem será usado, além do mais será usado para cadastro de usuários e não para gerar grandes quantidades de IDs ao mesmo tempo. Mas mesmo sob essa justificativa ainda está criando algo que não mascara a sequência muito bem. Qualquer pessoa sem conhecimento em progamação consegue entender a sequência e que se trata de uma data.
Se formos apontar um "problema" e como a intenção parece ser mascarar a sequência, acredito ser relevante colocar isso em pauta.
Sob esse contexto, focarei na mascaração da sequência. Então a pergunta que faço é, por que não usar o próprio valor do timestamp?
E se ainda quiser "embaralhar" pode apenas converter em letras.
Normalmente utilizo isso:
$id = microtime();
$a = explode(' ', $id);
$a[0] = str_replace('.', '', $a[0]);
$a[0] = base_convert($a[0], 10, 36);
$a[1] = base_convert($a[1], 10, 36);
echo $id.' -> '.$a[0].$a[1];

Retorna algo assim: 0.70350700 1481537805 -> 15vuy4oi2hvx
Esse primeiro, 0.70350700 1481537805, é o valor retornado da função microtime().
Removo o caracter ponto (.), separo os dois números e converto cada um com base_convert().
070350700 -> 15vuy4
1481537805 -> oi2hvx

No final, o resultado convertido é concatenado, resultando nesse ID: 15vuy4oi2hvx
É metade do espaço que ocuparia com o que apresentou na pergunta:  e1d6e1c2e1g1g0f8f5f4a2a0 e ainda um pouco mais "eficiente" em relação a colisões por concatenar o microtime ao timestamp além do fato de não se preocupar com a data, a menos que o ambiente onde execute tenha uma data configurada errada para um valor no passado cujas datas já possuam códigos gerados. São possibilidades ridículas, mas é possível acontecer.
Comparando o tempo de execução,
Script da pergunta: 0.0000128746032714844
Script do exemplo acima: 0.0000109672546386719
Não é algo tão relevante, portanto a vantagem maior é a string final que ocuparia metade do espaço.
De uma forma geral, não há problema algum no que apresentou na pergunta, dadas as condições. Mas achei que seria proveitoso demonstrar uma outra lógica que acredito ser um pouco melhor por gerar uma string mais econômica.
Comment: Tinha ciência de que "...cada século as chances de colisão serão maiores...", e desta forma ia exatamente argumentar "...que 100 anos é muito tempo...". Na questão da sequência, não consigo enxergar nenhum problema pois esse ID não é algum tipo de código de acesso que seria quebrado de alguma forma, mas teu formato me interessou. Bom, deve ter perguntado como cheguei nesta pergunta?! Dando uma olhada no JSON que o [Trello disponibiliza](https://trello.com/b/XVOTxCht.json), percebi que eles usam como identificador uma sequencia de 192bits e fiquei curioso, daí então comecei a questionar isso.
Comment: Na sua sugestão de solução, SEMPRE retornará um valor de 96bits?
Comment: É esperado que sim pois timestamp é sempre 10 dígitos e microtime, 9. Desde que use base 36.
Comment: Vou fazer mais alguns testes, algumas pesquisas e valido sua resposta que por cima foi muito útil pra mim. Obrigado.
Comment: Daniel, fiz alguns teste para validar sua ideia. Cheguei numa situação, mas não sei se de fato me trará um problema. No seu algoritmo hora me retorna um valor com 96bits, hora me retorna com 88bits; Percebi que atingiu cerca de uns 65% para 11 caracteres, e o restante com 12 caracteres. Alguma coisa errada não está certa! eheh No meu banco, quero dar preferência que uma coluna tenha um tamanho fixo todo preenchido. Tipo VARCHAR(12) que sempre contenha exatamente 12 caracteres.
Comment: Normalmente eu não defino tamanho fixo. Defino como `CHAR(20)` mas se pretende tamanho fixo, não se pode confiar no método apresentado aqui. Terá que considerar algo como MD5, SHA, etc. Mas só o MD5 em si já ocupa um espaço "monstro" de 32 caracteres para essa finalidade. Mas afinal, porque se preocupa em ter um tamanho fixo? E poderia mostrar exemplos desses casos que encontrou tamanho diferente?
Comment: Verdade, talvez eu não tenha que preocupar com tamanho fixo. Mas acha que posso então usar um coluna do tipo TEXT?! Só mais essa pra fechar a questão.
Comment: Coluna TEXT é grande demais. Desperdício de espaço. Eu aplico char 20 para dar uma margem segura. Note que não uso VARCHAR que aloca mais espaço. Aplico o simples CHAR. (Falando do MySQL)
Comment: Meu caso seria MySQL utilizando sync com SQLite.


Can any score-writer do 'irrational' time signatures?

Question: I know I can write them as metrical modulations but I prefer to write them like this:

...which Sibelius can't do. I have to switch to a graphics program and it's time-consuming.
The main advantage of writing them this way is that tuplet-relationships are familiar: you don't have to stop and work them out. You just have to remember to stop tapping your foot! Using metric modulations makes the page untidy.
Any suggestions? There's something for Mac called NoteAbility that seems to know about these time signatures, but it doesn't look very sophisticated otherwise.
Comment: Musescore (musescore.org) can do it. Their time signature feature allows you to overlay the "actual" time signature with custom text. It's very easy to do. Just know, I couldn't discover how to create the incomplete tuplets at the ends of your 7/6 measures.
Comment: Also, in any case these are not "irrational" as that would mean they would involve numbers like Pi or Sqrt(2) or other non-rational numbers.  Don't do that :)
Comment: Ok a 6th note is actually a 4th note in a triplet, I get that now.
Comment: Does Sibelius allow fractional time signatures? Allowing I understand your intent (a dubious proposal), could you change 7 / 6 to (2-1/3) / 4
Comment: Btw do you just want it to look like this, or do you need the software to understand this semantically (like play it back correctly without hidden tempo workarounds etc.)?  If not then Dorico can do this.
Comment: @herman, your initial objection to 'irrational' got me thinking ... someone should really clarify that it's not 'irrational' in the mathematical sense; it's 'irrational' in the 'only a crazy person would ask someone to play this' sense.
Comment: My experience with NoteAbility is that it can do just as much as the others but trying to adapt to the workflow slowed me down too much. There's not much of a community to help you. The developer used to have a purely graphic mac only music typesetter called Notewriter which was incredible, but was discontinued with Os X. It's the inclusion of midi with NoteAbility (its successor) that hampers it.
Comment: I personally like pi/e as a time signature.  Flooring both numbers gets you 3/2, and it's awfully close to 1/1.
Comment: I know some composers have done that, but no: Sibelius doesn't allow it. A good idea though. Thanks.
Comment: Can anyone even read this?  I mean, 6th notes don't exist afaik.  There must be clearer ways to express your intent.  The notation inside the 7/6 bars doesn't even make sense: there is a triplet at the end which has only 1 8th eight note and 1 8th rest in it.  If it were a triplet of 8ths then it would need three 8th note values.
Comment: Given that you use the notation to convey to the performer what you want done it would seem logical to write in the way that is simplest to understand.  Your meaning - in terms of note duration - looks very unclear to me.  A change of time signature and an indication of how the beats in the two time signatures relate would be easier to understand and make your music more approachable.  The end result should be the same.  Why make it harder than it needs to be?
Comment: @herman I only called them that 'cos that's what they're called! And I put the word in scare quotes to show I don't like the term! Jeez! :-)
Comment: @herman Thanks. No - it doesn't need need to play it back. I can do that in Cubase. Dorico? Wow. Haven't looked at it for a few years.
Comment: @JimM Thanks. For musicians this way IS the easiest to understand. As I said, you don't have to stop and work them out. They SHOW you the relationship. Metric modulations make the page cluttered, and you DO have to work them out, and they can't be sight-read because they don't show the relationship. I AM trying to make it as easy as possible! Been doing it this way in hand-written stuff for years :-)
Comment: @OldBrixtonian I guess in tearms of readability you could also choose write the first 6 beats of the 7/6 as regular 4/4 and then add a bar of 1/6.  Since they're notated as triplets in 7/6 anyway it doesn't change the notation, and everyone's familiar already with 4th triplets in regular 4/4.  I guess that also depends a little on whether all instruments are playing the triplets.  If some are playing regular 4th notes I'd personally write it as 4/4 + 1/6,
Comment: @herman That would be possible certainly, but not in this *particular* case. There's a different chord on each tenuto note, so the phrasing is more like 1/6 + 3/3 isn't it? And I could make it that. That's how it would be conducted. BUT 1/6 + 3/3 is a more confusing time signature than 7/6. (No-one IS playing in regular 4/4 btw.) I *could* change the bar *before* into 4/4 + 1/6, but I don't think that's any clearer. I really appreciate your thoughts.
Comment: @Aaron yeah but we're talking about mathematical ratios here, so using that term with a non-mathematical meaning is very confusing.  Just call them "crazy time signatures " then :)
Comment: I see you've already accepted an answer about using Dorico, but I'll add that I have definitely done this in Finale, and I suspect similar methods would work for Sibelius, although I don't use that program. The Maestro font includes time signature-style version of every number, so you just build the signature as an expression attached to the beginning of the measure. Then, you go into the measure attributes and add an appropriate amount of extra space at the beginning of the measure. Again, I don't know Sibelius specifics, but I'd be surprised if it doesn't have similar flexibility.
Comment: Pat, I really appreciate your help. Haven't got time to try it till later, but I'll get back to you. I 'm sure I can find whatever font Sib uses for time signatures and, hopefully, build one as you suggest. There's no 'bar/measure attributes' exactly, but I can create a bar, hide its rest, drag the time sig into it and hide the end barline. I think so anyway. It sounds feasible. Thank you. Speak later.
Comment: @Pat Muchmore I've cracked it. You were right. Sibelius CAN do it, AND play it back correctly. Enter the notes as normal triplets into a 4/4 bar followed by a quaver into a 1/4 one, then hide the barline and delete the time sigs, so that it looks like a single bar. Add space at the start of the 4/4 bar using a hidden grace note. Make 7/6 time sig with 'special text tuplets' font. Use an extendable triplet bracket with a hook at only its left end, and drop a '3' on it with 'magnetic layout' switched off. Use metric modulation changes to make the invisible 1/4 bar last only 1/6, and hide them.
Comment: @Pat Muchmore I know you're not a Sibelius user but I thought I should answer my own question somewhere here in case anyone ever needs to do it. (Yes, *very* unlikely!) Thanks again for making me try harder!
Comment: @OldBrixtonian Sure, no problem. Actually, you *can* provide a full on answer to your own question, and I think this might be a time where it's appropriate. You don't need to supplant the accepted answer, but future people searching might find it helpful, but are less likely to look deeply into the comments.
Comment: It's very confusing for a musician, so he or she would
spend a lot of time trying to figure out the meaning. There are 7 quarter note triplets in the bar which could relate to the number 7 in the time sig 7/6. But there is nothing that relates to the number 6. How can 7 quarter note triplets be the same thing as 7 sixth notes? Doesn't make sense. Let alone what is a sixth note? There is no indication of something that could be labelled as sixth notes, well maybe the eight notes as a subdivision of the quarter note triplets but that wouk give 14 eight notes. Big mystery.
Comment: @Lars The number at the top - as it always does -  tells you *how many*. The number at the bottom - as it always does - tells you *of what kind*. So, in the example, there are seven sixth notes in a bar. *Seven* is how many. *Sixth note* is what kind. You have always called them quarter-note triplets, but if you think about it you'll realize they could also be called sixth notes. In other words, it follows the existing rules of music. Eighth-note triplets could also be called 'twelfth notes'. Just ask yourself 'how many of these are there in one whole note?' and I think you'll understand it.
Comment: @Brixtonian Ok, I see what you mean. I strongly suggest that you include an explanation in the start of the score what you mean by a sixth note.
Comment: My question was only to do with finding music notation software that would handle them correctly. I didn't think I would end up explaining them and defending their existence. I learned about them nearly half a century ago but thet seem to be better known in Britain than elsewhere. The composers Brian Ferneyhough and Thomas Adès both use them, and their music has been played in the US, so there are musicians there who may well have come across the things. But If I am ever concerned that musicians might not know what they are, I will indeed explain what sixth notes, twelfth notes etc. are.
Comment: when you write "score writer" do you mean "notation software?"
Comment: @Michael Curtis: Yes I do. I see I started calling it "notation software" three comments up from here. I believe I use both terms interchangeably, even dipping a toe - on special occasions - into "music-engraving software". Are you suggesting I change the question? I've no objection if so.
Answer: I discover it CAN be done in Sibelius. AND it will play back correctly with a couple of hidden metric modulations.
First input the notes as normal crotchet-triplets into a 4/4 bar followed by a normal quaver into a 1/4 bar, then hide the barline and delete the time sigs, so that it looks like a single bar.
[Turn on 'View hidden objects' if you like.]
Add some space at the start of the bar using a hidden grace note. Switch its playback off.
Click the R. button in space above the staff, and from the menu that appears select text|special text|time signatures. Then click the L. button where you want the time signature and enter '7' then '6'.
Now to make the final incomplete-triplet's bracket.
Select the final quaver in the bar and press 'L' to open the Lines menu. Scroll through it and select the bracket without a final hook. It's named 'bracket above (start)'.
Position it where you want it, and lengthen or shorten it by dragging the end of its line with the mouse. Now right click above the bracket and navigate to text|special text and click on 'tuplets'. Then left click and type "3". The 3 appears and you can drag it into position on the bracket line.
[Depending on your set up it's possible you may need to switch magnetic layout on or off.]
Finally use a new tempo for what was the 1/4 bar to make it last only 1/6, and another one to set it back to the preceding tempo. Hide these tempo changes. Sibelius will now play it correctly.
As Sibelius still sees the 1/4 bar as separate, the bar-numbering will need to be corrected.
[Turn off 'View hidden objects' if you like.]
Answer: Lilypond handles this without fuss if you can do without a GUI: you just write \time 7/6 and enclose the notes in \tuplet 3/2 { ... }
<code>\version "2.20.0"
\relative c'' {
  \numericTimeSignature
  \time 4/4
  e4 b8. c16 cis8 cis gis4 |
  \time 7/6
  \tuplet 3/2 2 {
    bes4 bes f8 r
    g!4 d8 r e4
    b!8 r
  } |
  \time 4/4
  cis4 fis8. f16 e8 e a4 |
  \time 7/6
  \tuplet 3/2 2 {
    g4 g c!8 r
    bes4 ees8 r des4
    ges8 r
  } |
}
</code>
Comment: yes, to get the tuplet brackets and spacing as desired  you have to add the usual types of formatting instructions - my general point to the OP being that the use of a time signature like 7/6 doesn't add any significant difficulty when typesetting with Lilypond.
Comment: So \tuplet 3/2 {\time 7/6}?
Comment: No, eg the OP's second bar would be \time 7/6 \tuplet 3/2 {bes'4 bes' f'8 r8 g'4 d'8 r8 e'4 b8 r8}
Comment: Added minimum working example. And it works, tuplet brackets should be adjusted (span too small) but otherwise effective.
Comment: Thank you, Damian. Lilypond looks really good. I don't know if you saw my own answer, but I did eventually work out how to do it in Sibelius, and although the solution was complicated to describe, actually using it doesn't take long at all. So I'll stick with the devil I know.
Answer: With some workarounds, Dorico can do this.
The workarounds are necessary for the incomplete triplet at the end of the measure.  There is a custom line tool with which you can create this by hand.  It won't play correctly though, unless you add hidden tempo changes.
See this forum post.
Comment: That's really useful. Thanks. Yeah - hidden tempo changes. No problem. As I said I don't *need* it to play back, but if it did that'd be a bonus. I'd better spend a few hours in Sibelius/Dorico hell (as I do every few years) and see if Dorico has caught up with Sib enough to be useable, or if there are any plans for Sib to incorporate these time signatures. (Very unlikely I think.)
Comment: Well - in the end I found Sibelius CAN do it. AND it plays back correctly. It's a complicated workaround but at least it can be done. Thanks again for your input.
Answer: Since you've given no instruction as to the relationship between a quarter note in the first measure, and a (no-such-thing) "sixth note" in the second, this notation is useless to a performer in the first place.  You have nothing to indicate how to map the standard icon for a quarter-note and eighth-note into "sixth-note" timing.
I can honestly say I do not know any musician who would want to try to read that and figure out the metric.  Figure out how long your "7/6" measure will last in terms of the 4/4 measure, and notate  triplets or sixths or 3-beat quads as necessary.
Comment: @OldBrixtonian  Yes, I have,  however they are purely composer-wanking and from a performer's point of view,  highly obfuscatory.   Kill them. Kill them dead and burn their bodies (the time signatures, not the composers)
Comment: It's quite clear to me, 4/4 lasts 4 quarter notes and 7/6 lasts 7 lengths of quarter triplet note (this is what division of a full note into six parts is).
Comment: Don't know if this is helpful or not but: imagine the melody written out above, with no bar lines, and no time signatures. It's perfectly unambiguous how long each of the notes are in relation to each other. Adding barlines doesn't change that, and saying it means there's "a competely undefined meter relative to the previous measure" is simply untrue. That is to say, there is no such thing as "triplets in 4/4 time" as distinct to "triplets in any other time signature". That's like saying a dotted crotchet in 11/8 is different to a dotted crotchet in 4/4. It isn't. It's 3 quavers long.
Comment: And absent of any specification to the contrary, i.e. absent any specification that relative lengths of notes in the new bar have *changed* in relation to lengths of notes in the preceding bar, everything just happily continues at the same pace, regardless of what time signatures we may have passed; the time signatures express the size of the bars and indicate the principal subdivision, but they have NO EFFECT on relative durations of notes unless this is separately specified
Comment: Mmm...I've been playing, directing and conducting time sigs with 6, 12, 5 etc on the bottom since the 80s and honestly have never come across a musician who needed more than a few seconds to get their head around the notation; "what's 5/12?" "Five triplet eighths" "err...so like three triplets plus another two at the same speed" "yup" "ok I get it"
Comment: @Carl Witthoft Evidently you haven't come across them before :-) Check out the link in Hermann's answer above. Or this one: http://www.paulsteenhuisen.org/non-dyadicirrational-time-signatures.html
Comment: @Carl Witthoft It's so hard to tell what you *really* think :-) The excellent thing about the (ill-named, as I have admitted) irrational time signatures is this. You play that first bar, then you come to some crotchet triplets. You *know* how to play crotchet triplets because even composers you *like* used them. So you play six of them, then notice there's an *extra* one: a seventh one. You remember passing a funny time signature with a 7 at the top. "This must be the seventh one", you say. And you play it. Easy, for any musician worth his salt. In the taxi home, you work out what the 6 means.
Comment: @OldBrixtonian  But I  know how to play triplets when I see eighth-notes marked as triplets **in 4/4 time** .  When someone says "the beat is a sixth-note" that means I have a completely undefined meter relative to the previous measure.  If you want 7/8 time then  do that and put in a text marking indicating that the eighth-note is half the time period of the previous measure's quarter note.  "What the 6 means" is already strictly defined:   X/Y time means X instances of  Y-length notes.
Comment: @Carl Witthoft (Why did you switch to eighth-notes rather than quarter notes? any significance?)
Comment: @Judy Thank you. That was a good clear explanation! Sorry for the delay in replying. I've solved it now and it CAN be done in Sibelius with a bit of jiggery-pokery. AND it even plays back correctly. I've described the solution above btw.
Comment: Exactly. Musicians are generally amused/interested to encounter an easy time signature they've never imagined. [I'm enjoying that Icebreaker track that was mentioned the other day. It's right up one of my streets! Looking forward to exploring you further when time allows!]


EditMode and EditButton unexpected behavior when embedded in NavigationView

Question: I was working on a more complicated screen with a lots of data and I noticed weird behavior when edit mode is embedded in navigation view.
Following example work as intended - which means text changes between editing and not editing. However when embedded in navigation view, the behavior changes (text remains the same) both in previews and on simulator. Whether the if-else is hooked to editMode itself or to .isEditing does not matter.
Can anyone refer me to resources that would explain why? What am I missing
import SwiftUI

struct ContentView: View {

    @Environment(\.editMode) var editMode

    var body: some View {
        VStack {
            HStack {
                Spacer()
                EditButton()
            }
            Spacer()
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            if editMode?.wrappedValue == .inactive {
                Text("Not editing")
            } else {
                Text("Editing")
            }

            Spacer()
        }
        .padding()
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView { // if removed, the text will change
            ContentView()
        }
    } // NavigationView end
}

Answer: Here is a workaround for my similar case.
struct RootView: View {
    @State private var editMode = EditMode.inactive
    var body: some View {
        NavigationView {
            ContentView()
                .environment(\.editMode, $editMode)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        RootView()
    }
}

The point is .environment() should be applied to the view inside NavigationView.
I suppose the reason for the unexpected behavior is multiple Binding<EditMode> instances for environment's editMode are used among views and the code above may avoid redefining another instance.


Audit Table - Can we store the new value on audit table?

Question: I have created the audit table similar to the below code which logs the changes made on the source table. My question is can a audit table contain newly inserted record or it should contain only the updated records/history since the new record is there in source table ?
I am Looking for pros/cons on each approach and best practice.
<code>create table tblOrders
(
  OrderID integer Identity(1,1) primary key,
  OrderApprovalDateTime datetime,
  OrderStatus varchar(20)
)

create table tblOrdersAudit
(
  OrderAuditID integer Identity(1,1) primary key,
  OrderID integer,
  OrderApprovalDateTime datetime,
  OrderStatus varchar(20),
  UpdatedBy nvarchar(128),
  UpdatedOn datetime
)
go

create trigger tblTriggerAuditRecord on tblOrders
after update, insert
as
begin
  insert into tblOrdersAudit
  (OrderID, OrderApprovalDateTime, OrderStatus, UpdatedBy, UpdatedOn )
  select i.OrderID, i.OrderApprovalDateTime, i.OrderStatus, SUSER_SNAME(), getdate()
  from  tblOrders t
  inner join inserted i on t.OrderID=i.OrderID
end
go
</code>
Comment: Don't post images of code. Post code as text.
Comment: It depends on what you want to. There can't be 1 answer to this question. If you want to store them all, then store, if you not, then don't store.
Comment: @ibrahimozgon : I am looking for best practice on what audit table suppose to be. Thanks for your answer
Comment: just so you're aware - if you're on a recent version of SQL (2017 or later) then this stuff is built into the database.
Answer: It is totally based on your case,
But I would like to have the Audit table to have all records, the new inserted and the updated, so that I can view, check history, do time line calculations,... using just the Audit table as a separate entity without going back to the original table.
Also It might be helpful if I want to roll back to a certain record (it could be the first inserted one)


How can I get Slick Slider to display the images?

Question: I have a "test" content type with a title, body, and a media entity field that allows for multiple images. I installed Slick Slider 2.2. I mostly followed the steps outlined here: https://www.ostraining.com/blog/drupal/how-to-use-the-slick-module-in-drupal-8/.
I configured the field to use the Slick Media formatter.

When I add a node with the "test" content type and add two images in the image field, the next/prev buttons appear but I can't see the images. See video of slider animation.
I tried this on two different content types and I also tried using layout builder and got the same result.
I don't see any console errors.
I am running:

Drupal: 8.9.3
Slick: 2.2
Answer: I accomplished what you're trying to do using Slick Carousel together with Slick Views.
You can create a content-type that you intend to be aggregated into the slideshow.  In my case a testimonial type consisting of a background image and overlying text.
You can create a views block and set its format to Slick Carousel.  You will be provided with setting options to configure the slideshow as you wish.
Filter your view by the content-type you want to comprise your slideshow, in my case testimonial.
lastly, pull your views block slideshow into another piece of content via entity reference.
Comment: That seems like overkill for accomplishing what I need. I basically want to allow users to upload more than one Hero image on the content type and then show those images at the top of the page in carousel format. Slick provides this functionality, but for some reason, it's not working for me.
Answer: For anyone that has a similar issue although it's unlikely, the problem was the SCSS below:
.sr-only {
  position: absolute !important; /* Outside the DOM flow */
  height: 1px; width: 1px; /* Nearly collapsed */
  overflow: hidden;
  clip: rect(1px 1px 1px 1px); /* IE 7+ only support clip without commas */
  clip: rect(1px, 1px, 1px, 1px); /* All other browsers */
}

[aria-hidden="true"] {
  @extend .sr-only;
}

More specifically, the position: absolute line.


Double stops in ABRSM Grade 7 violin

Question: I am going to do ABRSM Grade 7 violin. Under scales and arpeggios I have to play double-stop scales in sixths, in G and Bb majors.

In a book I found out that when I am asked to play double stops in sixths in G I have to start with G & Eb. I am confused with the Eb as there's no Eb in G major scale.

Is this Eb a mistake?

If not why it is not Eb instead of E?

How to find out notes for other double stops?
Answer: These double-stop sixths will have the tonic of the scale up top, with the third of the scale on the bottom.
In the book you found, those double-stop sixths are actually in the key of E♭ major; E♭ (scale-degree 1) is on top and G (scale-degree 3) is on the bottom.
If you want sixths in the key of G major, you'll have G on top and B on the bottom. The scale will be:

    G  A  B  C  D  E  F♯ G
    B  C  D  E  F♯ G  A  B

In the key of B♭ you will have:

    B♭ C  D  E♭ F  G  A  B♭
    D  E♭ F  G  A  B♭ C  D
Comment: So when I am playing in G, I have to start with G on 3rd string and B on 4th string?
Comment: Just been on ABRSM website, and yes, it's G also Bb (maj) in 6ths. So I don't know why Eb should be there, except in the Bb scale. There is a pdf available, but it won't download for me.
Comment: @LasithaYapa I actually don't play violin, so I unfortunately can't help you. Hopefully someone else can!
Comment: @LasithaYapa - I hope you got this resolved last spring.  Just in case: "So when I am playing in G, I have to start with G on 3rd string and B on 4th string?"  Yes. // Do you have a teacher who can guide you with these things?

Double stops in ABRSM Grade 7 violin


ftp_connect returns NULL in PHP

Question: I'm trying to use ftp_connect('ftp.is.co.za') [for example] in PHP 5 or higher (multiple different versions on different machines). I can use the ftp command from the shell in all cases successfully, so it's no a firewall or connectivity issue. I always get NULL as a result, and no errors, if the domain name is valid and serving FTP. I do get errors when there is a problem, i.e. I'm getting NULL as a success message. All versions of PHP involved are compiled with --enable-ftp.
Thanks
As requested, an example:
$ ftp ftp.is.co.za
Connected to ftp.is.co.za (22.214.171.124).
220 ProFTPD 1.3.1 Server (Welcome to Internet Solutions FTP service.) [188.8.131.52]
Name (ftp.is.co.za:myusername):
Login failed.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> 221 Goodbye.
$ php -a
Interactive shell

php > var_export(ftp_connect("ftp.is.co.za"));
NULL
php >
$

Comment: Can you paste the code & output that shows the function returns `null`?
Answer: ftp_connect() returns a resource type when successful, and the docs for var_export() show that:

Note: Variables of type resource couldn't be exported by this function.

This is probably why var_export() is printing a NULL.

ftp_connect returns NULL in PHP


What does the tests of "scale" check?

Question: I have found this test: http://stat.ethz.ch/R-manual/R-patched/library/stats/html/mood.test.html
unfortunately I didn't find any information on wikipedia, but what "scale" means? What do those tests check?
Thanks
Answer: They test equality of distributions, and are sensitive to departures where the distribution in one group is a scaled version of the distribution in the other. There's more here, including the caveat that there are better tests than Mood's.
Comment: excuse me, what tests are better then mood ?
Comment: there are [some mentioned here](http://projecteuclid.org/DPubS?service=UI&version=1.0&verb=Display&handle=euclid.aoms/1177704370)

What does the tests of "scale" check?


.htaccess redirect

Question: I am working on a project in PHP and using Apache server.
Say, my project's url is myurl.com.
When i visit
http://myurl.com
it works well.
But when I visit
http://www.myurl.com OR www.myurl.com
it redirects me to http://myurl.com, dropping the www subdirectory.
I want it to stay same, like if we visit http://www.myurl.com it should keep the "www" in url.
I believe this is a .htaccess setting.
I couldn't get the settings right.
Please guide
Thanks
Answer: You should open the htaccess file and search for something like
<code>Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.myurl\.com$ [NC]
RewriteRule ^(.*)$ http://www.myurl.com/$1 [R=301,L]
</code>
This code is redirecting.
Look further here:  http://www.askapache.com/htaccess/mod_rewrite-tips-and-tricks.html#m0-askapache2
Comment: thanks for the response, but i couldn't get it right. i added above lines to my .htaccess which already has some code for wordpress settings (mine is a wordpress site), but the site threw "page not redirecting properly" error
Comment: If your original settings are redirecting `http://www.wesite.com/` to `http://wesite.com/` and your new setting are redirecting `http://wesite.com/` to `http://www.wesite.com/` if you have BOTH in your htaccess that would would cause a redirect loop
Comment: yes, I meant to remove this part of code. this is responsible for the redirecting and you said you don't want to redirect from "www".

.htaccess redirect


sum of the digits of the number $(5^{2015})(2^{2018})$

Question: What is the sum of the digits of the number $(5^{2015})(2^{2018})$
So I am guessing, I have to find out the product of $(5^{2015})(2^{2018})$ and add each digit of the product.
The question is how do I find the product of $(5^{2015})(2^{2018})$. Both numbers don't share the same base or exponents, so none of the laws of exponents (that I know of) will help me. Unless this problem is meant to be clever and have another way.
Any leads?
Comment: Note that $5^{2015} \times 2^{2018}$ = $(2\times 5)^{2015} \times 2^3 $.
Comment: Notice that $5^x\cdot2^x=10^x$. Does this help?
Comment: @dmtri: This is what I meant with "avoid gaming the system". If you feel the need to edit old questions, find the ones that *really* need to be edited. Not just capitalisations of "i" or adding `$` around `p`. The older the thread, the more substantial the edit should be.
Comment: @Asaf Karagila,  thanks for making the point.  I will follow.
Answer: $$(5^{2015})(2^{2018}) = (5^{2015})(2^{2015})(2^3) = (5\cdot 2)^{2015}2^3$$
$$= 10^{2015}2^3 = 8\cdot 10^{2015}$$
Notice that this is just the digit $8$ followed by $2015$ zeroes, so the sum is just $8$
Answer: Hint: $(5)^{2015}(2)^{2015} = (10)^{2015}$.
$(2)^{2018} = 2^{2015} \cdot 2^3$


Get delta value of Multifield

Question: How do I get the delta value of a multifield in a View template? I need to get the delta value in the Row output View template.
Answer: <code><?php foreach ($row->field_my_field as $data): ?>

  <?php if ($data['raw']['value'] == 'o'): ?>
    // Output nothing, or placeholder, whatever
  <?php else: ?>
    <?php print $data['rendered']['#markup']; ?>
  <?php endif; ?>

<?php endforeach; ?>
</code>

Get delta value of Multifield


Ao mudar select chamar executar pesquisa

Question: Estou tentando alterar um script que tenho para previsão do tempo, mas sem sucesso, hoje o usuário seleciona uma opção no select e clica no botão para executar a busca, o que estou tentando fazer é usar o OnChange para encurtar a operação.
O que tentei sem sucesso foi isso:
onchange="document.getElementById('frmBusca')

O script está assim hoje:
<form id="frmBusca" class="sky-form clearfix" action="" method="post">

            <select name="Cidade" class="form-control" id="Cidade" tabindex="1" >
                <option value="0">Cidade</option>
                <?php foreach ($ResCidade as $Cidade) { ?>
                <option value="<?php echo $Cidade->IdCidade; ?>"><?php echo $Cidade->Descricao; ?></option>
                <?php } ?>
            </select>

        <button class="btn btn-primary  pull-right btn-block">PESQUISAR</button>

O está que está sendo invocado:

Comment: Valeu @Bruno Heringer, sua ajuda colaborou demais.
Answer: Quando houver o evento change no select, pegue o valor e envia via ajax:


Efeito de escala de cinza em slide carousel

Question: Pessoal estou com uma dúvida alguém conhece algum plugin que faça com esse efeito do meu layout? preciso que as fotos fiquem em escala de cinza e somente quando ela estiver no meio seja a cor normal não sei se da para fazer isso com o owl-carouselou se existe algum plugin pronto que faça isso:
se houver algum plugin ou material de estudo podem me passar por favor.
Segue link do site
Comment: Jovem posta o seu CSS e o HTML inteiro ai inclusive com a ``
Comment: @hugocsl Adicionei o link do servidor de testes com o site na pergunta acessa lá
Comment: Sem o Carrocel dos clientes na página não da pra te ajudar...
Comment: @hugocsl então eu ainda nao fiz porque to pesquisando aqui se da apra fazer com owl carousel isso ou se já tem algum outro plugin que faça entende?
Comment: existe uma maneira, com css vc deixa todas as imagens em escala cinza, quando chegar na imagem central, em destaque, com o owl carousel vc insere uma classe que deixa ele na cor normal.
Answer: você aplica o filter: grayscale(1) em todos os items do carousel, no item que é aplicado as classes ".center" e ".active" automaticamente pelo plugin, você aproveita para aplicar novamente o filter mas com valor none.
link da solução: https://codepen.io/leandroruel/pen/WMbMPZ
html:

CSS:
.owl-item {
  filter: grayscale(1);
}

.owl-item.active.center {
  filter: none;
}

js:
$('.owl-carousel').owlCarousel({
  autoplay: true,
  center: true,
  loop: true,
  nav: true,
});