How to isolate $n$ when a factorial operator is present

Question: This equation was drawn to my attention with the instruction "solve for $n$."

$6n-\frac{n}{6}+n^6=n!-6^n$

Most of this is easy. Take the umpth root, multiply by the denominator, stuff like that. My only issue is finding a method to remove the factorial operator whilst keeping the other side of the equal sign satisfied.
Is there a quick method of doing this? Is there something easier than trying every possible combination and adjusting the solution to fit?
Any help would be appreciated.
-Thanks
Answer: As soon as $n!$ exceeds $6^n$, which is $n=12,$ the rest of the terms won't matter because they are too small.  Actually the $6^n$ is big enough to matter up to $n=14$.  That isn't many to try.  Then $\frac n6$ is non-integer unless $n=0,6,12$ so you can only try those three.  Only $0$ works.  Done.
Comment: Well, you want $n!$ to be not just bigger than $6^n$, but substantially bigger.
Comment: Technically it doesn't have to be integer, I've heard something about the factorial being expanded to non-integer values
Comment: @AlexLi:  there is the gamma function which is a real function of a real argument (or a complex function of a complex argument) but when it is written as factorial it is fair to assume it is natural numbers.  Then all the terms in the equation are natural with the possible exception of $\frac n6$
Comment: @Ross Millikan fair enough. I was just thinking that the problem wanted an actual solution ("solve for n" implies, to me, that there is a solution). Also, I just noticed, -1 could potentially give an integer if the 6^n was being added. Negative whole factorials should be okay.
Comment: Actually negative whole factorials (based on the gamma function) are infinite because of $(n-1)!=\frac {n!}n$ going through $n=0$ so they do not apply.  I just noticed that $n=0$ is a solution, so there is one,  and updated.
Answer: Hint : $n! >> 6^n > n^6 > n$ for large enough $n$


adding facebook login to spree 1.0.x

Question: I am using spree 1.0.3 and rails 3.1.4. I remember a year ago searching for this and it seemed to be fairly easy with devise and omniauth. However, I can't seem to find any of the concrete tutorials i found before on how to do this. Also, there have been major revisions (spree 1.0, omniauth 1.0) so I'm not sure how valid any of the older tutorials would be (there don't seem to be any new ones).  I see the spree_social plugin in github, but that seems to be in early beta still.
I see that the rails dog demo site has facebook login, but I don't know what they used to create that.
Is deviseable omniauth still viable for spree 1.0? If so, are there any demos or source code out there? If not, are there any options out there that provide as smooth an integration to social media logins as devise/omniauth did with spree?
Answer: Zyren,
I believe that https://github.com/spree/spree_social is being used for the demo. It should do most of what you need to do.

adding facebook login to spree 1.0.x


How to select a region of an image during drawing in LWGJL?

Question: I am trying to select a specific region of a texture in LWJGL during the drawing process, but my efforts have been fruitless. How (if possible) can I select only a region of a whole texture during drawing.
Please note that I am nowhere new to Java, I am an experienced programmer, but not when it comes to LWGJL, as I'm still getting the full grasps with it.
Below is my code.
Sprite.java
public class Sprite
{
private Icon icon;
private int width;
private int height;
private int offcutX; // all below and this for selecting the region of the image.
private int offcutY;
private int imageX;
private int imageY;

public Sprite(TextureRegistry registry, String ref)
{
    this(registry, ref, 0, 0, 0, 0);
}
public Sprite (TextureRegistry registry, String ref, int offcutX, int offcutY, int imageX, int imageY)
{
    try
    {
        icon = registry.getIcon("net/blockbuster/resources/" + ref); // loads the icon and converts it to opengl-readable format.
        width = icon.getIconWidth();
        height = icon.getIconHeight();
        this.offcutX = offcutX;
        this.offcutY = offcutY;
        this.imageX = imageX;
        this.imageY = imageY;
    }
    catch (IOException e)
    {
        e.printStackTrace();
        System.exit(-1);
    }
}
public int getWidth()
{
    return icon.getIconWidth();
}
public int getHeight()
{
    return icon.getIconHeight();
}
public void draw(int x, int y) // drawing method, called on every loop.
{
    glPushMatrix();
    icon.bind();
    glTranslatef(x, y, 0);
    glBegin(GL_QUADS);
    { // I would like to be able to do this within this block.
        glTexCoord2f(0, 0);
        glVertex2f(0, 0);
        glTexCoord2f(0, 1);
        glVertex2f(0, height);
        glTexCoord2f(1, 1);
        glVertex2f(width, height);
        glTexCoord2f(1, 0);
        glVertex2f(width, 0);
    }
    glEnd();
    glPopMatrix();
}
}

TextureRegistry.java
public class TextureRegistry
{
private HashMap<String, Icon> table = new HashMap<String, Icon>(); // map to hold all loaded textures

public Icon getIcon(String resourceName) throws IOException
{
    Icon tex = table.get(resourceName);
    if (tex != null)
    {
        return tex;
    }
    tex = getIcon(resourceName, GL_TEXTURE_2D, GL_RGBA8, GL_LINEAR, GL_LINEAR);
    table.put(resourceName, tex);
    return tex;
}
public Icon getIcon(String resourceName, int target, int dstPixelFormat, int minFilter, int magFilter) throws IOException
{
    BufferedImage image = loadImage(resourceName);
    int textureID = loadTexture(image);
    Icon icon = new Icon(target, textureID);
    icon.setWidth(image.getWidth());
    icon.setHeight(image.getHeight());
    return icon;
}
public static int loadTexture(BufferedImage image)
{
    int[] pixels = new int[image.getWidth() * image.getHeight()];
    image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
    ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4);
    for (int y = 0; y < image.getHeight(); y++)
    {
        for (int x = 0; x < image.getWidth(); x++)
        {
            int pixel = pixels[y * image.getWidth() + x];
            buffer.put((byte)((pixel >> 16) & 0xFF)); // r
            buffer.put((byte)((pixel >> 8) & 0xFF));  // g
            buffer.put((byte)(pixel * 0xFF));         // b
            buffer.put((byte)((pixel >> 24) & 0xFF)); // a
        }
    }
    buffer.flip();
    int textureID = glGenTextures();
    glBindTexture(GL_TEXTURE_2D, textureID);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
    return textureID;
}
public static BufferedImage loadImage(String ref) throws IOException
{
    URL url = TextureRegistry.class.getClassLoader().getResource(ref);
    if (url == null)
    {
        throw new IOException("Cannot find: " + ref);
    }
    Image img = new ImageIcon(url).getImage();
    BufferedImage bufferedImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    Graphics g = bufferedImage.getGraphics();
    g.drawImage(img, 0, 0, null);
    g.dispose();
    return bufferedImage;
}
}

Icon.java
public class Icon
{
private int target;
private int iconID;
private int width;
private int height;
private int iconWidth;
private int iconHeight;
private float widthRatio;
private float heightRatio;

public Icon(int target, int iconID)
{
    this.target = target;
    this.iconID = iconID;
}
public void bind()
{
    glBindTexture(target, iconID); // binds the texture
}
public void setHeight(int newHeight)
{
    this.height = newHeight;
    setHeight();
}
public void setWidth(int newWidth)
{
    this.width = newWidth;
    setWidth();
}
public int getIconHeight()
{
    return height;
}
public int getIconWidth()
{
    return width;
}
public float getHeight()
{
    return heightRatio;
}
public float getWidth()
{
    return widthRatio;
}
public void setIconHeight(int iconHeight)
{
    this.iconHeight = iconHeight;
    setHeight();
}
public void setIconWidth(int iconWidth)
{
    this.iconWidth = iconWidth;
    setWidth();
}
private void setHeight()
{
    if (iconHeight != 0)
    {
        heightRatio = ((float)height) / iconHeight;
    }
}
private void setWidth()
{
    if (iconWidth != 0)
    {
        widthRatio = ((float)width) / iconWidth;
    }
}
}

Answer: To specify a region of a texture to be drawn all you need to do is modify your texCoords. Currently you are using your entire texture, if for example you wanted only the quarter of it closest to the origin you would use this in your draw method:
    glTexCoord2f(0, 0);
    glVertex2f(0, 0);
    glTexCoord2f(0, 1/2f);
    glVertex2f(0, height);
    glTexCoord2f(1/2f, 1/2f);
    glVertex2f(width, height);
    glTexCoord2f(1/2f, 0);
    glVertex2f(width, 0);

which would result in an image the same size as before although using only the bottom left quarter of the texture.
Comment: Thank you, that has solved it. I didn't know you could do that in the `glTexCoord2f` method, because I tried changing them to decimal points, and the picture ended up distorted, but I did not do it for all of them. Thank you.


What is the WPF version of Control.MouseButtons?

Question: What is the WPF version of Control.MouseButtons?
Answer: NVM's answer is wrong.
Control.MouseButtons is a static property that tells which mouse buttons are currently down.
Input.MouseButtonState is merely an enum.

The correct answer is Input.Mouse.  This is a static class that has an individual property per button so that you can check if that specific button is pressed or not.
Answer: MouseButtonState
http://msdn.microsoft.com/en-us/library/system.windows.input.mousebuttonstate.aspx
Comment: MouseButtonState is the equiv to Forms.MouseButtons.. but the question was in regards to Control.MouseButtons.  See my answer below for the correct equivalent.


Why is my theme table row array not being displayed?

Question: I have the below code and I know both the $headers and the $html have values stored in them as i can echo them out.
I can also set the 'header' => in the theme function to be either $header or $html and it will display the data.
However when I add in 'rows' =>, no data is displayed.
Can anyone see why?
function emnies_ad_hoc_query_exporter_get_html_formatted_ad_hoc_query_responses($obj_response) {
  $str_current_country = '';

  foreach ($obj_response as $response) {
    if ($str_current_country != $response->country) {
      $str_current_country = $response->country;
      $html = emnies_ad_hoc_query_exporter_get_country_row($str_current_country, $obj_response);
    }
  }
  $header = array('Country', 'Wider Dissemination', 'Responses');
  $output = theme('table', array(
    'header' => $header,
    'rows' => $html
  ));
  return $output;
}

function emnies_ad_hoc_query_exporter_get_country_row($str_current_country, $obj_response) {
  $rows = array();
  $i = 0;
  foreach ($obj_response as $response) {
    if ($str_current_country == $response->country) {
      if ($i == 0) {
        $rows[] = $str_current_country;
        $rows[] = $response->wider_dissemination;
      }
      $i = $i + 1;
      $rows[] = $response->response;
    }
  }
  return $rows;
}

