Can lowered second degrees be used when switching music from major to minor even though they aren't actually part of the minor scale?

Question: What I noticed in some songs is the second degrees of the scale rarely get turned into lowered second degrees when switching music from major to minor by lowering the third, sixth and seventh degrees. But normally, the second scale degrees aren't lowered when switching music from major to minor by lowering the third, sixth and seventh degrees because the lowered seconds aren't even part of the Aeolian mode which it equals to the natural minor scale.
Example: A song in B♭ major would use the notes "B♭CDE♭FGA" but when switched to B♭ minor by lowering the D, G and A notes, the notes would become "B♭CD♭E♭FG♭A♭". Normally the C notes would remain the same when switching a song from B♭ major to B♭ minor since the C flats are not even part of the B♭ Aeolian mode which equals to the B♭ natural minor scale. But in rare cases, the C would become C♭ in certain parts of some songs.
Example: The piano song called Frankie and Johnnie from the Alfred's Adult Piano Course Level 2 book is in the key of B♭ major but has some E♭ major notes in it which that has a similar melody to the main melody of the actual key of the song which is B♭ major. If the song was played in B♭ minor, the C notes which are second scale degrees in the B♭ minor scale could be flattened for the E♭ major parts of the Frankie and Johnnie piano song just like how the G notes are flattened in the main melody of Frankie in Johnnie but in B♭ minor.
I understand that lowering all or most of the second degrees of the song in minor key would make it Phrygian, but lowering just a few second degrees of the song in minor key wouldn't necessarily make it a song in Phrygian mode. So it makes me wonder if the lowered second degrees can be used when switching music from major key to minor key despite the lowered second degrees are not actually part of the minor keys.
Comment: I think what you're asking about is a lowered second scale degree when changing modes, does that seem right? I'm afraid I'm a bit confused by the question. To me a minor second is an interval of a half step and both major scales and minor scales have two minor seconds per octave.
Comment: You can probably get this reopened if you post the actual rare case you were dealing with.
Comment: I don't understand *when* or *why* you'd be "transposing" from major to minor.
Comment: Usually "major second" and "minor second" refer to intervals, not scale degrees. I think you might want to edit your question to replace "minor second" with "lowered second degree". Otherwise this question is really hard to understand.
Comment: Also it would help to add some kind of example. It's not clear what you mean by "transposing major to minor". Do you mean a change of mode to the parallel minor? Or a modulation from a major key to a close or distant minor key? Maybe if you actually pick two keys to discuss, like writing "let's say I wanted to modulate from C major to Eb minor, would I put in a Db somewhere before the modulation?"
Comment: @ToddWilcox and the harmonic minor scale has three.
Comment: False premises - Aeolian is only one of three sets of notes which constitute 'minor' - and that's before minor modes are considered. And isn't ^2>^3 M2 in major, always going to m2 in minor? Otherwise it wouldn't work.
Comment: @ToddWilcox I was talking about if the lowered second degree can be used when transposing music from major to minor even though it's not actually part of the minor scale since I noticed in some songs is the major seconds rarely get turned into minor seconds when transposing music from major to minor.
Comment: "...But in rare cases..." Post the example you're talking about. It's too hard to know what you're thinking, but I suspect it might be part of a modulation in the piece, some kind of move toward the subdominant, which one thing that lowering the second degree in minor means.
Comment: Are you trying to analyze a particular use of a lowered second scale degree?  It would commonly occur when modulating to some tonality other than the parallel minor, for example to A-flat major or F minor in C major, but it could also occur in a particularly chromatic passage in the parallel minor.  It could even occur in a chromatic passage in the major key, although in that case you would more likely see a raised tonic than a lowered supertonic (that is, C sharp rather than D flat in C major).
Answer: Yes, the lowered/flattened second scale degree can be used when "transposing"/shifting music from a major key to a minor key, but it may sound weird.
"Transposing"/shifting music from a major key to its relative minor is common in classical music, especially minor-key sonata-allegros. While flattening the supertonic a.k.a. the second scale degree in the minor-key version is rare in such sonata-allegros, it has been done, although it often involves a "transposition" that is significantly less than perfect (e.g. something other than the second scale degree is replaced with the lowered second scale degree).
Take these two examples from classical music:
Piano Sonata No. 8 in C Minor, Op. 13 "Pathetique" by Ludwig van Beethoven, 1st movement (recording)
Recapitulation, shifted to C minor from E flat major (starts in 5:35 of recording):

Original (in exposition), in E flat major (starts in 2:40 of recording, top staff uses treble clef):

Keyboard Sonata in E minor, Hob.XVI:34 by Joseph Haydn, 1st movement (recording)
Recapitulation, shifted to E minor from G major (starts in 3:21 of recording):

Original (in exposition), in G major (starts in 0:46 of recording, top staff uses treble clef):

In both of these cases, the flattened supertonic is harmonized with a chord that emphasizes how foreign that note is to the base minor key, such as vii°4/3 of iv (for the Beethoven) and ♭II6 a.k.a. the Neapolitan (for the Haydn).
Flattening the supertonic when "transposing"/shifting music from a major to a minor key just might be more common in video game music, although it can have a strange and pointed effect again, and it still can often involve "transpositions" that are significantly less than perfect. Take these 2 examples from the Kirby series:
Kirby: Triple Deluxe

Minor-key version with lowered 2nd scale degree: "The World to Win", final boss theme involving automatic power-up (first use of lowered 2nd scale degree is at 0:14)
Major-key original: "Hypernova
Inhale", theme of said power-up (equivalent is at 0:05)

Kirby and the Forgotten Land

Minor-key version with lowered 2nd scale degree: "Morpho Knight", cutscene and boss theme (first relevant use of lowered 2nd scale degree is at 1:14, "transposition" notably sometimes retains raised 3rd scale degree)
Minor-key version without lowered 2nd scale degree for comparison: "The Beast Pack's Final Stand", late-game stage theme (equivalent starts at 1:45, more minor-key "transposition"s start earlier)
Major-key original: "Ready to Go", title theme (equivalent starts at 0:44, this "original" actually picked for convenience due to sharing a tonic with both minor-key versions above)

Note that all the minor-key examples with the lowered 2nd scale degree are for boss themes (where the higher tension the lowered 2nd scale degree provides may be more appropriate), with "Morpho Knight" in particular using the lowered 2nd scale degree earlier in the theme and its "tranposition" using the lowered 2nd scale degree likely to remain consistent with that earlier trend.
Comment: The Haydn example does have the lowered ^2 sound, it's a N6 chord.
Comment: In the Beethoven example is makes much more sense to call that Db `FA` - scale degree ^4 - relative to the Ab chord, not a lowered RE, ^2, because it is functioning as FA resolving to MI.
Answer: 'Transpose' is the wrong term for a mode change.  But we can let that pass.
If you're submitting an exercise in theory class, and the brief is 'transform this major key piece to minor', you would be well advised to leave diatonic 2nd degrees of the scale unchanged.
If you're composing music, with no imposed restrictions, you can do what you like. An occasional flattened 2nd degree may well be effective.  But when you use one you won't be transforming major to minor any more, you'll be transforming major to Phrygian, if only momentarily.


Regression with "unidirectional" noise

Question: I would like to learn a function $f: \mathbb{R}^n \rightarrow \mathbb{R}$ from data $(x_i, y_i)$ where $y_i = f(x_i) + \epsilon_i$. $\epsilon_i$ can be seen as observation noise; however, it is always smaller or equal to 0 ($\epsilon_i \leq 0$), i.e., the observations are always a lower bound on the true function value. Are there any regression approaches particularly suited for this setting? Is it required to make specific assumptions regarding the distribution of $\epsilon_i$?
Comment: Do you have multiple replicates at each observed level of $x_i$?
Comment: Do you know the form of $f(x)$? Can $\epsilon$ get close to $0$?
Comment: I don't know the specific form of $f(x)$. $\epsilon$ might get close to (or even become) $0$. Typically, I would not have multiple replicates at each observed level of $x_i$.
Answer: This set up is equivalent to the Deterministic (Efficiency/Productivity) Frontier Analysis in Econometrics, where the econometrician is trying to measure how far a firm/unit of production is from full-efficiency in the utilization of production factors. The $f(x)$ function is the full-efficiency production function (i.e. it gives maximum output given technology and inputs $x$, the "production frontier") and the error embodies a measurement of the distance of actual output from the theoretical maximum,
$$q_i = f(x_i) + \epsilon_i,\;\; \epsilon_i\le 0$$
This model has been largely abandoned, because in it, one of the regularity conditions for maximum likelihood estimation is violated: since $\epsilon_i\le 0$ we have always
$$q_i \le f(x_i)$$
which makes the range (i.e. the support) of the random variable $q_i$ (actual production) dependent on the parameters to be estimated (that are included in $f(x_i)$). Then the standard asymptotic properties of maximum likelihood estimators cannot be invoked, i.e. it is unknown whether they hold or not.
So it has been replaced by the Stochastic Frontier framework, where alongside the one-sided error-term, a zero-mean symmetric disturbance (usually assumed normal) is added (that represents chance effects on the output of the firm that are not related to the "internal efficiency" of the firm):
$$q_i = f(x_i) + u_i+\epsilon_i,\;\; E(u_i\mid x_i) = 0,\;\;\epsilon_i\le 0$$
which deals with the issue mentioned above (and it is after all, more realistic also). Can you augment your model also, by adding a symmetric zero-mean error? Then the machinery of ML estimation is already in place in the Stochastic Frontier literature, with more than one stochastic specifications worked out.
Comment: I didn't know the Stochastic Frontier framework. Sounds promising. I will give it a try. Thanks!
Comment: I tried implementing a simplified version of this using pymc but did not succeed yet. I posted a follow-up question on this under https://stackoverflow.com/questions/22194587/regression-with-unidirectional-noise
Comment: I am afraid I cannot help you with code. Stochastic frontier models are almost always estimated by Maximum Likelihood, after making a distributional assumption. The symmetric error term is assumed always normal, and the asymmetric error term is assumed, half-normal, exponential, or gamma. The density of the composite error  has been derived for these cases (in the case of a half-normal it is  a skew normal density), and researchers implement them directly in the context of ML estimation.
Comment: Right, I will probably implement the ML estimation myself. Thanks for your answer!