Comment: What does `$response->response` return?  Also what exactly are you trying to do with your function?
Answer: Try looking at it this way.  From looking at your $header, you are looking for 3 columns?
foreach ($obj_response as $response) {
if ($str_current_country == $response->country) {
  $rows[] = array($str_current_country, $response->wider_dissemination, $response->response);
}

EDIT
// Test Output
$header = array(t('Country'), t('Wider Dissemination'), t('Responses'));
$rows = array();
$rows[] = array('US', 'Extremely Wide', 'Response');
print theme('table', array('header' => $header, 'rows' => $rows));

The test works for me.  Maybe something in your response value is messing with it?
Comment: Thanks @iLLin,
However even if I use
    '$header = array('Country', 'Wider Dissemination');
     $html = array(' Answer 1', 'Answer 2');
     $output = theme('table', array('rows' => $header,'rows' => $html));
     return $output;'

It still doesn't work. I just get the error "Warning: Invalid argument supplied for foreach() in include() (line 114 of sites/all/themes/ec_resp/templates/global/table.tpl.php)"
Comment: Edited the response.
Comment: Also, from your comment, you have rows listed twice in your theme('table').


Question about the differential function on a surface

Question: My question is related to this Show that $\text{grad }f=\frac{f_uG-f_vF}{EG-F^2}\textbf{x}_u+\frac{f_vE-f_uF}{EG-F^2}\textbf{x}_v$
In both answers it's assumed that $df_{p}(X_u) = f_{u}$ and $df_{p}(X_v) = f_{v}$ but I don't know why this is true. I'm even confused about what $f_u$ and $f_v$ mean.
I know that $df_{p}(v)$ is such that $df_{p}(v)$ : $T_{p}S$ $\rightarrow$ $\mathbb{R}^3$ and that $\{X_u,X_v\}$ is a basis for $T_{p}S$ but I don't know why mapping basis vectors gives us $f_u$ and $f_v$
Answer: It's sort of by definition. Given a parametrization ${\bf x} = {\bf x}(u,v)$ for a surface $S$ and $f:S \to \Bbb R$, one writes $$\frac{\partial f}{\partial u}(q) \doteq \frac{\partial (f\circ {\bf x})}{\partial u}({\bf x}^{-1}(q)) $$for any $q$ in the image of ${\bf x}$. In other words, partial derivatives of a function defined on a surface only make sense once a coordinate system has been chosen. What happens is that people don't have the patience to be precise all the time, so they identify $f$ with $f\circ {\bf x}$ and then you have to struggle to understand what is going on. For a function $F:\Bbb R^n \to \Bbb R$, in general, one has $DF(p)(e_i) = (\partial F/\partial x_i)(p)$, so applying this to the local expression $f \circ {\bf x}$ gives that $${\rm d}f({\bf x}_u) = {\rm d}f({\rm d}{\bf x}(1,0)) = {\rm d}(f \circ {\bf x})(1,0) = \frac{\partial f}{\partial u} = f_u.$$Note that I'm supressing base points above. In any case, ${\rm grad}(f)\circ {\bf x}$ is a combination of ${\bf x}_u$ and ${\bf x}_v$, so write $${\rm grad}(f)\circ {\bf x} = A{\bf x}_u+B{\bf x}_v,$$for functions $A$ and $B$ to be found. Taking products with ${\bf x}_u$ and ${\bf x}_v$ gives $$f_u = EA + FB \quad \mbox{and}\quad f_v = FA + GB.$$So $$\begin{pmatrix}E & F \\ F & G \end{pmatrix} \begin{pmatrix} A \\ B \end{pmatrix} = \begin{pmatrix} f_u \\ f_v \end{pmatrix}\implies \begin{pmatrix} A \\ B \end{pmatrix} = \begin{pmatrix} E & F \\ F & G  \end{pmatrix}^{-1}\begin{pmatrix} f_u \\ f_v \end{pmatrix}.$$This gives the expressions for $A$ and $B$.
Comment: Finally I understand it, thanks


Error validating application

Question: When trying to make a post on my wall (using the ruby gem fb_graph) I get an "Error validating application" message. I've been scouring google for solutions but to no avail. Any idea on how I should start debugging this?
Answer: "Any idea on how I should start debugging this?"
Start by taking the access token and ensuring it validates well: https://developers.facebook.com/tools/debug
and ensure it has the required permissions for posting to walls: https://developers.facebook.com/docs/reference/api/permissions/
Comment: when I input it into the debug tool, all it says is "Error validating application" with no other info. Doesn't exactly tell me much I don't already know :/
Comment: Did you try debugging your secret key?  Or an access token?
Comment: I saw it, but you might want to ensure you're getting the user access token and not an app access token.  Best way to tell what type of access token you have is to check it in the linter tool.  You can go to: https://developers.facebook.com/tools/access_token/ and take one of those tokens.

Error validating application


EF keeps trying to persist invalid object

Question: I'm having a rather strange issue with Entity Framework 4.3 in my MVC application. I'm using a Unit of Work wrapper around DbContext, and in my MVC application I use Unity to pass this UOW to my repositories, and repositories to controllers. I've registered the UOW type with the HierarchicalLifetimeManager.
When I try to persist an entity to the database that raises an error, e.g. the database throws a UNIQUE constraint violation, the entity is kept inside EF's ObjectStateManager. So when I go back in my application to fix the error and save the new entity (without errors), EF first tries to add the old and invalid object again, thus failing with the same error.
What am I missing here? I believe that the invalid object should be completely forgotten by EF and that this would be done automatically. But it's clearly not the case.
To add objects to DbContext in order to persis them, the following command gets called (where base is the DbContext):
base.Set<TEntity>().Add(objectToPersist);

And to commit the changes to the database, I call:
base.SaveChanges();

Which throws the error.
Comment: You mention that you are using HierarchicalLifetimeManager for the UoW. I am assuming that you are creating a child container per request either manually or via Unity.Mvc3. Otherwise, the UoW will be a singleton which will cause all sorts of problems.
Answer:
I believe that the invalid object should be completely forgotten by EF
  and that this would be done automatically. But it's clearly not the
  case.

Right, that's not the case and I've never heard that entities would be detached from the context automatically when an exception occured.
There are basically two options to deal with the problem. I show a simple model with your example of a unique key constraint violation:
public class Customer
{
    // so we need to supply unique keys manually
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    public string Name { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());

        using (var ctx = new MyContext())
        {
            var customer = new Customer { Id = 1, Name = "X" };
            ctx.Customers.Add(customer);
            ctx.SaveChanges();
        }
        // Now customer 1 is in database

        using (var ctx = new MyContext())
        {
            var customer = new Customer { Id = 1, Name = "Y" };
            ctx.Customers.Add(customer);

            try
            {
                ctx.SaveChanges();
                // will throw an exception because customer 1 is already in DB
            }
            catch (DbUpdateException e)
            {
                // customer is still attached to context and we only
                // need to correct the key of this object
                customer.Id = 2;
                ctx.SaveChanges();
                // no exception
            }
        }
    }
}

The above is the prefered solution: Correct the object which is attached to the context.
If you need - for whatever reason - to create a new object you must detach the old object from the context. That object is still in state Added and EF will try to save the object again when you call SaveChanges leading to the same exception as before.
Detaching the old object would look like this:
            try
            {
                ctx.SaveChanges();
                // will throw an exception because customer 1 is already in DB
            }
            catch (DbUpdateException e)
            {
                ctx.Entry(customer).State = EntityState.Detached;
                // customer is now detached from context and
                // won't be saved anymore with the next SaveChanges

                // create new object adn attach this to the context
                var customer2 = new Customer { Id = 2, Name = "Y" };
                ctx.Customers.Add(customer2);
                ctx.SaveChanges();
                // no exception
            }

This procedure can be tricky if relationships are involved. For example if customer has a relationship to a list of orders, detaching the customer object will delete references between customer and its orders if the orders are attached to the context as well. You have to reestablish the relationships with the new customer2.
Therefore I'd prefer to modify the attached object to put it into correct state. Or let the application crash because such constraint violations usually indicate bugs in the code or - in a multiuser environment - should be handled with proper optimistic concurrency checks.
Answer: looks like you'll have to tell EF that you changed your mind about the invalid object:
base.Set().Remove(objectToPersist);
Comment: Is that really necessary? I have never run into this problem with EF before - only this application. I think that EF normally does this by default when it counters an SqlException exception while trying to persist a new object.
Answer: If you want to reset the changes, you could set the ObjectContext to null and re-instantiate it.


Fastest way to get average time

Question: I have a data set with name and datetime as columns
There are multiple entries of name with different datetimes
eg. input:
 name    datetime
 ------------------
  A1  2018-07-20 17:04:20.486
  A1  2018-07-18 17:48:30.910
  A1  2018-07-18 19:13:05.636
  A1  2018-07-17 15:01:30.976
  A1  2018-07-17 18:21:13.113
  B7  2018-07-18 16:38:33.410
  B7  2018-07-18 17:30:46.893
  B7  2018-07-17 15:45:48.673
  B7  2018-07-18 03:01:41.826
  B7  2018-07-19 18:12:40.923
  C3  2018-07-18 19:07:41.973
  C3  2018-07-17 16:59:51.646
  C3  2018-07-18 19:41:41.280
  C3  2018-07-20 16:01:44.543
  C3  2018-07-20 16:01:22.860

I need to just figure out the mean/avg TIME for each name
sample output:
name    avg_time
 B7    14:13:54
 A1    17:29:44
 C3    17:34:28

Solution #1
I have tried to replace the date with current date and then perform
groupby on name and get the mean time
today = pd.datetime.today()
data['datetime'] = data['datetime'] .apply(lambda x: x.replace(day=today.day, month=today.month, year=today.year))

for name, group in data.groupby(by='name'):
    avg_datetime(group['datetime'])

# avg_time calculation
def avg_datetime(series):
    """
    takes a series of datetime and returns the avarage time in '%H:%M' format
    :param series:
    :return:
    """
    series = pd.to_datetime(series)
    dt_min = series.min()
    deltas = [x - dt_min for x in series]
    avg_datetime = dt_min + functools.reduce(operator.add, deltas) / len(deltas)
    return avg_datetime.time().strftime('%H:%M')

Solution #2
I have also tried to convert the time to total number of minutes and then
calculate the mean and change back the format
# convert to total minutes
dt_index = pd.DatetimeIndex(pd.to_datetime(data['datetime']).dt.strftime('%H:%M'))
data['total_mins'] = dt_index.hour * 60 + dt_index.minute

mean_mins_list = [[name, int(group['total_mins'].mean())]
                  for name, group in data.groupby(by='name', sort=False, as_index=False)]
avg_time_df = pd.DataFrame(mean_mins_list, columns=['name', 'avg_time'])

# revert to HH:MM format
avg_time_df['avg_time'] = avg_time_df['avg_time'].apply(lambda x: str(math.floor(x / 60)) + ':' + str(x % 60))

my dataset is very huge, ~ 10 million unique names, what is the fastest way to perform this operation
Answer: Here's one option.
Calculate the total number of seconds for each datetime from the start of that day. Then groupby and calculate the mean, since they are just numbers at that point. Finally, convert back to a datetime, and just select the time part.
import pandas as pd

df['secs'] = (df.datetime - df.datetime.dt.normalize()).dt.total_seconds()
pd.to_datetime(df.groupby('name').secs.mean(), unit='s').dt.time

Output:
name
A1    17:29:44.224200
B7    14:13:54.345000
C3    17:34:28.460400
Name: secs, dtype: object

Fastest way to get average time


where can i get a tutorial for using visual studio installer