Regression with "unidirectional" noise


Memory adjustments for magento with php5-fpm , Nginx, APC, Mysql

Question: I am using magento with php5-fpm , Nginx, APC, and Varnish. When there is varnish hit, the load time is very good. But on varnish miss, the site takes toomuch time to load. I have seen through htop that CPU goes under a lot of load and Ram and swap become full.
I have a core2duo with 512mb Ram. I think there should be some memory issues. Please suugest me how should i configure the different parameters of php5-fpm, nginx, APC, Mysql.
Answer: Before tweaking php-fpm or nginx parameters, you need to check /etc/default/varnish file and see how much memory you have assigned to varnish (considering you have configured varnish to use malloc which uses RAM to store cached data.
you have 512MB of RAM, so you need to set that value accordingly. It should not be on higher side.
Also make sure that your server is not swapping, if it does, then please increase your RAM.
Two more things to check.
1. check /etc/nginx/nginx.conf for worker_process  it should be 1 if you have a single CPU.

check /var/log/php-fpm.log and make sure php-fpm is not running out of resources.
Comment: I have a core2duo(4CPUs), so i have set worker processes to 4, I have seen in php-fpm log this a lot "server reached pm.max_children setting (7), consider raising it".
Comment: I have  malloc,256m in varnish. Is it fine?
Answer: I am not sure if you have four CPU's. you can check cat /proc/cpuinfo for that.
the nginx worker_process should be set one less than the no of processors on your machine. So if you have two cpu's set it to 1.
each worker_process can handle the no of connections mentioned in the worker_connections that should be 1024 by default.
So max cleints that a nginx web server can handle is = worker_process * worker_connections. Also keep in mind the keep alive connections if you have enabled that in nginx.
So from my point of view nginx is not problematic here.
You should read carefully the max_children and parent processes that should be forked by php-fpm according to your server CPU/RAM.  then set it accordingly in php-fpm.conf
If you have set 256M in varnish that means you are only left with 256M of RAM on server for other server tasks, which is very less.
You can set varnish's cache to file system instead of RAM. the performance won't be that bad but you will save your RAM on this.
Try this and see how it works.


Match multiple lines between asterisks

Question: I am taking notes in an outline format that looks like this:
* Micro topic 1
** Microbes are small
** You can't see them!
*** Isn't that something?
* Micro topic 2
** I hope I like the teacher
*** She will be great!
** Micro is cool!

and want a regular expression that matches
* Micro topic 1
** Microbes are small
** You can't see them!
*** Isn't that something?

and
* Micro topic 2
** I hope I like the teacher
*** She will be great!
** Micro is cool!

so it would match from a line beginning with exactly one * up until (not including) a line beginning with exactly one *.
What I have so far:  (?<!.)\*\s.+\n\*+.+\n\*+.+\n\*+.+
But I need it to be dynamic.  The number of lines between each line beginning with a single * will not be consistent, and the text between them will not be consistent.
Comment: Looks a lot like org-mode. Perhaps they can help you find an answer over at http://emacs.stackexchange.com
Answer: Assuming regex in Python, the following should work if you looking for results of named group b. Note that in Python, ?P represents the named group b.
(?P\* ((?!\n\* ).)+)

You can see the test results at https://regex101.com/r/jU1gX0/1

Match multiple lines between asterisks


Will publish profile work for setting EnvironmentName if not publishing to IIS?

Question: I use this same method to set the eonvironmentname for a web app that I publish to a folder.  However, when publishing a .net core console app that is using IWebhostBuilder, the environmentname isnt seeming to get updated?
I have a .net core console app that I am publishing to a folder location and the console app uses IWebhostBuilder, hence I need to be able to set the environment name prior to publishing.  It seems to want to grab the default appsettings, rather than the one for my target environment (Dev).  I have a appsettings.Dev.json file

My publish profile looks like this
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <PublishProtocol>FileSystem</PublishProtocol>
    <Configuration>Dev</Configuration>
    <Platform>Any CPU</Platform>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <PublishDir>\\dev-server1\d$\Services\BoxService</PublishDir>
    <SelfContained>false</SelfContained>
    <_IsPortable>true</_IsPortable>
    <EnvironmentName>Dev</EnvironmentName>
    <RuntimeIdentifier>win-x64</RuntimeIdentifier>
  </PropertyGroup>
</Project>

[ Edit ]
Nothing was working, so I did an experiment because obviously I am missing something or just dont understand.  I created a new test console app with nothing in it except one class with a Main method.  Added the necessary packages (Extensions.Configuration etc), then proceeded to publish the app to a local folder with the following in my publishprofile.
<EnvironmentName>Local</EnvironmentName>

This is obviously not being used, because when I run it from visual studio, it reports the correct environment has been set, but when run from the published folder, its as if the environment has not been set.
Here is Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.EnvironmentVariables;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace Cmd1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var environmentName =
                Environment.GetEnvironmentVariable("ENVIRONMENT");

            // create service collection
            var services = new ServiceCollection();

            // build config
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", false)
                .AddJsonFile($"appsettings.{environmentName}.json", true)
                .AddEnvironmentVariables()
                .Build();

            // setup config
            services.AddOptions();
            services.Configure<AppSettings>(configuration.GetSection("App"));

            // create service provider
            var serviceProvider = services.BuildServiceProvider();

            var appSettings = serviceProvider.GetService<IOptions<AppSettings>>();

            string env = Environment.GetEnvironmentVariable("Environment");

            Console.WriteLine($" We are looking at {appSettings.Value.TempDirectory} from environment: {env}");
        }
    }
}

Appsettings.json
{
  "App": {
    "TempDirectory": "d:\temp"
  }
}

Appsettings.Local.json
{
  "App": {
    "TempDirectory": "c:\\temp\\rss-hero\\tmp\\"
  }
}

Setting Environment in VS

Results, from VS

Results when run from published folder
Comment: After the publish open Powershell in publish dir. Run `$Env:ENVIRONMENT = "Development"` and then start the application using `dotnet .\appName.dll`. Your application will use the specified env you specified earlier in the command.
Answer: You need to configure IWebhostBuilder like this
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .ConfigureAppConfiguration(builder =>
    {
        builder.AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.Dev.json", optional: true) // add more if you have
            .AddEnvironmentVariables();
    });

Then depending on the environment it will use appsettings{envrionment}.json. If no other present it will use appsettings.json (default). After publishing you can check the web.config to check the environment name it's using.
EDIT
For console app you do something like this
private static IConfigurationBuilder Configure(IConfigurationBuilder config, string environmentName)
    {
        return config
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables();
    }

And use like this (.Net core generic host)
Host.CreateDefaultBuilder(args)
.ConfigureHostConfiguration(builder =>
{
    Configure(builder, "Dev");
})
.UseConsoleLifetime()

Or if you want to get the environment from System environment variables.
public static IConfiguration CreateConfiguration()
    {
        var env = new HostingEnvironment
        {
            EnvironmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"),
            ApplicationName = AppDomain.CurrentDomain.FriendlyName,
            ContentRootPath = AppDomain.CurrentDomain.BaseDirectory,
            ContentRootFileProvider = new PhysicalFileProvider(AppDomain.CurrentDomain.BaseDirectory)
        };

        var config = new ConfigurationBuilder();
        var configured = Configure(config, env);
        return configured.Build();
    }

Comment: But I am not building a web app.  This is for a console app.  Im building a windows service. Hence, there will be no web.config
Comment: Then you can use `EnvironmentName` like [this](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-3.0#environmentname). And you should switch to generic host.
Comment: Yes, I am doing those things, but still wasnt working (although Im using webhostbuilder).  See update in orginal post


Grouping galleries with Colorbox modules

Question: Since two days that i'm looking around to find a easy and simple gallery for Drupal 7.32 and it seems much more complicated that how should be.
I think Colorbox is exactly what i'm looking for but I cannot find a good tutorial or resource that explain how to create a page with thumbnails that groups different galleries.
So when click on them I should go in another page and see all those thumbs from one specific gallery and be able to click on that and see them as slideshow.
More or less like here:
http://www.hopkinsco.com/portfolio
Can you please point me in the right direction?
Of course if you want to suggest another module or method is fine as well.
Comment: I achieve exactly what you want. Let me the time to explain my process in an answer ;-)
Comment: It will be awesome! Take your time :)
Comment: Welcome to Drupal Answers! Please note we don't accept questions whose topic is "Implementing a functionality, or a layout seen in a site, for which only a screenshot or a site URL is provided."
Answer: The content-type "gallery"
First of all, I created a content-type "gallery" which has several fields of my choice and a field "image" with illimited number of images.
The View
If I don't want something too specific, I use the Views module to create a View of all my galleries. I hope you already know that module. If not, go read the basics.

Choose content of type gallery
Set the title and the path of the page, etc...

You can choose which fields to show. If you want something like the site you linked in your question, you can use this configuration:

Format: grid (with number of columns to 4)
Fields:

Title
Image

Image style to thumbnail or whatever you created
Link to content (to land on gallery page when you click on the image)
Multiple value fields settings: display 1

Normally, you have now the equivalent of http://www.hopkinsco.com/portfolio when you open your View page.
The gallery page
The page of the content-type gallery displays all the fields you created for this content-type, in the order you arranged them in the admin. If you want something simple with the Colorbox module, you can go to admin/content-types/gallery/manage display and set the image field config like this (sorry for the french):

Then go click on the little gear on the right to set the advanced config:

Now you've got the equivalent of http://www.hopkinsco.com/portfolio/colonial.
The template and/or the style
Now that you've got the right content in the right place, you can customize the rendering with a little template and/or CSS.
Comment: Yeyyy!!! It works great!! :D Thank you very much, you save me a lot of headache :)
Comment: My pleasure :-)
Comment: Is there a way I can link to a specific display of a content type (not the standard, full content display)?


Equivalence statement for a metric space; Munkres chapter 35 question 3

Question: In Munkres's Topology is the following question:
Let $X$ be a metric space, the following are equivalent:

$X$ is bounded under every metric that gives the topology of $X$.
Every continuous function $\phi: X \to \mathbb{R}$ is bounded.
$X$ is limit point compact.

I need help proving 2. using 1.
The clue he gives is that if $\phi: X \to \mathbb{R}$ is continuous then $x \mapsto (x,\phi(x))$ is an imbedding.
But the image $\phi(X)$ may not necessarily bounded, can you give me a hint for this?
For 2 implies 3:
Let $A \subset X$ be infinite without a limit point.
$\forall a \in A$ $\exists a \in U$ open in $X$ s.t $U \cap A = \{a\}$. Hence $A$ has the discrete topology as a subspace. Then any surjection $\phi$ from $A$ onto $\mathbb{N}$ is continuous. Define $j \circ \phi: A \to \mathbb{R}$ with $j$ the inclusion map, it is continuous and hence bounded by 2 in  contradiction to it being onto $\mathbb{N}$.
For 3 implies 1:
In a metric space $X$ being limit point compact is saying $X$ is compact, and so bounded.
Comment: Let $d$ be one of the metric of $X$. Try to prove that $d_{\phi} (x,y) = d(x,y) + |\phi(x) - \phi(y)|$ is also a metric on $X$ with the same topology as $d$ by using the continuity of $\phi$.
Comment: @Youem I've seen this on the web; was kind of hoping to use the clue he gives, because to prove that that metric is equivalent requires a bit more than my course covers.
Comment: Okay. But how do you want to use the hypothesis of a metric gives the same topology of $X$ ?
Comment: @Mariah Here's a slight varient on Youem's comment which I think might be more to your liking.  Using the clue, we have an embedding $X\to X\times \mathbb R$, and since the product of two metric spaces is a metric space, the embedding gives us a new metric on $X$.  Because the new metric is bounded, $f$ must have been bounded.
Answer: That 3. implies 1. can be more direct: Suppose that $X$ is limit point compact but unbounded in a compatible metric $(X,d)$.
Then there is for any $x_0 \in X$ a sequence $(x_n)_n \subseteq X$ such that $d(x_0,x_n) > n$ for all $n$, as $X \nsubseteq B(x_0, n)$.
This set $\{x_n: n \in \mathbb{N} \}$ has a limit point $p$, which implies (in a metric space) that any $B(p, r)$, $r>0$ contains infinitely many $x_n$. Take $r=1$ and see that this is impossible, as $d(x_n, x_m) < 2$ infinitely many times...
We do not need limit point compactness implies compactness. (this exercise could be seen as a step toward the proof of this fact).
1 implies 2: Indeed if $\phi: X \to \mathbb{R}$ is continuous then $F(x) = (x,\phi(x)): X \to X \times \mathbb{R}$ is an embedding: the family $\{1_X, \phi\}$ separates points and points and closed sets, using a standard theorem (34.2 in Munkres).
This means that the product metric restriced to $F[X]$ i.e.
$$d_\phi(x,x') = d(x,x') + |\phi(x) - \phi(x')|$$ is an equivalent metric for $(X,d)$ as well. (this can also be shown directly). As $d_\phi$ is bounded by 1., so must $\phi$ be. So 2. follows
Answer: Your "For 2 implies 3" is wrong.
First, your notation like $\forall a \in A \exists a \in U$ does not make sense. Also, it is certainly not true that $A$ has the discrete topology as a subspace of $X$. (You could be given $A = X$.)
What you must have meant is that we pick a sequence of different points $\{a_n\}$ from $A$. The set $\{a_n\}$ has the discrete topology and you rename this set as $A$.
Further, $\phi: A \rightarrow \mathbb{N}$ with $f(a_n) = n$ is continuous.
So far so good.
However, your $j \circ \phi$ is continuous as a function on $A$, not as a function on $X$. You need to use the Tietze extension theorem to extend it to a function $ X \rightarrow \mathbb{R} $ to get the desired contradiction.


Submit Text Type Field OnChange

Question: I'm trying to submit a form upon changing of a text field in HTML. Currently, my code looks something like this:
echo("<form name=\"editAgendaItem" . $this->Id . "\" id=\"editAgendaItem" . $this->Id . "\" method=\"post\" action=\"./?module=meetings&preload=edit&function=editAgendaItem&agendaitem=" . $this->Id . "\">\n");
echo("
\n");
echo("
" . $this->Index . "	<input type=\"text\" value=\"" . $this->Title . "\" name=\"agendaItemTitle" . $this->Id . "\" onChange=\"javascript:document.forms['editAgendaItem" . $this->Id . "'].submit();\" />");
echo("	\n");
...

Which evaluates to
<form name="editAgendaItem19" id="editAgendaItem19" method="post" action="./?module=meetings&preload=edit&function=editAgendaItem&agendaitem=19">

1	<input type="text" value="" name="agendaItemTitle19" onChange="javascript:document.forms['editAgendaItem19'].submit()" />
...

But more importantly
<form name="editAgendaItem19" id="editAgendaItem19" method="post" action="...">
<input type="text" value="" name="agendaItemTitle19" onChange="javascript:document.forms['editAgendaItem19'].submit()" />
...

Which is eventually terminated by a  tag. My problem is that upon modifying the field and dropping focus, the form does not submit.

Thanks in advance for any help.
Edit:
I've also tried using this method in the onChange event instead of in-line code:

Edit:
Took the suggestion to use the following code:

In my head, and
<form name="editAgendaItem24" id="editAgendaItem24" method="post" action="...">
<input type="text" value="" name="agendaItemTitle24" id="agendaItemTitle24" />
</form>

In my content. Still no dice.
Comment: No, I'm octern. That's why "- octern" shows up at the end of my comments.
Comment: Are you getting any errors or warnings in your javascript console? If so, could you post them here?
Answer: Try this:
onkeyup="javascript:document.forms['editAgendaItem19'].submit()"

the onChange function only works if you remove focus by clicking somewhere else
Comment: That's the intention Snag - I wouldn't want to submit every time a user hits a key; as this would make entering an agenda item title like 'Call to Order' a two minute process; but thank you for the suggestion.
Answer: Your HTML could be like this:
<form name="myForm" id="myForm" method="post" action="...">
<input type="text" value="" name="myInput" id="myInput"/>

Now use jQuery:

This is my jsFiddle: http://jsfiddle.net/mtwLf/1/
Comment: You are correct @Mohammed Saberi; but for some reason when I flip this over to my page it doesn't apply. I'll post another edit to my main post with what I'm trying. Thanks for your help.
Comment: I'll give this a try and post back. Thanks.
Comment: Gave this a spin - didn't yield any results. Form doesn't submit.
Comment: You are wrong @DigitalJedi805; Take a look at the jsFiddle link carefully. Put your cursor in textbox and then, go out. The form will try to go to the action
Answer: Try to use onBlur event instead onChange
Comment: Thanks for the suggestion; may try this if the above doesn't work.
Answer: I'd really start by breaking out that javascript into a separate file and doing it on/after document ready. I think ive seen people say that its a bad thing nowadays to write inline javascript.
Anyone have any thoughts on that?
Comment: Well I have a submitForm method that is supposed to do this as well; but it doesn't actually send the form either. I'll edit the code above to show it.

Submit Text Type Field OnChange


Which database schema should I use?

Question: I want to create a custom voting module to learn how to write a module. The vote table will contain four fields (id, title, vote_up, vote_down).
Should I create a new table? If I create a new database table, how do I keep the relationship with the node being voted?
Answer: If you want to create a voting module you should look into Voting API, it's an API module that offers common functions and database storage for voting modules to use.
However, since this is a learning excercise, you might want to do it all yourself, in this case:

Use hook_schema() to define your database schema (the example on the documentation page is pretty self-explanatory!)
In Drupal 6 you need to manually specify which schema to install so implement hook_install() and hook_uninstall():

<code>function mymodule_install() {
  drupal_install_schema('mymodule');
}

function mymodule_uninstall() {
  drupal_uninstall_schema('mymodule');
}
</code>
An example of a hook_schema might look like this:
<code>/**
 * Implementation of hook_schema()
 */
  function mymodule_schema() {
    $schema['mymodule_votes'] = array(
      'description' => 'Your schema',
      'fields' => array(
        'vid' => array(
          'description' => 'vote id',
          'type'        => 'serial',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
        ),
        'nid' => array(
          'description' => 'node id',
          'type'        => 'int',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
        ),
        'vote_up' => array(
          'description' => 'number of votes up',
          'type'        => 'int',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
          'default'     => 0
        ),
        'vote_down' => array(
          'description' => 'number of votes down',
          'type'        => 'int',
          'unsigned'    => TRUE,
          'not null'    => TRUE,
          'default'     => 0
        ),
      ),
      'primary key'     => array('vid'),
      'indexes'         => array('node id' => array('nid'))
    );
    return $schema;
  }
</code>
Comment: thanks for your answer! i want to do it all myself. if i create three fields(ID, vote_up, vote_down), how to make a relationship with the node id?
Comment: i don't want to use voting api. in my module i only use.eg:$row['votes_up'] - $row['votes_down'];
Comment: I would create an extra (indexed) field in your schema for the node id :)
Comment: could you write down the  hook_schema() part on you answer, many thanks. i only want the vote module can vote up/down to the node article.
Comment: there you go :)
Answer: Examples has a NodeAPI example that implements a five-star vote on nodes.
For a D7 version, you'd want to deal with entities instead, but it's a working example of how you might set up a schema for voting, based on your needs.

Which database schema should I use?


how to change views output