Question: Anyone have suggestions on good tutorials or examples of how to create MSI packages using visual studio?
In particular, I'm interested in creating a deployment package for an ASP.NET website.
Comment: Do you mean creating installers?
Comment: Checking in his questions and answers you could see it's not that, but the way this question was written it completely misleads you to understand he doesn't know how to instal visual studio itself.
Answer: Assuming by "Visual Studio Installer" you mean creating an installer in Visual Studio, this one seems like it covers quite a few topics.  It gives you a quick and dirty way (via wizard) to get your installer working, then goes into details on how to change other properties, like version numbers, icons and such.
The wording of your title might prevent people from attempting to answer because Visual Studio Install is taken to mean the installer for putting VS on your system, whereas the wording of your questions and your history on SO indicate that you have VS installed and are probably wanting to create an installer for a VS project.  Clarifying this point will probably give you better responses.


How to read rules from a file

Question: I am trying to match the sentence against rules.
I am able to compile multiple rules and match it against CoreLabel using the following method :
TokenSequencePattern pattern1 = TokenSequencePattern.compile("([{tag:/NN.*//*}])");
TokenSequencePattern pattern2 = TokenSequencePattern.compile("([{tag:/NN.*//*}])");

List<TokenSequencePattern> tokenSequencePatterns = new ArrayList<>();
tokenSequencePatterns.add(pattern1);
tokenSequencePatterns.add(pattern2);

MultiPatternMatcher multiMatcher = TokenSequencePattern.getMultiPatternMatcher(tokenSequencePatterns);
List<SequenceMatchResult<CoreMap>> matched=multiMatcher.findNonOverlapping(tokens);

I have many rules inside a file. Is there any way to load the rule file?
I have seen a method to load the rules from file using the following method:
CoreMapExpressionExtractor extractor = CoreMapExpressionExtractor.createExtractorFromFiles(TokenSequencePattern.getNewEnv(), "en.rules");
List<MatchedExpression> matched = extractor.extractExpressions((CoreMap)sentence);

But it accepts CoreMap as its argument. But I need to match it against CoreLabel
Answer: Please see this comprehensive write up on TokensRegex:
https://stanfordnlp.github.io/CoreNLP/tokensregex.html

How to read rules from a file


What do Four Vertical Dots mean?

Question: I was looking through a score by Bartok (5th String Quartet) and came across a symbol I didn't recognize. There is a dot between each line in the clef.
What does this mean?

Edit: Here's another example, which looks more like a barline:
Comment: If I would have a guess I would think it is and arpeggio marking.
Answer: In this particular quartet, the solid bar lines are being used for coordination, but the instruments themselves are following their own metres which are demarcated by the dotted bar lines: the music is polymetric. The beaming across the bar line confirms this interpretation.
In the first example, the first violin is counting 4/8, 5/8, 3/8, 4/8; the 2nd violin is counting 4/8, 5/8, 7/8; and the viola and 'cello are counting 6/8, then two bars of 5/8. (The interpretation of each instrument's first and last "bars" might change depending on what precedes and follows the example.)
In the second example, the first and second violins are completing a "bar" with their first two quavers, then following with two bars of 7/8; the viola and 'cello are beating 5/8, 4/8 and 7/8.
Comment: Well, it's polymetre with a twist: not only are the instruments following their own metres, but those metres are constantly changing.
Comment: Yay for Bartok!
Comment: I was looking for a pattern but they kept falling after different numbers of eighths. Thanks!
Answer: This sort of notation normally means a "semi-barline". I have seen it where (e.g.) a 4/4 bar is divided into two halves by a dotted barline, meaning "It's in 4/4, but well you might also feel it in 2/4".
This example is a bit more difficult, but then it is Bartok. I would guess that the parts are supposed to "feel" the tempo divided into different ways.
But you needn't take my word for it: Gardner Read calls them "dotted barlines", and even discusses the Bartok string quartet no. 5, which divides up the different parts in just this way.
Comment: Gardner Read, "Music Notation", the section beginning p. 215 in the paperback edition I have...
Comment: Got a link for that citation? That's interesting, and "Bartok-y". I wondered about dotted barline, but they occur all over the place within the measures and across parts that it didn't seem likely. See edit, I think you're right.
Comment: Elain Gould in *Behind the Bars* also calls them *dotted barlines*. She state that they mark subdivisions of a bar, especially useful in very long bars or irregular ones, e.g. subdivided 2+2+3.

What do Four Vertical Dots mean?


Calculate $2^{5104} \bmod 10$ using mental arithmetic

Question: I am practising interview for Jane Street's trader internship and I found the following question.

Question: Calculate $2^{5104} \bmod  10$ using mental arithmetic.

I know that $2^5 \bmod 10 \equiv 2 \bmod 10.$
So,
\begin{align*}
2^{5104} & = (2^5)^{1020} 2^4 \\
& \equiv 2^{1020}2^4 \\
& = (2^5)^{204}2^4 \\
& \equiv(2^5)^{40}2^8 \\
& \equiv (2^5)^8 2^8 \\
& \equiv (2^5)^3 2 \\
& \equiv 6 \bmod 10.
\end{align*}
However, I find the calculations above very taxing if I use mental arithmetic. I believe there should be a faster way to answer the question but I am not able to find one.
Comment: Mental arithmetic depends on practice and what facts you have available.  I find your approach a good one and with practice you can keep it in your head.  A more useful fact is that the cycle of $2^k \pmod m$ divides $\phi(m)$.  As $\phi(10)=4$ the cycle of $2^k \pmod {10}$ repeats with period $4$ (and maybe $2$ or $1$).  Then $2^{5104} \equiv 2^4 \equiv 6 \pmod {10}$.
Comment: Does this answer your question? [How do I compute $a^b\,\bmod c$ by hand?](https://math.stackexchange.com/questions/81228/how-do-i-compute-ab-bmod-c-by-hand)
Comment: I added an answer highlighting a *general* rule for problems like this. There are [over $74$ worked examples here.](https://math.stackexchange.com/questions/linked/2059752?sort=votes)
Comment: $4\mid100$, so $4\mid5100$, so $4\mid5104$
Comment: @Bill Dubuque Nice. Thanks.
Answer: The cycle of units digits goes $2,\ 4,\ 8,\ 6,\ 2,...$, in a cycle of length 4 after the initial term of 1. $5104\equiv 4\pmod 4$, so the answer is the fourth term in the cycle which is $6$.
Comment: @Idonknow Sheesh, I managed to talk myself out of the correct explanation back there.  It is mod 4.
Comment: Haha you are right. May I know whether there is a theorem to justify your solution?
Comment: @Idonknow It's just calculating $2^{5104}\bmod 5$ knowing that $2^4\equiv 1\pmod 5$.  Then to figure it out mod 10 you just need to realize that 6 is the unit's place that is both even and equivalent to 1 modulo 5.
Comment: @Idonknow Again, **beware** that to be rigorous we need to either perform an *explicit* induction to prove how the pattern holds for all naturals (or else use some related result that does so). See my [comments on farruhota's answer](https://math.stackexchange.com/questions/3492787/calculate-25104-bmod-10-using-mental-arithmetic/3493676#comment7185638_3493052) for elaboration.
Answer: The Chinese Remainder Theorem says:
$$2^{5104}\equiv x \pmod{2\cdot 5} \iff \begin{cases}2^{5104}\equiv x\pmod 2 \\ 2^{5104}\equiv x\pmod 5\end{cases}$$
It follows that $x\equiv 0\pmod 2$ and $x\equiv 1\pmod 5$.
Consequently $x\equiv 6\pmod{10}$.
Comment: @Zaz, it's Fermat's small theorem: $a^{p-1}\equiv 1\pmod p$ for prime $p$ and relative prime $a$. So $2^4\equiv 1\pmod 5$ and $2^{5104}$ is a power of that.
Comment: How did you get that $x \equiv 1 \pmod 5$?
Answer: $$2^{5104}\equiv 16^{1276}\pmod{10}$$
$$\equiv 6\pmod {10}$$
Comment: Every power of a number ending in $6$ ends with $6$.
Comment: Can you elaborate how to obtain second equivalence?
Comment: I see. But I think that only applies to this particular case. More precisely, it applies when the power is divisible by $4.$
Comment: Yeah, @Idonknow.
Comment: @Idonknow $\ \bmod 10\!:\,\ 6^{\large 1+N} = 2(3\cdot 6^{\large N}\!\bmod 5) = 2(3) = 6\ $ as in my answer. See the [Remark here](https://math.stackexchange.com/a/2973731/242) for much further discussion on how this is related to alternative proofs (by induction, or by CRT or the Factor Theorem) for this  **power law for idempotents**.
Answer: $$2^{4n+2}=(5-1)^{2n+1}=-(1-5)^{2n+1}$$
$$\equiv-1\pmod5\equiv4$$
$$\implies2^{4n+4}\equiv4\cdot2^2\pmod{5\cdot2^2}$$
Answer: if a number is not divisible by five, its fourth power is equivalent to $1 \pmod 5$
Comment: Can you elaborate on how your suggestion work on my question?
Answer: This is the same as determining the units digit of $2^{5104}$. The units digit of the powers of $2$ repeat in the sequence $2,4,8,6$ (i.e. the $(4k+i)$th power of $2$, where $k\in\mathbb{Z}$ and $1\leq i\leq 4$, is the $i$th term in the sequence). Since $5104$ is a multiple of $4$, the answer is $6$.
Comment: Can you justify your last sentence? Why would $5104$ a multiple of $4$ gives the answer $6?$
Comment: $5104$ is also a multiple of $2$. Why isn't it $4?$
Comment: Euler totient theorem.
Comment: or an equivalent you can divide out by gcd to get rid of some complexity.
Comment: @Idonknow **Beware** that to obtain a *complete, rigorous* proof we need to either perform an *explicit* induction to prove how the pattern holds for all naturals (or else use some related result that does so). See my [comments on farruhota's answer](https://math.stackexchange.com/questions/3492787/calculate-25104-bmod-10-using-mental-arithmetic/3493676#comment7185638_3493052) for elaboration.
Answer: What is the remainder when you divide the exponent by 4?
If it is $0$ then last digit will be $6$. When it is $1$ then last digit will be $2$. For $2$ as remainder, last digit will be $4$ and finally for $3$, last digit is going to be $8$.But all this does not work when the exponent is $0$. For that case, last digit is $1$. So in present case, as the exponent $5104$ is wholly divisible by $4$, the last digit will be $6$.
The divisibility of a number by $4$ is not difficult to check either.  You just need to check number formed by the last two digits of the given number. The remainder that we get by dividing this number by 4 will be same as the remainder we get in case of original number. For the present case the two digit number is $04$ which is wholly divisible by $4$. And hence the original number $5104$ is also wholly divisible by $4$.
Answer: Mental arithmetic comes with practice. For $n>0$:
$$2^{n}\equiv 2,4,8,6 \pmod{10} \Rightarrow 2^{5104}\equiv 2^{4\cdot 1276}\equiv 6\pmod{10}\\
3^{n}\equiv 3,9,7,1 \pmod{10} \Rightarrow 3^{5104}\equiv 3^{4\cdot 1276}\equiv 1\pmod{10}\\ 4^{n}\equiv 4,6 \pmod{10} \Rightarrow 4^{5104}\equiv 4^{2\cdot 2502}\equiv 6\pmod{10}\ \ \ \ \ \ \ \ \\
7^{n}\equiv 7,9,3,1 \pmod{10} \Rightarrow 7^{5104}\equiv 7^{4\cdot 1276}\equiv 1\pmod{10}\\
8^{n}\equiv 8,4,2,6 \pmod{10} \Rightarrow 8^{5104}\equiv 8^{4\cdot 1276}\equiv 6\pmod{10}\\
9^{n}\equiv 9,1 \pmod{10} \Rightarrow 9^{5104}\equiv 9^{2\cdot 2502}\equiv 1\pmod{10} \ \ \ \ \ \ \ \ $$
Different examples:
$$2^{n}\equiv 2,4,8,6 \pmod{10} \Rightarrow 2^{5102}\equiv 2^{4\cdot 1275+2}\equiv 4\pmod{10}\\
9^{n}\equiv 9,1 \pmod{10} \Rightarrow 9^{5105}\equiv 9^{2\cdot 2502+1}\equiv 9\pmod{10}$$
Can you find: $2^{325} \bmod 10$? $13^{1234} \bmod 10$? Answer:

 $2^{n}\equiv 2,4,8,6 \pmod{10} \Rightarrow 2^{325}\equiv 2^{4\cdot 81+1}\equiv 2\pmod{10}\\13^n\equiv 3^{n}\equiv 3,9,7,1 \pmod{10} \Rightarrow 13^{1234}\equiv 3^{4\cdot 308+2}\equiv 9\pmod{10}$
Comment: I am able to calculate the questions given in your post easily now. Thanks. By the way, do you know of any source (book/website) that contains a lot of exercises on calculating $a^b \bmod c$? I need to practise more.
Comment: Here are [one](https://artofproblemsolving.com/wiki/index.php/Modular_arithmetic/Introduction) and [two](https://www.brainkart.com/article/Exercise-2-3--Modular-Arithmetic_39312/).
Comment: @Idonknow **Beware** that there are no *proofs* above. What is displayed are  *cyclic patterns* that could be used to compose proofs. But to obtain a complete rigorous proof you either need to *explicitly* perform the hinted induction or else use some other method that nicely encapsulates the induction, e.g. the Congruence Power Rule, or the mod Distributive Law (as in my answer, which reduces the induction to the *trivial* induction $\,1^n\equiv 1;\,$ see the [Remark here](https://math.stackexchange.com/a/2973731/242) for much more on that)
Comment: One could argue that one of the main goals of an (elementary) Number Theory course is to teach how to properly make such arithmetical inductions, e.g.to prove that for *all* primes $\,p,\,$ we have $p\mid ab\,\Rightarrow\, p\mid a\,$ or $\,p\mid b.\,$ Ancients saw patterns for small primes but did not know how to (inductively) extend that intuition to a rigorous proof that works for *all* primes. Not too infrequently such patterns can hold for very many small number then later fail, so rigorous inductive proofs are *essential* in order to obtain correct results.
Comment: See R. K Guy's [Strong Law of Small Numbers](https://en.wikipedia.org/wiki/Strong_Law_of_Small_Numbers) for many interesting examples of such empirical "inductions" that fail to hold true.
Answer: Notice  $\,\ 2^{\large 4+4N}\!\bmod 10
\, =\, \color{#c00}2\overbrace{(2^{\large 3}  \color{#0a0}2^{\large\color{#0a0}4N}\bmod 5)}^{\textstyle \color{#0a0}{2^{\large 4}}\!\equiv 1\pmod{\!5}} = 2(3)$
by applying $\ \color{#c00}ab\bmod \color{#c00}ac\, =\, \color{#c00}a(b\bmod c) = $ $\!\bmod\!$ Distributive Law to factor out $\,\color{#c00}{a=2}$


What is the difference between changing a songs beat unit and its BPM?

Question: A song in 3/8 is typically twice as fast as a song in 3/4, so what is the difference from doubling the BPM?
EDIT: I am aware of the difference between 3/8 and 3/4, but then what is the difference between a quaver played in a piece with a certain BPM and a crotchet played in a piece with double that BPM?
Answer: It's probably more to do with the style or feel of the piece.  Often a 3/8 piece would be in 1 whereas a 3/4 one would feel in 3 but that's a generalization.  You can of course have a slow piece in 3/8 and a fast one in 3/4.  Bottom line is there is no real difference between the two time signatures.
There is no difference between the two examples you give.  It would be to do with convenience when writing it out.
Answer: It's by no means a given that 3/8 will be twice as fast as 3/4.   There are some pretty slow 3/8 movements in the classical repertoire and plenty of fast waltzes written in 3/4.   You are correct, a quaver in 3/8 at [dotted crotchet=60], will be the same length as a crotchet in 3/4 at [crotchet=180].
There have been various conventions regarding whether to choose 3/4 or 3/8 over the ages.  They were never particularly rigid, and musical scholars delight in arguing over them :-)


Find the parameters a and b such that the function is continuous at $x=0$

Question: $$
f(x) =
\begin{cases}
\cos(x+a) & x<0 \\
e^{(x+b)^2} & x \ge 0
\end{cases}
$$
a) Find $a$ and $b$ such that the function is continuous at $x=0$.
So what I did:
$$ \cos(0+a) = e^{b^2} \quad\text{(eq1)}$$
and then I equated their derivatives:
$$ -\sin(a) = 2b e^{b^2} \quad\text{(eq2)}$$
and so the final equation became:
$$ \tan (a) = -2b. $$
What do I do after this?

Also part b was show that the equation $e^x = 2 + \cos x$ has a unique solution. I graphed the equation and it is true, but how do I show it otherwise?
Thank you in advance!
Answer: For part (a) it looks like you can simply take $a = 0$ and $b = 0$.
For part (b) observe that $1 \le 2 + \cos x \le 3$ for all $x$ and that $1 \le e^x \le 3$ only for $x \in [0, \log 3]$. On that interval $e^x$ is increasing and $2 + \cos x$ is decreasing so $e^x - (2 + \cos x)$ is increasing. Can you have an increasing function cross the $x$-axis more than once? Is there a theorem that says that gives a condition for when a function crosses the $x$-axis?
Comment: Okay so by the intermediate value theorem (a function which starts below the x-axis and finishes above must cross the x-axis) so that means it only crosses once. Also since it is an increasing exponential function we can say it is an one-to-one function which gives us an unique solution.
Comment: @Zeemz97 Careful, you wrote that the IVT means that it "only crosses once". The IVT shows that it crosses and the fact that it is increasing means that it can't cross at multiple points (you should try showing this from the definition of increasing: $x < y \implies f(x) < f(y)$).


Flask-Admin: add filter for parent's field

Question: I need to apply a filter based on a parent's field, i.e., I need to filter by Driver's name (parent) in the model view for the Shift model (child). These are my models:
import datetime

from sqlalchemy import Integer, DATE, ForeignKey, Column, String
from sqlalchemy.orm import registry, declarative_mixin, declared_attr

mapper_registry = registry()

@declarative_mixin
class Basic:
    @declared_attr
    def __sa_dataclass_metadata_key__(cls):
        return "sa"

    @declared_attr
    def __tablename__(cls):
        return snakecase(cls.__name__)

@mapper_registry.mapped
@dataclass
class Driver(Basic):  # parent
    id: int = field(init=False, metadata=dict(sa=Column(Integer, autoincrement=True, unique=True, primary_key=True, nullable=False)))
    name: str = field(metadata=dict(Column(String(255), nullable=False)))

@mapper_registry.mapped
@dataclass
class Shift(Basic):  # child
    id: int = field(init=False, metadata=dict(sa=Column(Integer, autoincrement=True, unique=True, primary_key=True, nullable=False)))
    date: datetime.date = field(metadata=dict(sa=Column(DATE, nullable=False)))
    driver_id: int | None = field(metadata=dict(sa=Column(Integer, ForeignKey('driver.id'), nullable=True)))

    driver: Driver | None = field(metadata=dict(sa=lambda: relationship('Driver', lazy=False)))

This is my model view for the Shift model:
from flask_admin.contrib.sqla import ModelView

class ShiftModelView(ModelView):
    """ModelView to manage Shift model."""

    form_columns = ["id", "date"]
    form_widget_args = {"id": {"disabled": True}}
    column_list = [
        "id",
        "date",
    ]
    column_searchable_list = ["id", "date"]

I need to apply a filter by Driver's name in my model view ShiftModelView. I was thinking of adding a custom filter, but is there an easier way to achieve this?
Answer: This can be achieved by adding "driver.name" (parent class) to the model view's column_filters:
from flask_admin.contrib.sqla import ModelView
class ShiftModelView(ModelView):
"""ModelView to manage Shift model."""
...
column_filters = ["driver.name"]
...

Notice that driver references the relationship of Driver in Shift, and the . (dot operator) access the field in the parent class.


Passing datatable from one form to another

Question: I want to copy datatable to another form.
Form1.cs
public DataTable Data1
{
    get { return dtDetailsAll; }
}

Form2.cs
Form1 m = new Form1();
dtSessionst = m.Data1.Copy();

However it doesn't copy the values. Can you help me on it ?
Comment: You're making a new (empty) instance of Form1 and getting the data from there, is there any data in there when you open it at first? because this wont work if not. If you need the data in form 2 just pass it as parameter to form2 :)
Comment: @EpicKip Could you please write as an answer?
Comment: do you open form2 from form1? and when you open it is the data already present in form1?
Answer: You have the wrong instance of Form1 in Form2.cs. using the key word new :
Form1 m = new Form1();

you create a new instance which is different from that one where the full DataTable Data1 exists.
Solution: You need to pass the right instance to Form2.
1) create a second constructor in Form2 which can take a Form1 as parameter
2) save it in a class field:
private Form1 frm1;
public Form2(Form1 f1)
{
    frm1 = f1;
    InitializeComponent();
}

3) now you can use this variable to access Data1:
dtSessionst = frm1.Data1.Copy();

Comment: I did this however, empry form appears, control are not initializing. Both constructor should have InitializeComponent(); ?
Comment: I read your comment yesterday. It is important that you keep the original parameterless constructor and make a "second" one. Yes both constructors need the `InitializeComponent()` call, otherwise no controls will be on the form. You can call the original constructor from the second constructor like this: `public Form2(Form1 f1) : this(){...}` this way the `InitializeComponent` call will be made irrespective of which constructor you use.


Default VS2010 IList type in Intellisense/ReSharper

Question: Let's say I have the following function:
public IList<string> Foo()
{
  // code goes here
}

I'm used to being able to type in return new and as soon as I hit [SPACE], Intellisense pops up and suggests List<string> but right now it defaults to ReadOnlyCollectionBuilder<string> and the only other option in there is TrackableCollection<string>. I recently rebuilt my dev environment and I no longer get this functionality. I THOUGHT that this was the default. I've never had this problem before (and have built more than half a dozen development environments with VS2010).
What setting(s) do I change to get this back?
Comment: Not sure. Works fine for me with VS2010 + ReSharper 6. If you look in ReSharper > Options > IntelliSense > General, is the "ReSharper" radio button selected?
Comment: @Joe White: Yup, that's set to `ReSharper`
Comment: It works in my ReSharper 5.1, VS2010.
Comment: It works fine in some of my VS2010s as well. Just not one of them, which was a clean install. Made no sense to me.
Answer: I finally figured the answer out to this. Specific versions (but not all) of Telerik's JustCode was causing this. Upgrading, disabling, or uninstalling JustCode finally made this problem go away.


powerquery group by rows with formula on multiple columns

Question: I am trying to group/merge two rows by dividing the values in each based on another column (Eligible) value.
From the initial raw data, I have reached this level with different steps (by unpivoting etc.) in power query.

Now I need to have a ratio per employee (eligible/not-eligible) for each month.
So for employee A, "Jan-14" will be -10/(-10 + -149) and so on. Any ideas will be appreciated. Thanks

Really appreciate the response. Interestingly, I have used your other answer to reach this stage from the raw data.
Since we are calculating how much time an employee worked on eligible activities each month so We will be grouping on the Employee. Employee name was just for reference which I took out and later will join with employee query to get the names if required. There was a typo in the image, the last row should also be an employee with id 2.
So now when there is a matching row, we use the formula to calculate the percentage of time spent on eligible activities but
If there isn't a matching row with eligible=1, then the outcome should be 0
if there isn't a matching row with eligible-0, then the outcome should be 1 (100%)
Answer: Try this and modify as needed. It assumes you are starting with all Eligible=0 and will only pick up matching Eligible=1.  If there is a E=1 without E=0 it is removed.  Also assumes we match on both Employee and EmployeeName
~ ~ ~ ~ ~
Click select the first three columns (Employee, EmployeeName, Eligible), right click .... Unpivot other other columns
Add custom column with name "One" and formula =1+[Eligible]
Merge the table onto itself, Home .. Merge Queries...   with join kind Left Outer
Click to match Employee, EmployeeName and Attribute columns in the two boxes, and match One column in the top box to the Eligible Column in the bottom box
In the new column, use arrows atop the column to expand, choosing [x] onlt the Value column.  Make the name of the column: Custom.Value
Add column .. custom column ... formula = [Custom.Value] / ( [Custom.Value] + [Value])
Filter Eligible to only pick up the zeroes using the arrow atop that column
Remove extra columns
Click select Attribute column, Transform ... pivot ... use custom as the values column
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"Employee", "EmployeeName", "Eligible"}, "Attribute", "Value"),
#"Added Custom" = Table.AddColumn(#"Unpivoted Other Columns", "One", each 1+[Eligible]),
#"Merged Queries" = Table.NestedJoin(#"Added Custom",{"Employee", "EmployeeName", "Attribute", "One"},#"Added Custom",{"Employee", "EmployeeName", "Attribute", "Eligible"},"Added Custom",JoinKind.LeftOuter),
#"Expanded Added Custom" = Table.ExpandTableColumn(#"Merged Queries", "Added Custom", {"Value"}, {"Custom.Value"}),
#"Added Custom1" = Table.AddColumn(#"Expanded Added Custom", "Custom", each [Custom.Value]/([Custom.Value]+[Value])),
#"Filtered Rows" = Table.SelectRows(#"Added Custom1", each ([Eligible] = 0)),
#"Removed Columns" = Table.RemoveColumns(#"Filtered Rows",{"Eligible", "Value", "One", "Custom.Value"}),
#"Pivoted Column" = Table.Pivot(#"Removed Columns", List.Distinct(#"Removed Columns"[Attribute]), "Attribute", "Custom", List.Sum)
in #"Pivoted Column"

Comment: Thanks a lot. that's great. I didn't realize that we can do a self join with power query.
Comment: Also, I have updated the question to make the example more elaborate. Thanks for the patience and assistance.


Celery Beat not Scheduling Task in Django Project

Question: I'm working on a Django project where I'm using Celery for task scheduling. I have a periodic task that should run every minute, but it seems that Celery Beat is not picking up this task. Here's my setup:
tasks.py:
from celery.schedules import crontab
from ..apps.scraper.scrapers.updates import get_updates
from .settings import app

app.conf.beat_schedule = {
    "get_updates": {
        "task": "..apps.scraper.scrapers.updates.get_updates",
        "schedule": crontab(minute="*/1"),  # Run every 1 minute
    },
}

celery.py:
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "manga_project.settings")

app = Celery("manga_project")

app.config_from_object("django.conf:settings", namespace="CELERY")

app.autodiscover_tasks()

app.conf.broker_url = "redis://localhost:6379/0"

updates.py:
@app.task
def get_updates():
    print("Looking for manga updates...")
    mangas = Manga.objects.all()
    for manga in mangas:
        print("Checking ", manga.title, " ...")
        scrape_chapters("str", manga.url)

I expect the get_updates task to run every minute, but it's not happening. When I start Celery Beat, it doesn't seem to pick up this task when I check the debbuger.
I tried restarting celery and adding some error handling, but the tasks just simply doesnt get picked up so I am not sure how to handle this.
Any advice would be appreciated.
Answer: autodiscover_tasks Searches a list of packages for a "tasks.py" module which is default related_name for search.
As your tasks reside in updates.py
so change app.autodiscover_tasks() to app.autodiscover_tasks(related_name='updates') to check for updates.py
read autodiscover_tasks parameters and what it does
You can take a look here if you have task files are not in the same relative location
Celery discover tasks in files with other filenames
and of course, you can change the updates.py to tasks.py if that works


Struggling to Understand Algorithm for Displaying Polynomial Matings with Julia Sets

Question: I'm working on creating a program that visualizes projected Julia Sets on a Riemann Sphere (such as my video here) when I came across this website visualizing matings between Julia Sets, and I want to recreate them for my own program (such as this video). However, with any resource that I've read that explains the process, I can't seem to wrap my mind around what's going on... I'm not sure if I simply don't yet have the formal education required (my knowledge of complex analysis is only limited to visualizing iterated fractals), or if these sources are just hard to understand.
What I want to learn specifically about is what is described here (from the previous website - what's in bold is what I want to learn, and what's italicized is what I have a hard time conceptually understanding):
"A progressive interpolation was introduced, between the two polynomial Julia sets and their mating. It consists in gluing equipotentials together and gives a holomorphic dynamical system between different spheres (this was observed by Milnor). This dynamical systems gives an easy method for drawing a conformally correct picture of the deformation of the polynomial Julia sets under the equipotential gluing: this method was explained to me by Buff. The result is an image which depends on the potential. This is what the movies show: the potential starts high and slowly approaches 0."
Essentially, what I'm looking for is given:

some point z on the complex plane (I already know how to project this
onto the Riemann Sphere)
two filled Julia Set coordinates $c_1$ and $c_2$ (for example, the Basilica and Rabbit - eventually I hope to move beyond two)
some value t that represents the value of the potential that decreases to 0 (for the mating animation)
some value n that represents the maximum escape-time iterations
some value b that represents the bailout value

... do some math that calculates the color for that point (just like the escape-time algorithm - though this is the limit of my understanding, so I'm hoping that I can visualize the matings in the same way) when it's projected on the Riemann Sphere. Is this possible? I would be grateful for anything to help my understanding with this! If I'm in too far in over my head with this kind of math, then I'd also be satisfied with a copy-and-paste solution for my particular goal here.
I already tried reading these papers:

Pasting Together Julia Sets: A Worked Out Example of Mating
The Medusa Algorithm for Polynomial Matings
The Thurston Algorithm for Quadratic Matings
Slow mating and equipotential gluing
Slow mating of quadratic Julia sets

I did consider putting this on StackOverflow instead, but I think this is more of a math question than a programming one.
EDIT:
After a week of going through Claude's code, I finally figured out an algorithm to which I can display the slow mating in real time! Its implementation in my project is not without a couple of bugs, but I was able to get the basic animation working (I've made some videos to show the mating of Basilica vs. Rabbit, its inverse, and its projection on the Riemann Sphere). The algorithm is as follows:
INITIALIZATION
Constants
R1 >= 5
R2 = R1 * R1
R4 = R2 * R2

Variables
# the two Julia Sets to slow mate
Complex p
Complex q

# mating presets
int mating_iterations
int intermediate_steps

# Julia Set presets
int julia_iterations
float bailout

# image presets
int width
int height

# intermediate path segments
Complex x [mating_iterations * intermediate_steps]
Complex y [mating_iterations * intermediate_steps]

# store inverse of pullback function (https://mathr.co.uk/blog/2020-01-16_slow_mating_of_quadratic_julia_sets.html)
Complex ma [mating_iterations * intermediate_steps]
Complex mb [mating_iterations * intermediate_steps]
Complex mc [mating_iterations * intermediate_steps]
Complex md [mating_iterations * intermediate_steps]

# what's sent to the GPU
Complex ma_frame [mating_iterations];
Complex mb_frame [mating_iterations];
Complex mc_frame [mating_iterations];
Complex md_frame [mating_iterations];

# Compute potentials and potential radii
float t[intermediate_steps]
float R[intermediate_steps]

for s: the count of intermediate segments
{
    t[s] = (s + .5) / intermediate_steps

    R[s] = exp(pow(2, 1 - t[s]) * log(R1))
}

p_i = 0     # nth iteration of the p Julia Set
q_i = 0     # nth iteration of the q Julia Set

# Calculate path arrays (Wolf Jung's equations 20 and 21)
for i: each frame in mating_iterations*intermediate_steps
{
    # i = intermediate_steps * n + s
    # for each n:
    #     for each s
    int s = i % intermediate_steps;
    int n = (i - s) / intermediate_steps;    # this is not needed here

    # Equation 20
           1 + ((1 - t[s]) * q / R2)                p_i / R[s]
    x[i] = ------------------------- * -------------------------------------
           1 + ((1 - t[s]) * p / R2)   1 + ((1 - t[s]) * q / R4 * (p_i - p))

    # Alternatively, if R1 = 1e10
    x[i] = p_i / R[s]

    # Equation 21
           1 + (1 - t[s]) * q / R2   R[s]
    y[i] = ----------------------- * ---- * (1 + ((1 - t[s]) * p / R4 * (q_i - q)))
           1 + (1 - t[s]) * p / R2   q_i

    # Alternatively, if R1 = 1e10
    y[i] = R[s] / q_i

    if (s == intermediate_steps - 1)    # last 's' before new 'n'
    {
        p_i = p_i^2 + p
        q_i = q_i^2 + q
    }
}

Prior to point calculation (CPU Render Loop)
# This could've be done using a nested for loop, but I needed to be consistent with my notation so I could understand the algorithm easier

for i: each frame in mating_iterations*intermediate_steps
{
    # i = intermediate_steps * n + s
    # for each n:
    #     for each s
    int s = i % intermediate_steps;
    int n = (i- s) / intermediate_steps;

    int first = intermediate_steps + s
    int s_prev = (s + intermediate_steps - 1) % intermediate_steps

    if (n > 0)
    {
        // Pull back x and y (Wolf Jung's Equation 22)
        for k: count of total mating iterations - current mating iteration (n)
        {
            int k_next = k + 1
            int next = intermediate_steps * k_next + s
            int prev = intermediate_steps * k + s_prev

                         (  1 - y[first]     x[next] - x[first]  )
            z_x[k] = sqrt(  ------------  *  ------------------  )
                         (  1 - x[first]     x[next] - y[first]  )

                                                     x[first]
                                                 1 - --------
                         (  (1 - y[first])           y[next]   )
            z_y[k] = sqrt(  --------------  *  --------------  )
                         (  (1 - x[first])           y[first]  )
                                                 1 - --------
                                                     y[next]

            // choose sign by continuity
            if (length(-z_x[k] - x[prev]) < length(z_x[k] - x[prev]))
            {
                z_x[k] = -z_x[k]
            }
            if (length(-z_y[k] - y[prev]) < length(z_y[k] - y[prev]))
            {
                z_y[k] = -z_y[k]
            }
        }

        // copy results into path arrays
        for k: count of total mating iterations - current iteration (n)
        {
            x[intermediate_steps * k + s] = z_x[k]
            y[intermediate_steps * k + s] = z_y[k]
        }
    }

    a = x[intermediate_steps + s]
    b = y[intermediate_steps + s]
    ma[i] = b * (1 - a)
    mb[i] = a * (b - 1)
    mc[i] = 1 - a
    md[i] = b - 1

    for k: 0 to current mating iteration (n)
    {
        ma_frame[k] = ma[intermediate_steps * k + s]
        mb_frame[k] = mb[intermediate_steps * k + s]
        mc_frame[k] = mc[intermediate_steps * k + s]
        md_frame[k] = md[intermediate_steps * k + s]
    }

    # SEND VARIABLES TO GPU
        julia_iterations
        bailout
        p
        q
        R (taken from 'R[s]')
        current_mating_iteration (taken from 'n')
        ma_frame
        mb_frame
        mc_frame
        md_frame
}

Apply for each point on the complex plane (GPU Fragment Shader: for each pixel on the screen)
z = point on complex plane

for k: starting from current_mating_iteration and decreasing to zero
{
        ma_frame[k] * z + mb_frame[k]
    z = -----------------------------
        mc_frame[k] * z + md_frame[k]
}

if (length(z) < 1)
{
    c = p
    w = R * z
}
else
{
    c = q
    w = R / z    # note: this is complex division
}

for i: the rest of the regular Julia Set iterations (julia_iterations - n)
{
    break if (length(z) > bailout)

    w = w^2 + c
}

pixel_color = based on w

Comment: Very cool visualizations!
Answer: From what you are saying I am unfortunately almost certain that you do not have enough mathematical background to really understand the theory of matings (which is something quite advanced, not realistically understandable before grad school). You typically want to have taken an advanced course in complex analysis, topology, and some background in complex dynamics.
It is difficult to explain shortly the notion of matings, but I'll try to give a quick summary of my own understanding of the topic. An equipotential is a line where the Green function is constant and strictly positive (if you don't know what the Green function is, you need background in complex dynamics). If the Julia set is connected then this equipotential is homeomorphic to a circle. In particular, it splits the sphere into two components, one containing the Julia set and the other containing $\infty$, and each of those components are homeomorphic to a disk. If you take two different connected Julia sets and two such equipotentials, you can glue the components containing the Julia sets by identifying the two equipotentials (if you don't understand this sentence you need background in topology). What you get then is something homeomorphic to a sphere (let's call it $S_1$, and you get a continuous map $f$ defined on $S_1$ that coincides with the restrictions of both polynomials outside of the glueing line. However the range of $f$ is not $S_1$ but rather a similar object obtained by glueing two different equipotentials (the ones that are images of the previous ones by the two polynomials). So you get a continuous map $f: S_1 \to S_2$, where $S_1$ and $S_2$ are topological spaces homeomorphic to spheres.
With some work and a really deep theorem that I won't even try to explain here, called the measurable Riemann mapping theorem, you can somehow get a holomorphic map $g: \hat{\mathbb C} \to \hat{ \mathbb C}$ from this whole business. The map $g$ is conjugated to $f$ by homeomorphisms that map the $S_i$ to the Riemann sphere. However, you shouldn't consider that $g$ is a dynamical system since it is conjugated to $f$, which has different domain and range. But if you used equipotentials $G=t$ for $S_1$, then you used equipotentials $G=dt$ for $S_2$, and as $t \to 0$ the difference between these two equipotentials shrinks to zero. So you want to prove that the map $g_t$ that you get with this whole procedure has a limit when $t \to 0$. This is not true in general, but when it is the case that limit is exactly what's called the mating (in one sense) between the two polynomials.
Comment: Thank you for your reply! I understand now how this is completely beyond my level of education, but let me see if I can do something with what I can learn on my own.

If I understand correctly, I need to be able to calculate both Julia Sets' equipotentials - which, according to https://math.stackexchange.com/questions/3025488, is calculated by $$G(z)=\lim_{d\to\infty}\frac{\log(|f^d(z)|)}{n^d}$$ If the first is $G=t$, then the other is $G=dt$ as $t$ approaches 0 (or is it the difference?). If I got this right, then do all I need to learn is computing these values?
Comment: computing (numerically) the equpotentials will not enable you to make computer pictures. you will still miss that hard step where you map the abstract spheres $S_i$ to the usual Riemann sphere. I don't really understand myself how to generate a computer picture of that step.
Comment: Oh that's not a problem at all, I understand that part of the math: my program does it by taking a point on the Riemann Sphere and projecting it onto the complex plane, using that point to determine the color of its corresponding point on the sphere. It's merely the escape time algorithm with an added step of projecting the plane onto the sphere (see my video that I have linked in the question). As far as I understand, all I need to do is compute the equipotential(s) at some point $z$ on the complex plane, determine some sort of coloring scheme, and then project that point onto the sphere.
Comment: If this is true, then all I have to figure out is how to actually compute the equipotentials - or whatever it is I'm supposed to be computing. I just need to understand how to manipulate the given variables (detailed in my question) at a particular point on the complex plane so I can do the stereographic projections and graphics stuff from my end.
Comment: no, I am not talking about the stereographic projection. I am talking about the mapping from the two glued disks to the Riemann sphere. That mapping is not easily computable, even numerically.
Comment: Forgive me, but I am not understanding what you mean by "abstract spheres" and "glued disks": isn't the mating originally occurring on the complex plane, not a sphere? From what I see, the mating itself requires no spherical mapping at all - or at least, this is what I see in the image on this page: https://www.math.univ-toulouse.fr/~cheritat/MatMovies/RabbitBasilica/
Comment: the plane together with the point $\infty$ is called the Riemann sphere. there isn't much difference between the complex plane and the Riemann sphere. there is however a difference between the Riemann sphere and the spaces $S_i$ from my answer, defined as two disks glued together along their boundaries. it is possible to identify these $S_i$ with the usual complex plane, but that takes work and you need to do this work to reproduce the pictures from your link.
Comment: Sorry about the wait! I edited my question to include the algorithm that worked for me, and I'll be honest I'm still fuzzy on how to practically understand $S_i$ (I conceptually get it), but I'm slowly understanding more and more the more I'm immersing myself in this math so there's still hope!
Answer: The theory is also beyond my level of education, but a practical implementation to make pictures is relatively straight forward following Chapter 5 of Wolf Jung's paper "The Thurston Algorithm for Quadratic Matings" (preprint linked in question).  However, an important thing missing in my code is detecting homotopy violations, so there is no proof that the images are correct.
In my code, the slow mating is computed as per Wolf Jung's chapter 5, pulling back the critical orbits using continuity to choose the sign of the square root.  Pulling back an orbit means the next orbit's $z_n$ depends in some way on the previous orbit's $z_{n+1}$.  The process has a sequence of orbits, where the orbit at time $t+s+1$ depends on the orbits at time $t + s$ (for choosing roots by continuity) and time $t + 1$ (for the input to the square root function).  Increasing the granularity $s$ presumably makes the continuity test more reliable.
To render images, the pull-back in Wolf Jung's paper is inverted to a sequence of functions of the form $z\to\frac{az^2+b}{cz^2+d}$, which are composed in reverse order starting from the desired pixel coordinates. Then choose the hemisphere based on $|z|<1$ or $|z|>1$, find $w=Rz$ or $w=R/z$ and $c=c_1$ or $c=c_2$ depending on hemisphere, and continue to iterate $w→w^2+c$ until escape (or maximum iteration count is reached).
Here is a scrappy diagram of the process that I made, which is how I initially understood how it works.  The top left triangle (green) is computed for the critical orbits, with the aim to calculate the coefficients of the inverse of the bottom diagonal.  Then the red path is computed per pixel.  The subdiagram at the right shows the continuity checking process.

For colouring filaments with distance estimation I use dual complex numbers for automatic differentiation, for colouring interior I use a function of the final $w$ to adjust hue.  To keep images stable for animations, the same number of total iterations is needed for the interior pixels each frame.


Scrapy - NameError: global name 'logger' is not defined

Question: I am trying to modify Scrapy retry a little bit by modifying the middleware. I use this middleware:
class Retry500Middleware(RetryMiddleware):

    def _retry(self, request, reason, spider):
        retries = request.meta.get('retry_times', 0) + 1

        if retries <= self.max_retry_times:
            logger.debug("Retrying %(request)s (failed %(retries)d times): %(reason)s",
                         {'request': request, 'retries': retries, 'reason': reason},
                         extra={'spider': spider})
            retryreq = request.copy()
            retryreq.meta['retry_times'] = retries
            retryreq.meta['download_timeout'] = 600
            retryreq.dont_filter = True
            retryreq.priority = request.priority + self.priority_adjust
            return retryreq
        else:
            logger.error("Gave up retrying %(request)s (failed %(retries)d times): %(reason)s",
                         {'request': request, 'retries': retries, 'reason': reason},
                         extra={'spider': spider})

Then I get this error.
Traceback (most recent call last):
  File "/usr/lib64/python2.7/site-packages/twisted/internet/defer.py", line 1128, in _inlineCallbacks
    result = g.send(result)
  File "/usr/lib/python2.7/site-packages/scrapy/core/downloader/middleware.py", line 53, in process_response
    spider=spider)
  File "/usr/lib/python2.7/site-packages/scrapy/downloadermiddlewares/retry.py", line 54, in process_response
    return self._retry(request, reason, spider) or response
  File "/home/<user_name>/<project_folder>/<project_name>/<project_name>/middlewares.py", line 48, in _retry
    logger.debug("Retrying %(request)s (failed %(retries)d times): %(reason)s",
NameError: global name 'logger' is not defined
2018-08-15 14:01:44 [scrapy.core.engine] INFO: Closing spider (finished)

I used it in my machine and the middleware works just fine. What should I do to avoid this error?
Answer: In the end, I use this code instead
import logging
logging.log(logging.ERROR, "Gave up retrying %(request)s (failed %(retries)d times): %(reason)s",
                         {'request': request, 'retries': retries, 'reason': reason},
                         extra={'spider': spider})

Answer: import logging
logger = logging.getLogger(__name__)

You can either put a self.logger = logging.getLogger(name) in your Generic.init() function, or define a global logger after importing the logging. Refer to this answer :
NameError: global name 'logger' is not defined


How do I create a subnet using the Google Compute Engine cloud console?

Question: I am wanting to create a subnetwork as described here:
https://cloud.google.com/compute/docs/reference/beta/subnetworks
How can I do this using the cloud console?
thanks
Answer: You can follow the steps below to create subnetworks from Developer console:

From Developer console click Networking.
Select Networks from left side.
Click on Create a network.
On this page you can choose between Custom or Automatic subnetworks and the region for these subnetworks.

For more information you can refer to this link.


URL Amigavel não permite acessar a index do site

Question: Olá, tenho a seguinte código no htaccess
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d

RewriteRule (.*) index.php [QSA,L]

Porem quando tento acessar a pagina principal site.com ele diz que não é possível acessar.
index.php

    <?php
        require 'config/tratarUrl.php';
        include $pag;
    ?>

tratarUrl.php
if(file_exists(DIR_PAGES.$url[0].'.php'))
{
    $pag = DIR_PAGES.$url[0].'.php';
}

Comment: é wordpress? acho que essa informação depende de como sua index trabalha para manipular os dados recebidos
Comment: `RewriteRule ^(.*)$ index.php [QSA, L]` começa corrigindo isso.
Comment: @DaniloD Eu uso Xampp para abrir o site.
Answer: acredito que o código a seguir vai funcionar para você
# BEGIN
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.php [L]
</IfModule>
# END

mas lembrando, tudo depende de como sua aplicação trabalha
Comment: Mesmo coisa, quando tento acessar aparece o erro `ERR_TOO_MANY_REDIRECTS`.
Comment: tem como colocar o código da sua index?
Comment: Já editei a pergunta.


Derivation of inverse sine, what is wrong with this reasoning?

Question: I'm trying to find the derivative of $\sin^{-1}(x)$. I know the steps that lead to $\frac{1}{\sqrt{1-x^2}}$, however I don't understand why the following reasoning leads to a wrong answer.
Because
$$\frac{d}{dx}f^{-1}(x) = \frac{1}{f'(f^{-1}(x))} $$
If we plug in for $f(x) = \sin(x)$, and because $\frac{d}{dx}\sin(x) = \cos(x)$ we get
$$\frac{d}{dx}\sin^{-1}(x) = \frac{1}{\cos(\sin^{-1}(x))} $$
Since $\sin(x) = \cos(x-\frac{\pi}{2})$, we can state that $\sin^{-1}(x) = \cos^{-1}(x-\frac{\pi}{2})$. (I suspect this is what is wrong)
Thus,
$$\frac{d}{dx}\sin^{-1}(x) = \frac{1}{\cos(\cos^{-1}(x-\frac{\pi}{2}))}$$
Then, by the definition of inverse function, we have
$$\frac{d}{dx}\sin^{-1}(x) = \frac{1}{x - \frac{\pi}{2}}$$
Comment: In general $\arccos(x-\pi/2)$ is not defined everywhere from$ [-1,1]$ for example at any point in $[-1,0]$.
Comment: You identified the problem : $\cos(\sin^{-1}(x))=\sqrt{1-x^2}$
Comment: @ClaudeLeibovici But how that proves $\sin^{-1}(x) \neq cos^{-1}(x-\frac{\pi}{2})$?
Answer: Actually if we avoid using $f,f^{-1}$ notations, things will become much more clear:
Let $y=\sin^{-1}x: [-1,1] \mapsto [-\frac{\pi}{2},\frac{\pi}{2}]$, so $x=\sin y$. Thus
$$1=\cos y \cdot y'$$
$$y'=\frac{1}{\cos y}$$
But if $x=\sin y$, we have $\sqrt{1-x^2}=\cos y$, because $\cos y \ge0$ for $y \in [-\frac{\pi}{2},\frac{\pi}{2}]$ (Here, in your question, you need to watch the domain and range when you take the inverse to make sure they match; and as a matter of fact, they do not match - but you really do not need to take the inverse)
Thus
$$y'=\frac{1}{\sqrt{1-x^2}}$$
Answer: How does $\sin(x) = \cos(x-\frac{\pi}{2})$, imply $\sin^{-1}(x) = \cos^{-1}(x-\frac{\pi}{2})$.
Set $x=0,\sin^{-1}=0,\cos^{-1}\left(-\dfrac\pi2\right)$ is not real as $-\dfrac\pi2<-1$
Similarly for  $x=\dfrac\pi2$
Comment: In fact, $\sin x=\cos\left\{2m\pi\pm\left(\dfrac\pi2-x\right)\right\}$ where $m$ is any integer.  Also if $f(x)=g(x+h),$ can we say $$f^{-1}(x)=g^{-1}(x+h)$$


Malformed expression :"Error" when trying to retrieve value from hashmap

Question: I am trying to initialise the value of X to be the value of a hashmap.
Using the the IDE debugger , I can clearly see that the key-value of the hashmap has been initialised

However when i hover over the value of "secondcol" , i get the following

I don't understand how it is that the hashmap shows that the value has been initialised however the "secondcol" shows a malformed expression.
Moving on to the next step will cause a Null PointerException Error
What is happening and how do i resolve this issue ??
Comment: Collections must use boxed equivalents of primatives. In your case, the keys of the hash map are of type Integer. The for loop uses primitive ints. Have you tried explicitly boxing i?
Comment: What do you mean by "boxing i"
Comment: I posted something in the answer section to demonstrate boxing.
Answer: From the debugger it looks like the code should be
=CurrentPeerNode.ftable.table.get(i).value.secondcol
and
=CurrentPeerNode.ftable.table.get(i).value.thirdcol.
(You were missing the .value)


What named chord is this?

Question: I'm looking for named chords - we've already identified a couple others (it's part of a puzzle, e.g. Dream chord, Electra chord, etc.)
It goes: A  A#  D  D#  G  A  A(low) and is played in arpeggio form...
Comment: You need to tell us what you mean with "A(low)". Is it a half tone lower? An octave lower? Are the notes ascending or descending?
Answer: In some non-tertian forms of music a "chord" created by a series of the same intervals (such as fourths) is described systematically by the specific interval and the number of pitches used.  This chord would be described as two quartal triads (quartal describing the interval of the fourth and triad because three different notes are used).
These chords are openly inverted and have no real system of usage in terms of common practice.  I am not including the second "A natural" because it is a repeated note most likely for emphasis.  It seem the chord is built on "A" as a root note.
edit: If you reorganize the notes in this chord you wind up with two sets of three perfect fourths (working under the assumption that "A(low)" means Ab).  If both A's are intended to be natural I would posit that this is an Ebmaj7#9 (Eb-G-Bb-D-A)
Comment: Note that #9 in a Eb chord is F#. A would be #11 or #4, and the chord would then be a lydian chord. But having the #11 at the bottom of the chord is a bit strange. On the other hand, this is arpeggiated.
Comment: Interesting. `A - D - G` are a fourth apart, `A# - D#` is a fourth, what would you say about the relation between A and A#?
Comment: @Gauthier I'm going to edit my answer
Comment: I see. But the fact that these sets are half a tone apart should be very relevant, shouldn't it?
Comment: man, I am really failing on this.  I meant to write 11 : )  I suppose the context would help alot with analyzing this chord.
Comment: I'm not sure there is a context, OP says it is a quizz, I guess they get a sequence of tones and must describe what it is. As a chord, this tone sequence is very dissonent. It feels more like a scale, hence my answer.
Comment: Very good option.
Answer: Seems to me that this is a chord built on stacked perfect fourths with added neighbor notes for embellishment.
A to D is a perfect fourth. D to G is a perfect fourth.
The A#, D#, and A/Ab (I'm assuming by low you mean flat) are neighbor notes -- being that they are one half-step higher than their counterparts -- and do not play a role in the actual naming of the chord.
Composers will add neighbor notes and passing notes, which are dissonant to the main chord or harmony, as a way to add embellishment, tension, and interest.
Answer: These tones form the Iwato scale.
http://en.wikipedia.org/wiki/Iwato_scale

The iwato scale is a musical scale that is similar to the Locrian mode
  (spelled 1 b2 b3 4 b5 b6 b7), seventh mode of the major scale,
  different in that it has no 3rd or 6th notes, thus making it
  pentatonic. It spelling is therefore 1 b2 4 b5 b7. It is used in
  traditional Japanese music for the koto.

A scale is not a chord, but since the sequence is played in "arpeggio form", I believe this is relevant.
As a quizz question, I think the probabilty of Iwato being part of the answer is significant.
Answer: Basic triads are one thing, but with more complex chords, in functional haromony, a group of notes can only truly be identified as a chord if they are examined in the context of the chord progression in the musical passage where you find it. There's not much point in trying to give one group of notes a name in isolation. The same group of notes may have different chord names depending on their use in different contexts.
Guitarists tend not to realize this, because guitarists tend to look at a chord as a particular "shape" of fingers on the fretboard, and they want to give one "shape" a name. But composers, music theorists, and other instrumentalists, even piano players, don't think this way.

What named chord is this?


Examples of pictures using notated music

Question: My teacher was talking about a college professor she had that had a picture drawn out that was drawn using music. It was a playable piece but looked complicated. I'd like to see an example and can't find any online
Comment: Hi, welcome.  You will find (in general, not just here) that providing an example of the picture and a detailed description of how the music produced the picture.  For example, I know of "show off" cases where a complicated fourier transform dataset was converted back to sound and the resultant signal, written in spiral format, produced a picture.
Comment: Possible duplicate of [How do you read Graphic Scores?](https://music.stackexchange.com/questions/23725/how-do-you-read-graphic-scores)
Comment: It sounds like you may be talking about some form of [graphical notation](https://en.wikipedia.org/wiki/Graphic_notation_(music)).
Comment: Would piano roll notation a la Synthesia count? Because that's where I've seen the majority of these pictures made out of music.
Answer: I'm not sure this is what you mean, but there is the piece "Ode an das Ruhrgebiet" by Marc Vogler which is a playable piece, but the score sheet depicts the headframe of a coal mine in Essen, Germany. You can see an image on the composer's page. (Larger version).


Copy address bar content to clipboard

Question: How can I copy the contents of the browser's address bar to the user's clipboard using javascript / jquery? I'm trying to make an extension for Chrome and Firefox which adds a hotkey for that.
I figured [F6] was an easy target for the hotkey because it already selects the contents of the address bar in both browsers. So I tried:
(function() {
    $(document).keyup(function(e) {
        // [F6] selects and copies address bar content.
        if (e.keyCode == 117){
            document.execCommand('copy');
        }
    });
})();

However this doesn't copy it. Next I tried to get the url trough window.location.href, but I still have to copy it to the clipboard. So far the methods I found for getting a variable into the clipboard involve adding elements to a page. Seeing as it's for an extension and not a website I would prefer it doesn't modify pages.
I'm new to javascript and extension development so I'm in the dark on how I should go about this. Any help would be much appreciated.
Comment: You can do it inside an event page which is a hidden background page so you won't modify the web page. Use chrome.commands API to declare a hotkey, chrome.tabs API to get the URL, don't use content scripts.
Answer: You can see what is done here : How to copy URL on button click?
Maybe you will need an hidden field to put the url before copying it.

Copy address bar content to clipboard


Uncaught TypeError: Cannot read property 'split' of undefined at XMLHttpRequest.alertContents

Question: Estou fazendo um requisição AJAX, via GET e colocando na variável httpRequest e estou tentando usar um .split(';') na resposta de texto este é um trecho do código que estou usando:
 var prof1 = 0, prof2 = 0,prof3 = 0, prof4 = 0,prof5 = 0, prof6 = 0,prof7 = 0, prof8 = 0,prof9 = 0, prof10 = 0,prof11 = 0, mat1 = 0,mat2 = 0, mat3 = 0, mat4 = 0,mat5 = 0, mat6 = 0, mat7 = 0,mat8 = 0, mat9 = 0, mat10 = 0,mat11 = 0;
    var requestant, requestatual,prof,mat;
    requestant = '';
    window.setInterval(makeRequest, 10000);
    httpRequest = new XMLHttpRequest();
    function makeRequest() {
        httpRequest.open('GET', 'result.php');
        httpRequest.send();
        if (httpRequest.readyState === 4) {
            httpRequest.onreadystatechange = alertContents;
        }
    }
    function alertContents() {
        if (requestant !== requestatual) {
            if (requestatual !== '') {
                if (requestatual !== undefined) {
                    requestatual = httpRequest.responseText;
                    requestatual = requestatual.split(';');
                    prof = requestatual[0].split(',');
                    mat = requestatual[1].split(',');
                    prof1 = prof[0];
                    prof2 = prof[1];
                    prof3 = prof[2];
                    prof4 = prof[3];
                    prof5 = prof[4];
                    prof6 = prof[5];
                    prof7 = prof[6];
                    prof8 = prof[7];
                    prof9 = prof[8];
                    prof10 = prof[9];
                    prof11 = prof[10];
                    mat1 = mat[0];
                    mat2 = mat[1];
                    mat3 = mat[2];
                    mat4 = mat[3];
                    mat5 = mat[4];
                    mat6 = mat[5];
                    mat7 = mat[6];
                    mat8 = mat[7];
                    mat9 = mat[8];
                    mat10 = mat[9];
                    mat11 = mat[10];
                    requestant = requestatual;
                    grafcs();
                }
            }
        }
    }

Erro
Uncaught TypeError: Cannot read property 'split' of undefined at XMLHttpRequest.alertContents

Resposta que a result.php dá
1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , ;0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,

Comment: O que está a obter de `httpRequest.responseText` é `undefined`(indefinido) logo não pode fazer `split`. É melhor colocar o resto do código que está a utilizar para a requisição para se conseguir perceber de onde vem o problema.
Comment: Faz um console.log(typeof requestatual) antes do split e conta pra gente o que obteve no console.
Comment: Não falta a verificação do status 200 => `httpRequest.status == 200` ? E porquê as variáveis todas? Não era mais fácil usar diretamente os arrays `prof` e `mat`?
Comment: já coloquei o js todo
Comment: Não, @Isac, já que o status pode ser 304 (Não modificado)
Answer: Pode ser que:

requestatual pode não ser uma string
requestatual é undefined
httpRequest não está recebendo informações

Obs: Mostre mais código da próxima vez.
Comment: @LeoneCerqueira você chamou o `makeRequests()`?
Comment: eu n tou vendo la @LeoneCerqueira
Comment: ah, ja vi tente `setInterval(function() {makeRequest();}, 10000);`
Comment: não dei um alert() nele está tudo ok
Comment: chamei sim ta la no js
Comment: Tentei, mas não resolveu, porque o problema não está na resposta,nem no loop setInterval e sim no `split`
Comment: @LeoneCerqueira dá um `console.log` no `requestatual`
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/64991/discussion-between-leone-cerqueira-and-pedro-pinto).
Answer: Seu código tem problemas no recebimento do XMLHttpRequest.
Você está verificando o readyState antes de carregar o retorno. O correto seria:
function makeRequest() {
        httpRequest.open('GET', 'result.php');
        httpRequest.send();
        httpRequest.onreadystatechange=function(){ //callback quando o retorno estiver pronto
            if (httpRequest.readyState === 4) { //processo concluído
                requestatual = httpRequest.responseText; // atribuo os dados recebidos à variável
                alertContents(); // chamo a função
            }
        }
    }


Definir TimeZone padrão Golang

Question: Existe alguma forma de definir um TimeZone (Location) padrão no Golang para não precisar ficar setando hora?
Atualmente estou setando manualmente o TimeZone toda vez que eu preciso trabalhar com Time usando isso:
loc, _ := time.LoadLocation("America/Sao_Paulo")
tim := time.Now().In(loc)

Answer: Você pode setar a váriavél time.Local. Segundo a documentação:

var Local *Location = &localLoc

Local represents the system's local time zone. On Unix systems, Local > consults the TZ environment variable to find the time zone to use. No > TZ means use the system default /etc/localtime. TZ="" means use UTC. > TZ="foo" means use file foo in the system timezone directory.

Então você pode usar para mudar o Local.

Por exemplo:
time.Local = time.UTC

Dessa forma ao executar o time.Now() será em UTC.

No caso do America/Sao_Paulo bastaria fazer:
time.Local, _ = time.LoadLocation("America/Sao_Paulo")

Isso pode ser declarado no main() e todas as chamadas subsequentes utilizarão esse fuso-horário.

Se fizer um teste:
func main() {
    fmt.Println("Tempo padrão:", time.Now())

    time.Local = time.UTC
    fmt.Println("Tempo UTC:", time.Now())
    fmt.Println("Tempo UTC:", time.Now())

    time.Local, _ = time.LoadLocation("America/Sao_Paulo")
    fmt.Println("Tempo SP:", time.Now())
    fmt.Println("Tempo SP:", time.Now())
}

Resultado:
Tempo padrão: 2021-06-17 15:28:04.5675042 +0100 BST m=+0.092369601
Tempo UTC: 2021-06-17 14:28:04.5844768 +0000 UTC m=+0.109342201
Tempo UTC: 2021-06-17 14:28:04.5844768 +0000 UTC m=+0.109342201
Tempo SP: 2021-06-17 11:28:04.5844768 -0300 -03 m=+0.109342201
Tempo SP: 2021-06-17 11:28:04.5844768 -0300 -03 m=+0.109342201

Comment: Sempre existiu, ao menos desde do Go 1.0.1, lá de ~2012. Pode ver o código fonte em https://go.googlesource.com/go/+/refs/tags/go1.0.1/src/pkg/time/zoneinfo.go#57.
Comment: Essa solução é perfeita porque é multiplataforma! A solução usando a variavel de sistema TZ, igual citada nas respostas abaixo só funciona em ambiente linux.
Comment: Show de bola! Funcionou perfeitamente! Sabe me dizer se sempre existiu essa varíavel? Porque anos atras quando eu pesquisei não achei nada.
Comment: Entendi. Estranho que quando eu pesquisei não achei isso em lugar nenhum, e eu pesquisei muito, muito mesmo, ai como não achei nada na época acabei criando uma função que inicializa um novo time.time no timezone que eu quero. Mas esse jeito ai é mais simples e é nativo do GO. Muito obrigado novamente.
Answer: Você pode criar um package em separado setando esta configuração e importá-lo nos locais em que precisar, por exemplo:
package tzinit

import (
    "os"
)

func init() {
    os.Setenv("TZ", "America/Sao_Paulo")
}

Importando configuração
package main
import _ "path_pacote/tzinit"

import (
    "fmt"
    "math"
    //mais algum outro pacote
)

Espero ter ajudado !
Comment: Já tinha visto esta resposta em outros tópicos e ela simplesmente não funciona. Já havia feito alguns testes com ela e não funciona.
Caso quiser testar você pode usar o seguinte trecho de código: https://play.golang.org/p/-RnSNe2HVY2
Comment: Depois de alguns anos eu descobri que essa solução de setar a variavel de ambiente TZ só funciona em ambientes linux/unix, em ambiente Windows não. Nesse caso é só usar time.Local = time.UTC
Answer: É necessário utilizar a função time.Now().In()
loc, _ := time.LoadLocation("America/Sao_Paulo")
// handle err
currentTime := time.Now().In(loc)

// outra forma de fazer o exemplo acima
loc, _ := time.LoadLocation("America/Sao_Paulo")
currentTime := time.Now()
currentTime.In(loc)

Exemplo no Go Playground
Comment: Isso não define um timezone padrão para todas as datas que é oque eu quero. Isso vai definir um padrão para a minha variavel atual do time.
Answer: Seta direto na máquina, então o time.Now() vem com a timezone certo.
Exemplo de Dockerfile:
FROM alpine:latest
RUN apk add --no-cache tzdata
ENV TZ=America/Sao_Paulo
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

Comment: É uma boa alternativa, daria pra ver pra setar esses ENV pelo GO, porque nem todo mundo usa Docker, mas é uma ótima ideia setar ENV. Alias, você testou ver se isso funciona?
Comment: Setando essa timezone na máquina do servidor tem o mesmo resultado, caso não use docker.

Definir TimeZone padrão Golang


Preciso mudar o nome desse campo 'Biblioteca01' para uma palavra de no máximo 10 caracteres, exemplo: 'BIBILIOT01'

Question: Porém por conta do WHEN S.codSala LIKE 'B%', não aceita.
inserir a descrição da imagem aqui
CASE
WHEN S.codSala LIKE 'A%' OR S.codSala LIKE 'B%' OR S.codSala LIKE 'C%' OR S.codSala LIKE 'D%' OR S.codSala LIKE 'E%'OR S.codSala LIKE 'F%' OR S.codSala LIKE 'G%'
THEN S.codSala
WHEN S.codSala = '%Biblioteca01%' THEN 'BIBLIOT1'

ELSE ''
END AS CODSALA,
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: Você precisa usar outro CASE depois do THEN e podes validar da mesma forma que tentou, mas recomendo algo mais genérico, por exemplo:
CASE WHEN S.codSala LIKE 'A%' OR S.codSala LIKE 'B%' OR S.codSala LIKE 'C%' OR S.codSala LIKE 'D%' OR S.codSala LIKE 'E%'OR S.codSala LIKE 'F%' OR S.codSala LIKE 'G%' THEN
    CASE WHEN (LEN(S.codSala) > 10) THEN
        LEFT(S.codSala, 8) + RIGHT(S.codSala, 2)
    ELSE
        S.codSala
    END
ELSE
    ''
END AS CODSALA

Comment: Valeu cara, deu certo!


How to apply patches that are created in core-dev

Question: Noob here. I'm trying to apply patches to my website, but it's keeps skipping because the version of the patch is for DEV. For example, I want to apply a patch to Core like this issue: https://www.drupal.org/project/drupal/issues/2579343.
How should I apply patches that are in core-dev?
Thanks!
Answer: If the patch weren't already committed, you would need to reroll the desired patch against your Drupal Core version. This can be done by cloning the git repository of Drupal Core and generating a patch against the relevant revision of your version of Drupal.
The Drupal Core git repository can be found at https://www.drupal.org/project/drupal/git-instructions
See Making a patch on how to create a patch.
However in this case we can see that the issue has already been marked as "Fixed" and the patch of comment #19 was committed, so if you are on Drupal Core 8.1.x or up, you should already have the changes from that patch on your Drupal site.
Comment: Thanks for your help Baikho. I guess I'm still having issues rolling back my d7_fields. I'm using D8.9.11 right now. Thanks for your help. Going to make a new post on how to add a new value in value list.