Question: I need to create a block with eg the latest comments on the site.
when using views, concegui select the data I wanted, but the problem is that I need to edit the output of view (specify the html). I tried to make a tpl, but the fields when they get to this, are already formatted ([#markup]). also tried to make a block programmatically by accessing the fields of view, via <code>$comments = views_get_view('last_opinions');</code>, but so the fields do not bring content, but for example, ids (for referrals), or integers (in the case of dates), ....
basically, how to change views output?
Answer: Views out but can be changed at every stage of the process upto the field level.
You can check the theme information in the other section towards the bottom of the right vertical tabs. There you would see the list of theme templates you can use. The last one is where the fields get themed. and moving upwards each of the wrapping themes such as the row theme the entire page theme etc. The name suggestion are also there in the same place.
You can make the template as specific as you want.
Comment: thanks for the reply.
As I understand from your answer, that would create a tpl for each of the fields for the row and the row style, because I want to modify almost everything. is not there a better way?
Comment: what kind of change do you want to apply to the html and the purpose of the same?
Answer: Views has a set of hooks that you can use as well as template files.
If you don't want to use tpl.php files then use hooks.
This is probably what you want but there are plenty of others that are easy to find on api.drupal.org:
http://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7
If that's not powerful enough for you then you can also write your own Views handlers that extend the existing handler classes OOP-style and just change how things are rendered there.
Answer: If you want to change exposed filter form in view then use hook_views_exposed_form to Change the exposed form output.
if your view is for listing some content type data then you can use tpl and tpl
naming convension is in theme information on bottom of right side in advance.
then in tpl you can get $rows variable and iterate over this for data but you can change the listing design like table or div layout.

how to change views output


Ajax request 500 interval error

Question: I am using Python Flask framework to build my website. I try to use ajax call to get server response and result in 500 internal error.
app.py
from flask import Flask, render_template,request
@app.route(''+'/api/suggest/')
def api():
   pass

index.js
new Ajax.Request('api/suggest/',{
    method: 'get',
    onSuccess: function(response) {
        alert(response);
    }
});

http://localhost:5000/api/suggest/ returns 500 Internal server error

Failed to load resource: the server responded with a status of 500
  (INTERNAL SERVER ERROR)
Comment: Did you run your flask app to make sure that it works? From what I can see, if that is your code, it's not looking too good.
Comment: @idjaw yea localhost:5000 works fine for me
Comment: `@app.route(""+/api/suggest")` but that is wrong. Are you showing the exact code on your end?
Comment: @idjaw My mistake in the post. It should be @app.route(''+'/api/suggest'), still get same error.
Comment: `''+'/api/suggest/'` is the same as `'/api/suggest/'`.
Comment: OK....so that means you actually have a method with `pass` in it. You *need* to return something.
Answer: I believe that your api() function needs to return something, rather than pass. If you pass the function, it has a return value of None and messes up with your alert(response). Instead, you should do:
def api():
    return {}

or
def api():
    return "Testing"

Ajax request 500 interval error


Is it good to open multiple ports on TCP server?

Question: The Tcp server need to serve many clients, If one client one server port and one server thread to listen the port, I want to know weather it is faster ?
If one port is good, could someone explain the different between one port and multiple ports in this case, thanks!
Answer: The problem with using multiple ports to achieve this is that each of your clients will each have a specific port number.  Depending on the number of clients there could be a tremendous amount of bookkeeping involved.
Typically, for a tcp server that is to serve multiple clients, you have a "main" thread which listens to a port and accepts connections on that port.  That thread then passes the connected socket off to another thread for processing and goes back to listening.
For a wealth of Unix network programming knowledge check out "The Stevens Book"
Answer: Generally speaking* the server will allocate it's own outgoing sockets for each connected client (and you don't need to be aware of those numbers). Each client connection handle will hold it's port references.
When defining the servers connection port, you will allocate a socket for incoming clients to connect to. There is no performance benefit using multiple sockets, in fact allocating additional sockets will show a performance hit (although for each port it will be tiny.)
update...
By the way, assigning multiple incoming ports (particularly a large range) for clients to connect to is also insane. From the perspective of making the service usable and maintainable.
Comment: thanks! I think there is a buffer for one port to save the client request(if there are too many requests).


How to get a "simple" function pointer from a member function

Question: I'm having a problem with function pointers and nothing I found on the net helped me to solve this problem.
I have a function from a C API which take a pointer of a void function :
extern int APIFunction(int, void (*func)(int));
I have a class with the function I would like to put when I call the API function.
class MyClass
{
   public:
      void myFunction(int status, otherAPi arguments...);
};

Then, I created a pointer to my member function and created a new instance of my class
typedef  void (MyClass::*MyClassFunctionPointer)(int stat, otherAPi arguments...);
MyClassFunctionPointer fctPointer= &MyClass::myFunction;
LicenseSecurity instance;

I get an error when I try to call my APi function with the function pointer I created:
int stat = APIFunction(5, fctPointer ); // -> error 1
int stat = APIFunction(5, instance.*fctPointer ); // -> error 2

I got errors respectively in the first and second case:
E2034 Impossible to convert 'void (MyClass::*)(int, otherAPITypes...)' into 'void (*) (int, otherAPITypes...)'
E2342 Bad type correspondence in the parameter 'func' ('void (*)(int, otherAPITypes...)' desired, 'void(int, otherAPITypes...)' obtained)

I don't have access to the API function so I can't modify it. To summary the problem: how How to get a "simple" C function pointer to put in argument of a function from a member function of my class?
Thanks
Comment: I think boost::bind is helpful here
Comment: @Constantin Then he would have a functor that wraps the member function call...but he still couldn't pass it to the API function.
Comment: possible duplicate of [C++ class member function callback](http://stackoverflow.com/questions/8079453/c-class-member-function-callback)
Comment: Yeah, that's the trick thought to wrap it in a functor and bind the class instance... I can't remember what the next step was though. I might be confused cause I can't find an example....
Answer: Unfortunately, you can't.  Sorry.
Ideally, your API would accept something like std::function that would allow you to wrap free functions or member functions.  But if you can't modify the API, then you have no choice but to provide a free function.
Comment: @Constantin: yes, g++ is just a wrapper for gcc with specific options
Comment: Actually, you can do that in certain cases. GCC has a special feature called PMI conversion for that reason. But that won't work for all methods (think multiple, virtual inheritance) and is certainly not standard and not even portable across compilers.
Answer: You can't get a "simple" function pointer to a non-static member function because the function requires a this pointer when called.  If you were to create a function pointer like that then when the function was called there would be no this pointer for it to reference.
Answer: With an ancient C API like that, you unfortunately don't have any way to do this.
What you have to do is make a static or non-member function to take the callback, and then figure out which instance of the object to call the member on. Some C APIs allow a user data to be passed to the callback, and in that case you use that to store the this pointer in question. If that's not an option you can use a global or singleton object and only allow a single such callback to be registered.
Comment: The problem is that with a static or non-member function I can't use attributes of my class and I need it.
Answer: You can declare the callback as either a standalone function or as a static method of the class.  The tricky part is accessing a class instance pointer inside the callback.
Ideally, a well-designed API allows you to specify a user-defined value to callbacks. That allows you to easily pass in a class instance and access it directly inside the callback.  But it sounds like you are not working with such an API, so you need to use a workaround.
If you have only 1 class instance being used with the API at a time, you can store the instance pointer into a global variable, and have the callback use the global variable to access the instance.
But if you have multiple class instances being used at the same time, you are looking for a thunking solution, similar to the VCL's MakeObjectInstance() function, which allows TWndMethod-signatured class methods to be used as Win32 window procedure callbacks.  Essentially, a block of executable memory is dynamically allocated, stub assembler code is written into the block, and the instance pointer and class method pointer are stored in the block as well.  The block is then passed to the API as if it were a function pointer. When the API calls the "function", the stub code gets executed, which has to manipulate the call stack and CPU registers to call the stored class method pointer passing the stored instance pointer as its hidden this parameter, while preserving the semantics of other parameters, the call stack, function result, etc.
Nothing in C++ really accomplishes that kind of thunking natively.  It is not difficult to implement manually, but it is not trivial either (have a look at the source code for MakeObjectInstance() in the VCL's Classes.pas source file). The hardest part is coming up with the necessary stub code that matches the semantics of your particular class method's signature.


How are the weights set in the AR and MA?

Question: I am studying ARIMA models and trying to get a grip of the concept.
But I cant seem to find anyone motivating the values on the weights.
Consider the following AR(2) model below,
$Y_{t} = \mu + \beta Y_{t-1} + \beta_{-1} Y_{t-2} + \epsilon_{t} $
How are the Betas set? They seem to be decreasing since the correlation is lower further back in time (makes sense).
Like; B1 = 0.81, B2 = 0.52 etc...
Are the values found in the ACF/PACF diagrams?
Comment: PACF indicates proper length, once you've decided length (2, in your case) the parameters can be estimated by, say, R, and the method is usually maximum likelihood by default.
Answer: For a pure AR model the B's are estimated/suggested using the PACF as starting values. All ARIMA models can be restated as a weighted average of the past.


Guitar string tension and scale length

Question: A simple question: you have an acoustic guitar with a 20 inch scale and tune it to say E. Now transfer the string to a 25 inch scale and retune it to E. By what  percentage would the tension increase?
Comment: You are assuming the same string gauges? A related question would be how to compensate (retain the same tension) by changing the string gauge.
Answer: The square of the frequency of a vibrating string is directly proportional to the tension, and inversely proportional to the square of the length of the string. So, for two strings of identical composition vibrating at the same frequency:
T2 = (L22 / L12) * T1.
For L1 = 20in and L2 = 25in, we have L2 = 1.25 * L1, or L22 = 1.5625 * L12. This means that:
T2 = 1.5625 * T1 = (1 + 0.5625) * T1.
The tension in the 25 inch string is 56.25% higher than the tension in the 20 inch string. Hmmm, in retrospect, you probably should have asked this over at the SE Physics site.
Comment: does a 25 inch scale exist on acoustic?
Comment: @NeilMeyer -- [Stewie Mac](https://www.stewmac.com/How-To/Online_Resources/Learn_About_Guitar_and_Instrument_Fretting_and_Fretw/Scale_Length_Explained.html) shows some Nationals as 25" scale length, and some other acoustics as longer. I have a Taylor 12-string with a 25.5" scale length.
Comment: @NeilMeyer - My Fender, Epiphone and Yamaha acoustics are all pretty close to 25" scale. 25.5", 25.65" and exactly 25" respectively. Scale lengths are averaged across the strings, as the saddles are not parallel to the nut. Epi measured from the zero fret.
Comment: In laymans' terms, I'd have said the sting is 25% longer, so it'd need 25% more tension. Guess it's not simply a straight line graph... +1

Guitar string tension and scale length


php | wordpress | sort array of values

Question: I'm working in Wordpress with a custom post type of ''publications."  Originally, each "publication" was assigned to a single "category," and getting them to display by category was simple...
$args = array( 'post_type' => 'publications', 'meta_key' => 'publications_category', 'orderby' => 'meta_value', 'order' => 'ASC');
$loop = new WP_Query( $args );

Then the client decided they wanted to assign the same "publication" to multiple "categories," and my meta_key became an array.  And now I can't get the "publications" to sort alphabetically by "category."
Because my meta_key is now an array, I removed the 'meta_key', 'order_by' and 'order' from the query. Here's what I have been testing...
<?php
$args = array( 'post_type' => 'publications');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$cp_category = get_post_meta($post->ID, 'publications_categories', true); // assign a var to the array
foreach ($cp_category as $category) { // iterate through the array
the_title();  // print the title
echo '

' . $category . '

'; //  print the category
}
endwhile;
?>

I have tried various sort() functions on the array with not luck.
There are six categories. The values are strings: 'cabg_vs_opcab', 'high_risk_patients', 'mortality_and_morbidity', 'stroke', 'clampless_beating_heart', and 'economics.'
Here is what the output looks like.  I added a print_r() to diplay the array above each entry:
http://offpump.com/clinical-publications/

All I want to do is order the entries by their category so I'm hoping there is a way to do that.
Thanks for any help or suggestions!
Answer: You should not sort them alphabetically after retrieving them from the database.
To avoid any duplicate processing you should fetch them pre-sorted.
Quick search led me to the syntax for wordpress queries:
$args = array(
        'post_type' => 'post',
        'meta_key' => 'pb_issue_featured',
        'orderby'   => 'meta_value',
        'order' => 'DESC',
        'post_status' => 'publish',
        'posts_per_page' => $posts,
        'paged' => $paged,
        'meta_query' => array(
            array(
                'key' => 'headline',
                'value' => 1,
                'compare' => '!='
                )
            )
        );
$q = new WP_Query($args);

https://wordpress.stackexchange.com/questions/109849/order-by-desc-asc-in-custom-wp-query
Comment: Thanks for helping. Just to be clear, my meta_key (publications_categories) is an array (from a checkbox group) of one or more categories (cabg_vs_opcab, high_risk_patients, etc.). I added a meta_query as you suggested, but it only worked if I used the 'LIKE' comparison. Comparing with "=" or "IN" did not work. That has me stumped b/c I need to get ONLY the one category, and "LIKE" also fetches any other category in the array with the one I want. And finally, is there a way to get all the categories in one query? Not just one at a time?
Comment: That is the goal isn't it :) I'm not as familiar with wordpress so my suggestion is to explore a direct sql solution, use it or after finding the necessary syntax convert it into wp_query format.
Answer: So since the only 'compare' parameter that worked for me was "LIKE" I ended up using it.  The page/template has a loop for each "LIKE" query -- six in all -- and it works fine b/c there are not that many posts.
I'm determined to find a better solution, however, and will come back and post it when I get there.
Thanks to all who helped.

php | wordpress | sort array of values


in firewalld port 80 is closed but nmap shows the port is open, and I can connect to it

Question: my linux environment is fedora 27, httpd is running, and firewall-cmd --list-all shows
FedoraWorkstation (active)
  target: default
  icmp-block-inversion: no
  interfaces: wlp3s0
  sources:
  services: dhcpv6-client ssh samba-client mdns
  ports: 1025-65535/udp 1025-65535/tcp
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

Although the http service or port 80 is not allowed, nmap shows that
Starting Nmap 7.60 ( https://nmap.org ) at 2017-11-25 18:55 PST
Nmap scan report for 10.0.0.15
Host is up (0.000052s latency).

PORT   STATE SERVICE
80/tcp open  http

Nmap done: 1 IP address (1 host up) scanned in 0.33 seconds

and actually I can connect to the server using browser
"systemctl status httpd" shows no errors but "systemctl status firewalld" shows following errors
Nov 25 18:34:44 localhost.localdomain firewalld[3310]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete FORWARD --out-interface virbr0 --jump REJECT' failed:
Nov 25 18:34:44 localhost.localdomain firewalld[3310]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete FORWARD --in-interface virbr0 --jump REJECT' failed:
Nov 25 18:34:44 localhost.localdomain firewalld[3310]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete INPUT --in-interface virbr0 --protocol udp --destination-port 53 --jump ACCEPT'
Nov 25 18:34:44 localhost.localdomain firewalld[3310]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete INPUT --in-interface virbr0 --protocol tcp --destination-port 53 --jump ACCEPT'
Nov 25 18:34:44 localhost.localdomain firewalld[3310]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete OUTPUT --out-interface virbr0 --protocol udp --destination-port 68 --jump ACCEPT
Nov 25 18:34:44 localhost.localdomain firewalld[3310]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete INPUT --in-interface virbr0 --protocol udp --destination-port 67 --jump ACCEPT'
Nov 25 18:34:44 localhost.localdomain firewalld[3310]: WARNING: COMMAND_FAILED: '/usr/sbin/iptables -w2 -w --table filter --delete INPUT --in-interface virbr0 --protocol tcp --destination-port 67 --jump ACCEPT'
Nov 25 18:43:17 localhost.localdomain systemd[1]: Reloading firewalld - dynamic firewall daemon.
Nov 25 18:43:17 localhost.localdomain systemd[1]: Reloaded firewalld - dynamic firewall daemon.
Nov 25 18:43:17 localhost.localdomain firewalld[3310]: WARNING: FedoraServer: INVALID_SERVICE: cockpit

if I make same situation in my virtual machine which runs centos7, firewalld works as I want. while running httpd in vm, if I add http service in the firewall rule, then I can connect otherwise I cannot. but in fedora, I don't know what is wrong.
what I was trying to do was port forwarding from host port 80/tcp to my vm port 80/tcp. I realized that port forwading was not working and neither add-service, or add-port in firewall-cmd. How can I fix the problem?
Although iptables is disabled, I post output of iptables -L here.
192.168.122.0/24 is network for my vm
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     udp  --  anywhere             anywhere             udp dpt:domain
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:domain
ACCEPT     udp  --  anywhere             anywhere             udp dpt:bootps
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:bootps
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
INPUT_direct  all  --  anywhere             anywhere
INPUT_ZONES_SOURCE  all  --  anywhere             anywhere
INPUT_ZONES  all  --  anywhere             anywhere
DROP       all  --  anywhere             anywhere             ctstate INVALID
REJECT     all  --  anywhere             anywhere             reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             192.168.122.0/24     ctstate RELATED,ESTABLISHED
ACCEPT     all  --  192.168.122.0/24     anywhere
ACCEPT     all  --  anywhere             anywhere
REJECT     all  --  anywhere             anywhere             reject-with icmp-port-unreachable
REJECT     all  --  anywhere             anywhere             reject-with icmp-port-unreachable
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere
FORWARD_direct  all  --  anywhere             anywhere
FORWARD_IN_ZONES_SOURCE  all  --  anywhere             anywhere
FORWARD_IN_ZONES  all  --  anywhere             anywhere
FORWARD_OUT_ZONES_SOURCE  all  --  anywhere             anywhere
FORWARD_OUT_ZONES  all  --  anywhere             anywhere
DROP       all  --  anywhere             anywhere             ctstate INVALID
REJECT     all  --  anywhere             anywhere             reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     udp  --  anywhere             anywhere             udp dpt:bootpc
OUTPUT_direct  all  --  anywhere             anywhere

Chain FORWARD_IN_ZONES (1 references)
target     prot opt source               destination
FWDI_FedoraWorkstation  all  --  anywhere             anywhere            [goto]
FWDI_FedoraWorkstation  all  --  anywhere             anywhere            [goto]

Chain FORWARD_IN_ZONES_SOURCE (1 references)
target     prot opt source               destination

Chain FORWARD_OUT_ZONES (1 references)
target     prot opt source               destination
FWDO_FedoraWorkstation  all  --  anywhere             anywhere            [goto]
FWDO_FedoraWorkstation  all  --  anywhere             anywhere            [goto]

Chain FORWARD_OUT_ZONES_SOURCE (1 references)
target     prot opt source               destination

Chain FORWARD_direct (1 references)
target     prot opt source               destination

Chain FWDI_FedoraWorkstation (2 references)
target     prot opt source               destination
FWDI_FedoraWorkstation_log  all  --  anywhere             anywhere
FWDI_FedoraWorkstation_deny  all  --  anywhere             anywhere
FWDI_FedoraWorkstation_allow  all  --  anywhere             anywhere
ACCEPT     icmp --  anywhere             anywhere

Chain FWDI_FedoraWorkstation_allow (1 references)
target     prot opt source               destination

Chain FWDI_FedoraWorkstation_deny (1 references)
target     prot opt source               destination

Chain FWDI_FedoraWorkstation_log (1 references)
target     prot opt source               destination

Chain FWDO_FedoraWorkstation (2 references)
target     prot opt source               destination
FWDO_FedoraWorkstation_log  all  --  anywhere             anywhere
FWDO_FedoraWorkstation_deny  all  --  anywhere             anywhere
FWDO_FedoraWorkstation_allow  all  --  anywhere             anywhere

Chain FWDO_FedoraWorkstation_allow (1 references)
target     prot opt source               destination

Chain FWDO_FedoraWorkstation_deny (1 references)
target     prot opt source               destination

Chain FWDO_FedoraWorkstation_log (1 references)
target     prot opt source               destination

Chain INPUT_ZONES (1 references)
target     prot opt source               destination
IN_FedoraWorkstation  all  --  anywhere             anywhere            [goto]
IN_FedoraWorkstation  all  --  anywhere             anywhere            [goto]

Chain INPUT_ZONES_SOURCE (1 references)
target     prot opt source               destination

Chain INPUT_direct (1 references)
target     prot opt source               destination

Chain IN_FedoraWorkstation (2 references)
target     prot opt source               destination
IN_FedoraWorkstation_log  all  --  anywhere             anywhere
IN_FedoraWorkstation_deny  all  --  anywhere             anywhere
IN_FedoraWorkstation_allow  all  --  anywhere             anywhere
ACCEPT     icmp --  anywhere             anywhere

Chain IN_FedoraWorkstation_allow (1 references)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh ctstate NEW
ACCEPT     udp  --  anywhere             anywhere             udp dpt:netbios-ns ctstate NEW
ACCEPT     udp  --  anywhere             anywhere             udp dpt:netbios-dgm ctstate NEW
ACCEPT     udp  --  anywhere             126.96.36.199          udp dpt:mdns ctstate NEW
ACCEPT     udp  --  anywhere             anywhere             udp dpts:blackjack:65535 ctstate NEW
ACCEPT     tcp  --  anywhere             anywhere             tcp dpts:blackjack:65535 ctstate NEW

Chain IN_FedoraWorkstation_deny (1 references)
target     prot opt source               destination

Chain IN_FedoraWorkstation_log (1 references)
target     prot opt source               destination

Chain OUTPUT_direct (1 references)
target     prot opt source               destination

output of "lsof -i -P -n|grep LISTEN" is
dnsmasq    1037 nobody    6u  IPv4   27561      0t0  TCP 192.168.122.1:53 (LISTEN)
cupsd      1788   root    9u  IPv6   37232      0t0  TCP [::1]:631 (LISTEN)
cupsd      1788   root   10u  IPv4   37233      0t0  TCP 127.0.0.1:631 (LISTEN)
httpd      2355   root    4u  IPv6   43072      0t0  TCP *:80 (LISTEN)
httpd      2358 apache    4u  IPv6   43072      0t0  TCP *:80 (LISTEN)
httpd      2359 apache    4u  IPv6   43072      0t0  TCP *:80 (LISTEN)
httpd      2360 apache    4u  IPv6   43072      0t0  TCP *:80 (LISTEN)
sshd       3070   root    5u  IPv4   50178      0t0  TCP *:22 (LISTEN)
sshd       3070   root    7u  IPv6   50180      0t0  TCP *:22 (LISTEN)
jupyter-n  3512   rhce    4u  IPv6   64019      0t0  TCP [::1]:8888 (LISTEN)
jupyter-n  3512   rhce    5u  IPv4   64020      0t0  TCP 127.0.0.1:8888 (LISTEN)
python3    3545   rhce   14u  IPv4   66283      0t0  TCP 127.0.0.1:40521 (LISTEN)
python3    3545   rhce   17u  IPv4   66287      0t0  TCP 127.0.0.1:49589 (LISTEN)
python3    3545   rhce   20u  IPv4   66291      0t0  TCP 127.0.0.1:48583 (LISTEN)
python3    3545   rhce   23u  IPv4   66295      0t0  TCP 127.0.0.1:39659 (LISTEN)
python3    3545   rhce   28u  IPv4   66300      0t0  TCP 127.0.0.1:35933 (LISTEN)
python3    3545   rhce   41u  IPv4   68637      0t0  TCP 127.0.0.1:44955 (LISTEN)

and output of ss -tlpn is
State       Recv-Q Send-Q                                                            Local Address:Port                                                                           Peer Address:Port
LISTEN      0      100                                                                   127.0.0.1:49589                                                                                *:*                   users:(("python3",pid=3545,fd=17))
LISTEN      0      32                                                                192.168.122.1:53                                                                                *:*                   users:(("dnsmasq",pid=1037,fd=6))
LISTEN      0      128                                                                           *:22                                                                                *:*                   users:(("sshd",pid=3070,fd=5))
LISTEN      0      5                                                                     127.0.0.1:631                                                                                *:*                   users:(("cupsd",pid=1788,fd=10))
LISTEN      0      128                                                                   127.0.0.1:8888                                                                                *:*                   users:(("jupyter-noteboo",pid=3512,fd=5))
LISTEN      0      100                                                                   127.0.0.1:44955                                                                                *:*                   users:(("python3",pid=3545,fd=41))
LISTEN      0      100                                                                   127.0.0.1:35933                                                                                *:*                   users:(("python3",pid=3545,fd=28))
LISTEN      0      100                                                                   127.0.0.1:48583                                                                                *:*                   users:(("python3",pid=3545,fd=20))
LISTEN      0      100                                                                   127.0.0.1:40521                                                                                *:*                   users:(("python3",pid=3545,fd=14))
LISTEN      0      100                                                                   127.0.0.1:39659                                                                                *:*                   users:(("python3",pid=3545,fd=23))
LISTEN      0      128                                                                           *:80                                                                                *:*                   users:(("httpd",pid=2360,fd=4),("httpd",pid=2359,fd=4),("httpd",pid=2358,fd=4),("httpd",pid=2355,fd=4))
LISTEN      0      128                                                                           *:22                                                                                *:*                   users:(("sshd",pid=3070,fd=7))
LISTEN      0      5                                                                         [::1]:631                                                                                *:*                   users:(("cupsd",pid=1788,fd=9))
LISTEN      0      128                                                                       [::1]:8888                                                                                *:*                   users:(("jupyter-noteboo",pid=3512,fd=4))

Comment: show a `iptables -L`
Comment: All your COMMAND_FAILED lines must first be resolved. What result do you have if you run them one by one on the command line?
Comment: executing the failed commands one by one does not give error. In my understanding, firewalld is different service from iptables. but why did firewalld execute the failed commands? does firewalld depend on iptables even though iptables service is disabled?
Comment: All traffic is always allowed on the local host.
Comment: In what you describe as the output of iptables -L, I do not see a listing of ports and their status. Have you tried any of these commands to view more on the status of TCP port 80:
lsof: `$ sudo lsof -i -P -n | grep LISTEN` netstat: `$ netstat -tulpn | grep LISTEN` (for linux) Your firewall shows port 80 is closed? And you do not have any http services somewhere calling the default port?
Comment: I started httpd(apache), and I intentionally closed port 80 using firewall-cmd in order to test. but unfortunately, firewalld does not work as I want. and output of ss and lsof is on post
Comment: With `netstat -tulpn | grep :80` you could see which process is accepting traffic on port 80
Answer: Interestingly firewalld did not allow port forwarding to virtual machine, even though the firwalld command was right. I found that iptables rule blocks the port forwarding before firewalld. so I added directly port forwarding rule to the first row of iptables rules.


How to perform a search using the Desk API v2

Question: Has any one had any success using Desk's public API to do searches for either customers or companies? I am using the RestSharp library to submit requests, which works fine for creating new companies or pulling individual cases by ID. Here is a sample of what I'm trying to do.
RestClient client = new RestClient();

client.Authenticator = RestSharp.Authenticators.OAuth1Authenticator.ForProtectedResource(Configuration.ApiKey, Configuration.SiteKey, Configuration.Token, Configuration.TokenSecret);
client.BaseUrl = "https://imathlete.desk.com/api/v2";

string json = new JavaScriptSerializer().Serialize(new Dictionary<string, object> {
    { "q", "my company" }
});

RestRequest request = new RestRequest {
    Method = Method.GET
    , Resource = "companies/search"
    , RequestFormat = DataFormat.Json
};

request.AddBody(json);

RestResponse response = (RestResponse)client.Execute(request);
string data = System.Text.Encoding.ASCII.GetString(response.RawBytes);

I've tried switching out the "q" in the request body for either "name" or "domain," but the response is always the same:
{"message":"Invalid search parameters"}

Any advice would be greatly appreciated.
Answer: Maybe change
Resource = "companies/search"

to
Resource = "companies/search?"

Also be sure to URI encode your query string
debugging tips:

Use the PostMan chrome extension, other browsers might have
similar tools
Inspect the network XHR requests sent by the Desk
search box in the Desk app.


Como resolver problema de layout do errorText em Flutter

Question: Eu estou tendo uma certa dificuldade com o errorText do TextFormField.
Sempre que aparece ele "empurra" os outros elementos pra baixo.
O que eu uso é basicamente essa estrutura:
Scaffold(
      backgroundColor: Colors.deepPurple.shade100,
      body: Center(
        child: Form(
          key: _formKey,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 32.0),
            width: 400,
            height: 200,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                TextFormField(
                  decoration: const InputDecoration(
                    labelText: 'Nome',
                    floatingLabelBehavior: FloatingLabelBehavior.always,
                    border: OutlineInputBorder(),
                    contentPadding: EdgeInsets.only(left: 11, right: 3, top: 14, bottom: 14),
                    errorStyle: TextStyle(fontSize: 9, height: 0.1),
                  ),
                  validator: (value) {
                    if(value == null || value == '') {
                      return 'Campo não pode ser vazio';
                    }
                  },
                ),
                const SizedBox(height: 24,),
                SizedBox(
                  width: 80,
                  height: 35,
                  child: ElevatedButton(
                    onPressed: () {
                      _formKey.currentState!.validate();
                    },
                    child: const Text('Validar')
                  ),
                ),
              ]
            ),
          ),
        ),
      ),
    );
  }

Comment: Fala Nelson. A resposta que foi fornecida resolveu seu problema? Se sim, acha que pode aceitá-la? Você pode fazer isso clicando no símbolo de ✔ ao lado da resposta. Fazer isso contribui com a categorização e eventuais buscas no site. Um abraço.
Answer: Esta é uma dúvida que já foi discutida no repositório oficial do Flutter (em inglês, um tempo atrás).
O erro ocorre porque a altura que o Widget calcula para si é diferente caso ele possua ou não uma mensagem de erro a ser exibida.
Foram citadas duas soluções:

Adicione um helperText vazio (Isto é, um espaço: " "), utilizando o mesmo estilo que o seu errorText. Desta forma o Widget vai calcular sua altura levando em consideração o texto inferior e não vai ser diferente da altura de quando a mensagem de erro aparece:

TextFormField(
  decoration: const InputDecoration(
    helperText: ' ', // Helper text como uma string contendo um espaço.
    helperStyle: TextStyle(fontSize: 9, height: 0.1), // O mesmo que o usado em errorStyle

Envolva o seu TextFormField em um outro Widget com uma altura fixa (como um SizedBox). É importante que essa altura fixa seja maior do que o tamanho que o TextFormField ocupa. Em meus testes, 70 foi suficiente:

children: [
    SizedBox(
        height: 70,
        child: TextFormField( // Seu TextFormField aqui.

Ambas as soluções atingem o resultado desejado. Você pode escolher a que melhor se adequa:
A primeira tem como vantagem o fato de ser uma altura dinâmica. Você não precisa se preocupar em escolher arbitrariamente um valor para a altura, como precisa fazer na segunda solução. O TextFormField terá sempre sua altura justinha e exata. Se no futuro algo externo mudar, pode ser que a altura escolhida no segundo método não seja mais adequada. Você pode experimentar mudar a altura para um valor pequeno e ver o que acontece.
Em contra partida, a primeira solução "parece" um pouco mais como uma gambiarra. Pode atrapalhar a legibilidade, e vai precisar de uma lógica pequena caso você queira usar um helperText também. Em um futuro, caso outra pessoa (ou você mesmo) leia essa linha, pode não ser claro a necessidade do espaço em branco.


$\theta^Tx$ vs. $\sum_{j=1}^n\theta_j x_j$

Question: I'm taking Andrew Ng's Machine Learning course on Coursera and there's a slide where he's discussing "vectorised" versions of different formula which execute much more efficiently than their iteratively defined functions.
One of the course lecture slides he defines a function $h(\theta)$ two different ways and defines them as equivalent, but I can't see how they are equal.
$h(\theta) = \sum_{j=1}^n\theta_j x_j$
and
$h(\theta) = \theta^Tx$
The main difference being that the first one reduces to a single value and the second one a row vector ($\theta$ originally being a column vector).
My two questions are:

Is he just skipping the step of summing over the row vector in $h(\theta)=\theta^Tx$ because he expects to use more vector operations in the future and does not need a single value?
Why do we need to transpose $\theta$? Is it just more convenient to have a row vector in some cases rather than a column vector?

I know any answer here will likely be working off of assumptions, but I'm guessing there are some sort of field best practices he might be working with.
Comment: Have you ever multiplied matrices?
Answer: Note that $\theta$ and $x$ are both column-vectors.  So by multiplying matrices, we see that
$$
\theta^T x = \pmatrix{\theta_1 & \cdots & \theta_n}\pmatrix{x_1 \\ \vdots \\ x_n} =
\theta_1 x_1 + \cdots + \theta_n x_n,
$$
which is exactly the sum we wanted.
Regarding your second question: there is no product (in this context) defined between two vectors of $\Bbb R^n$.  If we transpose the first vector however, we can get the inner-product (AKA dot-product) $\theta^Tx$ as illustrated above.
Interestingly, there is also an "outer-product" $\theta x^T$; note that this multiplication results in an $n \times n$ matrix.
Comment: If you are new to matrix-multiplication, see [this page](https://www.mathsisfun.com/algebra/matrix-multiplying.html).  Look in particular at the "rows and columns" section.
Comment: @Breedly it is a common convention in this area that lowercase letters (such as $x$ and $\theta$) could refer to either to scalars or vectors (usually column-vectors).  Capital letters like $X$ are typically reserved for matrices that have more than one column.
Comment: I should have read the whole page. I didn't get to the part about 1 x 3 and 3 x 1 matrices. Some of the course material seem to indicate that "x" is a scalar in this case. An X would indicate a matrix.
Comment: Thanks! This was really helpful.
Answer: Be carefull, $\theta = (\theta_{1}, ... ,\theta_{n}) $ and $x = (x_{1},...,x_{n})$
Then $\theta^{T} \cdot x = \sum \theta_{j} x_{j}$
Are the same


Meaning and interpretation of Transfer Entropy

Question: I am a first-year undergrad student and I have been reading about Transfer Entropy for my research. Although I understand the math behind I am not really sure what the value means. For example, I run $TE(X\mapsto Y)$ and I get the value of TE as 0.624.
What does this value mean?
Answer: Since you've already followed the math, I'll provide an explanation in intuitive, layman terms rather than the precise definition.
$TE(X\mapsto Y)=0.624$ means that the history of the X process has 0.624 bits of additional information for predicting the next value of Y. (i.e., it provides information about the future of Y, in addition to what we know from the history of Y).
Since it is non-zero, you can conclude that X influences Y in some way.
The TE should not be negative. To see if the TE is actually significant, you could compare it with the entropy of Y. If H(Y) is, say 200 bits per sample,  0.624 may not be significant. TE should never be more than the entropy of Y, so that's the range you expect.
Comment: I have two questions: 1) can TE be negative? 2) Is there a range in which TE oscillates?
Comment: Just added explanation in the answer.
Comment: could you explain how in the above case TE is more than the Entropy of Y? Is there a general ratio we assume when comparing TE with the corresponding entropy?
Comment: TE should not be more than the entropy. It's either a machine floating point error or a bug. There isn't a general rule for the ratio that I know of - it's something you might consider as it relates to the problem.


Any Solution To Converting Apk To 64 bit in Android studio please Example

Question: android {
    compileSdkVersion 29
    defaultConfig {
        applicationId "com.alifbaataa.madniqaida.madaniqaidahpro"
        minSdkVersion 16
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 79
        versionName '13.11.24'
        ndk {
            abiFilters 'armeabi-v7a','arm64-v8a','x86','x86_64'

        }
        ndk {
            abiFilters = []
            abiFilters.addAll(PROP_APP_ABI.split(':').collect {it as String})
        }

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true

        lintOptions {
            checkReleaseBuilds false
            abortOnError false
        }
    }
    buildTypes {
        release {
            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    //noinspection GradleCompatible
    implementation 'androidx.appcompat:appcompat:1.0.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.vectordrawable:vectordrawable:1.0.0'
    implementation 'androidx.navigation:navigation-fragment:2.0.0-rc02'
    implementation 'androidx.navigation:navigation-ui:2.0.0-rc02'

    implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
    implementation 'com.google.firebase:firebase-storage:16.0.4'
    implementation 'com.google.firebase:firebase-auth:16.0.5'
    implementation 'com.google.firebase:firebase-database:16.0.4'
    implementation 'com.google.firebase:firebase-firestore:17.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'

    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'com.github.carlosmuvi:SegmentedProgressBar:0.6.0'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    implementation 'com.github.varunest:sparkbutton:1.0.6'
    implementation 'com.github.lzyzsd:circleprogress:1.2.1'
    implementation 'com.bcgdv.asia.lib:ticktock:1.3'
    implementation 'com.akexorcist:RoundCornerProgressBar:2.0.3'
    implementation 'com.github.mjn1369:prettydialog:1.0.4'
    implementation 'com.github.panwrona:DownloadProgressBar:1.1'
    implementation 'com.mindorks.android:prdownloader:0.4.0'
    implementation 'com.henryblue.mxvideoplayer:xvideoplayer:1.2.0'
    implementation 'com.anjlab.android.iab.v3:library:1.0.44'
    implementation 'com.sackcentury:shinebutton:0.2.0'
    implementation 'com.facebook.shimmer:shimmer:0.4.0'
    implementation 'androidx.multidex:multidex:2.0.0'

}

How can I fix that and convert to 64 bit?
Answer: Did you analyze your apk? Is it not in 64 bit?
There are two ways to convert apk into 64-bit if it is not.
First you did in this build.gradle file. You have made correct changes but if still your APK is not in 64-bit then it means you are using some library that supports only 32-bit. So read document and track from 3rd party libraries you use in your project, replace or modify them to make them supportive for 64-bit architecture
Comment: I also read documentation at least 20 times but don't understand what i do for that to convert 64 bit actually i don't know how to resolve it any example please help me i also trying to convert but still 32 bit any help with example code or screenshot thank you
Comment: You have to look into the libraries you used in app. This is the solution. You have to do little effort to see any third party library you used in your project which only supports 32-bit.
Comment: I thought the issue is with that library: com.henryblue.mxvideoplayer:xvideoplayer:1.2.0. Check its documentation.
Comment: you mean i remove this dependencies
com.henryblue.mxvideoplayer:xvideoplayer:1.2.0
or other method to use please help
Comment: Thank you (Zubaria Ashraf) its work now
when i remove these dependencies then create in bundle apk that work fine thank you very much
Comment: @SehrMubeen its good to hear that you solved your problem but I did not said to remove I told you to go through with the documentation of this library there may be a solution to make it 64-bit compatible. Anyway, you can also use some alternative library to that does not support 64 bit.


Use the formal definition to prove that the following sequence diverges

Question: $\displaystyle s_n=\left(\frac1n-1\right)^n$
My attempt:
For large $n$, the sequence oscillates between $e^{-1}$ and $-e^{-1}$ and therefore diverges. Now for the proof.
Assume, for the sake of argument, that the sequence converges to $L$.
$\exists N\in\mathbb{N}$ such that $|s_n-L|<0.1$ whenever $n\ge N$
$\displaystyle\left|\left(\frac1n-1\right)^n-L\right|<0.1$ whenever $n\ge N$
$\displaystyle\implies\left|\left(\frac1{n+1}-1\right)^{n+1}-L\right|<0.1$ whenever $n\ge N$
We can rewrite these 2 equations as
$\displaystyle\left|(-1)^n\left(1-\frac1n\right)^n-L\right|<0.1$ whenever $n\ge N$ --------------- (1)
$\displaystyle\left|(-1)^{n+1}\left(1-\frac1{n+1}\right)^{n+1}-L\right|<0.1$ whenever $n\ge N$
$\displaystyle\implies\left|(-1)^n\left(1-\frac1{n+1}\right)^{n+1}+L\right|<0.1$ whenever $n\ge N$ --------------- (2)
How do I get a contradiction from equations (1) and (2)?
Comment: You know that $(1-\frac1n)^n$ is monotonically increasing and greater $1/4$ for $n>2$?
Answer: Since $\left(\frac1n-1\right)=(-1)\left(1-\frac1n\right)$, we can write
$$s_n = (-1)^n\left(1-\frac1n\right)^n. $$
It is clear then that
$$s_{2n} = \left(1-\frac1{2n}\right)^{2n}\stackrel{n\to\infty}\longrightarrow e^{-1}, $$
which implies $\limsup_{n\to\infty} s_n\geqslant e^{-1}$, and similarly
$$s_{2n+1} = -\left(1-\frac1{2n+1}\right)^{2n+1}\stackrel{n\to\infty}\longrightarrow -e^{-1}$$
which implies $\liminf_{n\to\infty} s_n\leqslant -e^{-1}$. It follows that $$\liminf_{n\to\infty}s_n \ne \limsup_{n\to\infty}s_n, $$ and so the sequence $s_n$ does not converge.


Node Lambda timing out firebase-admin SDK

Question: I'm trying to send push notifications through Firebase Cloud Messaging from a node js lambda in AWS.
My function works and I receive the notification on my phone, however the lambda keeps timing out (even at 20s timeout). I can see in logs my lambda callback is being called. It appears that something is preventing the lambda from returning.
I initialise with:

const serviceAccount = require('./firebaseKey.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'xxx',
});

and send with:

const fcmResponse = await admin.messaging().sendToDevice(fcmToken, message);

My hunch is that it's something here preventing it from returning as everything else is pretty vanilla.
Does anyone have any ideas as to what's causing the timeouts?
Comment: Are you able to show more of your code? Are you doing anything with the `fcmResponse` value? I am guessing you aren't returning a promise to the function and it doesn't know when things end. Just a guess without seeing more of the function code.
Answer: For others looking at this.
Firebase seems to leave some stuff kicking around, which means the callback is never called.
Adding the following line in the handler solves the problem:

context.callbackWaitsForEmptyEventLoop = false;


BDD & Test Coverage

Question: I have started writing my first BDD tests for iOS, using Quick and Nimble, and I have a question about test coverage.
I realize that in traditional unit tests, developers aim to have 100% test coverage. However, I haven't read that for BDD. If I am understanding BDD correctly, when I am testing the behavior of my code, then the little details of the implementations don't matter; what matters is that I get the expected outcome from my code, correct?
I started trying to get 100% code coverage, but it seems like I am starting to write brittle tests because instead of focusing on the outcome of my code, I am trying to cover all of the paths that my code can take.

Am I understanding BDD correctly?
Does aiming for 100% code coverage defeat the purpose of BDD?
Comment: You can have 100% test coverage with both, but BDD will ensure you to have developped the right thing.
Comment: the difference of BDD and TDD is not about test coverage, it is about focusing on the behavior in of the software rather than testing implementation detail(Test the API not the implementation as some call it) ,BDD and TDD both will lead to 100% code coverage because one of the main ideas is writing the test first before any implementation code.
Comment: "I realize that in traditional unit tests, developers aim to have 100% test coverage". They certainly do not. 100% test coverage would means that all branches of the code are being traversed at least once, as evidenced by coverage tools. This is generally unnecessary unless you are writing high-.assurance code  (formal methods may be more appropriate then). A unit means to test verify the correct functioning of a unit so that, upon bug fixing and refactoring one can easily check that functioning is still correct. If 100% coverage were intended, one would have to rewrite the unit tests, too.
Answer: As mentioned in one of the comment, the core aspect of BDD is to give you tests (that could be automated) that guarantee that your product is doing exactly that what it is supposed to do. And obviously: "not less than that".
And in that sense, BDD plus coverage helps you with making sure that your product is not doing much more than that.
In other words: assuming that all your BDD test pass; and your coverage is 75% ... than that could mean: 25% of your code base are not required in order to provide the behavior specified within your BDD testcases. Meaning: you can have a closer look at those 25% of untouched lines to understand why they are not needed; to then determine if there is a chance to delete same parts of that unused source code.
As in: the 2nd best thing you can do as software developer: delete code from your code base without reducing the functionality of your product.
( and for the record: the best thing that a SW developer can do: add a new feature to his product that attracts new customers - deleting code helps your quality in the long run, but customers pay your salary short, medium and long term )
Comment: I found more clarity when you discussed the 75% vs the 25%. Reason being is that I add `fatalError()`s in some `guard` statements to help me easily find holes in my logic. However, when running my tests, the `else` clauses of the `guard` statements aren't executed since things are functioning as expected. I was creating additional tests to make the `guard` statements fall through to the `else` clause, therefore getting coverage for the `else` clauses, not knowing if that was appropriate for achieving 100% coverage.
Comment: That makes sense.

BDD & Test Coverage


How to write XML Code in Blockquote

Question: I am writing meta tags in blockquote but it is not displaying. Can anyone help?
Answer: Since SE supports partial HTML tags, it will try to render any HTML-like tags (e.g. XML), even if they are invalid. To prevent it from being rendered, you need to replace "<" character with <.

> Text
>
> <note>
> <to>Tove</to>
> <from>Jani</from>
> <heading>Reminder</heading>
> <body>Don't forget me this weekend!</body>
> </note>
>
> Another text

will be rendered as

Text
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  Don't forget me this weekend!
  </note>
Another text

Alternatively, just use code-block inside the quote-block. In this case, the XML syntax can be pasted directly without needing to replace "<" characters.
> Text
>
>     <note>
>         <to>Tove</to>
>         <from>Jani</from>
>         <heading>Reminder</heading>
>         Don't forget me this weekend!
>     </note>
>
> Another text

will be rendered as

Text
<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    Don't forget me this weekend!
</note>

Another text

How to write XML Code in Blockquote


Adding JavaScript before drupal.js

Question: I am trying to add jQuery to my page (it is not being added by default). The file is adding to the page but after drupal.js causing the error:
SCRIPT5009: 'jQuery' is undefined
drupal.js, line 5 character 1

The code that adds drupal.js to the page in common.inc
...
'misc/drupal.js' => array(
          'data' => 'misc/drupal.js',
          'type' => 'file',
          'scope' => 'header',
          'group' => JS_LIBRARY,
          'every_page' => TRUE,
          'weight' => -1,
          'preprocess' => TRUE,
          'cache' => TRUE,
          'defer' => FALSE,
        ),
...

In my module hook_init I have:
  drupal_add_js('misc/jquery.js', array(
    'group' => JS_LIBRARY,
    'weight' => -20,
    'cache' => TRUE,
  ));

I would think with a lower weight it would load before drupal.js?
The header of the page contains the following scripts:

Comment: _The file is adding to the page but after drupal.js causing the error:_ That's not right - you're getting that error because your script is loading before jQuery, not because it's loading after drupal.js
Comment: Could you please show us order of your js files? Just turn off aggregation before you do that.
Comment: @Mołot question updated
Comment: You still didn't provide what I ask you, so I still cannot help.
Comment: @Mołot having one of those days ;)
Comment: OK, so the problem is: drupal.js is before jquery.js and jquery.once.js - it should be after them. Being before, it throws error and breaks execution. Is it the same without your module? Or was it your module to swap them? Either way, it looks strange.
Answer: In the end I got it working by changing the code to:
  drupal_add_js('misc/jquery.js', array(
    'group' => JS_LIBRARY,
    'weight' => -20,
    'every_page' => TRUE,
    'cache' => TRUE,
    'scope' => 'header',
  ));
  drupal_add_js('misc/jquery.once.js', array(
    'group' => JS_LIBRARY,
    'weight' => -19,
    'every_page' => TRUE,
    'cache' => TRUE,
    'scope' => 'header',
  ));

This then meet the rules on https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7

First by scope, with 'header' first, 'footer' last, and any other scopes provided by a cust om theme coming in between, as determined by the theme.
Then by group.
Then by the 'every_page' flag, with TRUE coming before FALSE.
Then by weight.
Then by the order in which the JavaScript was added. For example, all else being the same, JavaScript added by a call to drupal_add_js() that happened later in the page request gets added to the page after one for which drupal_add_js() happened earlier in the page request.
Answer: You should not add jQuery manually. It is added by Drupal itself. Adding existing libraries is known to cause problems.
If you need newer jQuery version than one included within Drupal, use jQuery update module.
Comment: But jQuery Update only allows to update to 1.8, any shamely, anything higher than jQuery 1.8 will cause Drupal to not work anymore...lol
Comment: @SolomonClosson yes, anything higer than jQuery 1.8 will make Drupal fail as they gave up on backward compatibility. That's the very reason jQuery Update will not allow you to go higher. But dev branch allows you to go up to 1.10.2 and use separate version on admin pages, so if your frontside theme replaces all jQuery version-sensitive scripts provided by core with appropriate hooks and theming functions, then you are OK. and if it does not, changing jQuery manually is even more of a disaster.
Comment: Appropriate hooks and theming functions in your theme, isn't that what jQuery Update should do according to your description of it in the dev build?

Adding JavaScript before drupal.js


do sessions work when cookies are disabled?

Question: if the user has disabled cookies in the browser, do sessions work? cause i know there is a session cookie in the client when i create sessions.
Answer: The session id can be appended to the URL, so, yes, they can.
Check out here
Edit to answer additional question
Cookies are the preferred method if you can help it. You should read the Wikipedia article to get a better understanding. From the article if you don't read it:

Transferring session identifiers as
  HTTP cookies is more secure
Comment: is sending with url better in any way?


Nginx 1.6.2 limit_req_zone: is there a key that identifies unique users?

Question: I am currently managing a website where users are sometime really hasty about new content, and refresh the page intensely leading to a high server load and eventually a crash.
I optimized the website as much as I reasonably could, adding server side caching, UX modification, raising server capacity etc... but it is still not enough.
I then discovered ngx_http_limit_req_module which is doing the work pretty well. There is one problem though: users are highly likely to browse the website from one particular place, which means a same IP address. And in that case, even with a civilized browsing behavior, the limit rate will be triggered.
If possible, I would like to identify each user specifically so the request rate is only triggered when a single user refreshes the page too much, but not when a lot of users using the same IP browse the site normally.
The syntax of the limit_req_zone directive is as follow:
limit_req_zone key zone=name:size rate=rate;

I am currently using something like this:
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

The module documentation also add these informations:

The key can contain text, variables, and their combination. Requests
  with an empty key value are not accounted.

And

Prior to version 1.7.6, a key could contain exactly one variable.

I have little to no experience with Nginx but it seems there could be some solution.
Hence my question: is there a variable than could possibly identify unique users, even if they share the same IP address ?
Thank you very much for your help !
Answer: I finally found  ngx_http_userid_module which allows Nginx to identify a user with a cookie.
After configuring this module, I just needed to change the limit_req_zone directive like this:
limit_req_zone $uid_got zone=one:10m rate=1r/s;

Note: If this module is not already present with your Nginx installation, you will need to recompile it with the proper parameters. This can be difficult if you're not familiar with this process.