text:
Q: Box topology and connectedness property I've been trying to properly comprehend how the box topology is constructed, which I noticed I don't understand corretly when my professor asked me to show if it's false or true that the box-topology of connected spaces is connected. I know that it isn't and I've found an example in this thread here: Infinite product of connected spaces may not be connected?. The definition I'm using for the box topology is the same as from Munkres, which is:
Let $\{X_\alpha\}_{\alpha \in J}$ an indexed family of topological spaces. We will take a basis for the space $\prod_{\alpha\in J} X_\alpha$ as the set of the following products $\prod_{\alpha \in J} U_\alpha$, where $U_\alpha$ is an open set of $X_\alpha$ for every $\alpha \in J$.

Firstly, I thought that it was connected and I came with a proof:
Let $A,B$ be open sets for $X = \prod_{\alpha\in J} X_\alpha$ in the box topology, where $ A = \prod_{\alpha\in J} A_\alpha$ and $B = \prod_{\alpha\in J} B_\alpha$, where $A_\alpha, B_\alpha$ are open sets for $X_\alpha$ for every $\alpha$ and $A\cup B = X$ with this union being disjoint.
Since, the union is disjoint we must have at least one $\alpha' \in J$ such that $A_{\alpha'}\cap B_{\alpha'} = \emptyset$. Since $A\cup B = X$, then $A_{\alpha'} \cup B_{\alpha'} = X_{\alpha'}$ and given the fact that $X_{\alpha'}$ is connected we gain that $X_{\alpha'} = A_{\alpha'}$ and $B_{\alpha'} = \emptyset$ without loss of generality.
So, what I did next is to say that we must have $B = \emptyset$, because it has one of its coordinates being the "empty coordinate". Otherwise, if $B$ is not the empty set, something that doesn't make sense to me, how could I pick an element that is equal to something not empty in the coordinates $B_\alpha$ for $\alpha \neq \alpha'$ while being something "empty" in the coordinate $B_{\alpha'}$?
In general, I'm really doubtful if some set similar to $B$, in the case where $B\neq \emptyset$, can be an element for the basis of the box topology. According to the definition it seems possible however from my point of view I don't see how it is viable to pick an element from such a set.
In the end, considering I wasn't so sure of what I did, I searched a little and I found the page I cite in first paragraph. My proof is obviously wrong, but I didn't managed to understand my mistake until now and I have a feeling that this is strictly related on how the box topology works somehow.
If someome can help me I'd be much obliged :)

A: The problem with your proof is that $A$ and $B$ do not have to have the form $A = \prod_{\alpha\in J} A_\alpha$ and $B = \prod_{\alpha\in J} B_\alpha$.  Remember, sets of this form are not the entire box topology, but only a basis for the box topology.  So instead, $A$ and $B$ just must be unions of sets of this form.


text:
Q: vcrpy record cassettes doesn't record in a test using test_client.post I'm implementing pytest and I want to record the answer of a request using vcrpy.
I'm using flask 1.0.2, pytest 4.5.0, pytest-flask 0.15.0 and vcrpy 2.0.1. I implemented a restful api using flask. I wrote a test but I would like to record the response of the request and vcr is not recording the response.
My endpoint is:
from flask import jsonify
from flask import Blueprint

class CompanyResource(Resource):

    def post(self):
        response = jsonify({
            "timestamp": datetime.utcnow()
        })
        response.status_code = 201
        return response

api_bp = Blueprint('dashboard', __name__)
api = Api(api_bp)
api.add_resource(CompanyResource, 'company', endpoint='company')

The test is the following
import pytest
import vcr

from flask import url_for

base_vcr = vcr.VCR(
    cassette_library_dir='tests/dashboard/fixtures',
    record_mode='once'
)

def test_create_company(client, company_data, headers):
      with base_vcr.use_cassette('create_user.yaml'):
           response = client.post(url_for('dashboard.company'),
                                  json=company_data,
                                  headers=headers)

I expect a file auto-generated on the directory specified. But when I run the test the cassette was not generated. The thing is that if I change client.post by requests.post the response is recorded for a get request, but if I try with a post an error is yield:
requests.exceptions.MissingSchema: Invalid URL '/api/dashboard/company': No schema supplied. Perhaps you meant http:///api/dashboard/company?

Do you have any suggestions to test my post endpoint and record the answer?

A: This is a little late but vcrpy has a list of libraries it records the HTTP requests for. requests is one of them, and the others are mentioned in https://vcrpy.readthedocs.io/en/latest/installation.html#compatibility.

*

*aiohttp

*boto

*boto3

*http.client

*httplib2

*requests (both 1.x and 2.x versions)

*tornado.httpclient

*urllib2

*urllib3

Not sure what test client fixture you are using in your pytest, but if you use requests to call your endpoint successfully, it should record the response for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: after4 - Simple python task (index and list issues) this is my first time asking a question on stack overflow. It has been really valuable to me while I have been learning python 2.7
The question is as follows:
"Given a non-empty list numlist of ints, write a function after4(numlist) that returns a new list containing the elements from the original numlist that come after the last 4 in the original numlist. The numlist will contain at least one 4.
after4([2, 4, 1, 2]) → [1, 2]
after4([4, 1, 4, 2]) → [2]
after4([4, 4, 1, 2, 3]) → [1, 2, 3]"

I believed the question to be rather simple but I just can seem to get the code right for what I had planned in my head.
  def after4(numlist):
    """
    Given a list of numbers, will print all numbers after the last 4
    :param x: list - list of numbers including the 4
    :return: list - New list of all numbers after the last 4
    """
    indices = [i for i, x in enumerate(numlist) if x == 4]
    index = max(indices)
    print x[index:]

But I keep getting this error and I'm not sure how to work around it.
'int' object has no attribute 'getitem'" (the error is on the final line of the code "print x[index:]")
Thank you in advance.

A: You use the name x for two different purposes: as the list parameter for the function after4() and as an integer in the list comprehension for the variable indices.
The interpreter thinks you mean the integer one in the last line, but you mean the list parameter one. Change one of those names to a different name and see what happens.
You should use more descriptive variable names from now on. For example, instead of using x for the list parameter, use something like number_list, which makes it clear just what it is. Keep short names like x for mathematical parameters (such as math.sin(x)) and for list comprehensions.

A: Sorry, previous implementation was wrong. This is correct :)
def after4(x):
    rev = list(reversed(x))         #rev = it's reversed list
    start = len(x) - rev.index(4)   #start = it's index of last 4,  len(x) - length of list
    print x[start:]

In method index(x, y):
x - searching element (here it's 4)
y - index from we want start searching, if we skip this argument it starts from index 0.


text:
Q: Hyphens vs. periods in the script slug in wp_register_script? I have seen script and style handles written in two different ways in wp_register_script and wp_enqueue_script (the same applies to wp_register_style and wp_enqueue_style):

*

*wp_register_script( 'jquery-someplugin', $location );

*wp_register_script( 'jquery.someplugin', $location );
#1 uses a hyphen, #2 uses a period. What is the best practice here?
Which should I be using?

A: Use hyphens only.
Take a look at wp-includes/script-loader.php:
$scripts->add( 'scriptaculous-sound', '/wp-in
$scripts->add( 'scriptaculous-controls', '/wp
$scripts->add( 'scriptaculous', '', array('sc

// not used in core, replaced by Jcrop.js
$scripts->add( 'cropper', '/wp-includes/js/cr

$scripts->add( 'jquery', '/wp-includes/js/jqu

// full jQuery UI
$scripts->add( 'jquery-ui-core', '/wp-include
$scripts->add( 'jquery-effects-core', '/wp-in

$scripts->add( 'jquery-effects-blind', '/wp-i
$scripts->add( 'jquery-effects-bounce', '/wp-
$scripts->add( 'jquery-effects-clip', '/wp-in
$scripts->add( 'jquery-effects-drop', '/wp-in
$scripts->add( 'jquery-effects-explode', '/wp
$scripts->add( 'jquery-effects-fade', '/wp-in
$scripts->add( 'jquery-effects-fold', '/wp-in
$scripts->add( 'jquery-effects-highlight', '/
$scripts->add( 'jquery-effects-pulsate', '/wp
$scripts->add( 'jquery-effects-scale', '/wp-i
$scripts->add( 'jquery-effects-shake', '/wp-i
$scripts->add( 'jquery-effects-slide', '/wp-i
$scripts->add( 'jquery-effects-transfer', '/w

$scripts->add( 'jquery-ui-accordion', '/wp-in
$scripts->add( 'jquery-ui-autocomplete', '/wp

Yes, I copied a rectangle. :)
The unofficial naming scheme is: main library first, then package, then sub-package, all separated by hyphens.
If you follow this scheme – and other developers too! – you lower the risk to enqueue the same library as another plugin just with another name.
Unfortunately, even in core you can find exceptions: 'suggest' and 'schedule' are using jQuery …


text:
Q: "No such host is known." error when publishing bot with LUIS AI to Azure but working fine locally I have hosted a bot in Azure and when debugging with ngrok via bot emulator I get an error stating: No such host is known. I've had such an experience with the bot before, and it meant that the LUIS AI configuration, specifically the LuisAPIHostName value, was not written in the right format in appsettings.json.
As it turned out, back then when the app wasn't even hosted, the problem was that I was given an endpoint from the hosted LUIS service, https://<your.region>.api.cognitive.microsoft.com/, but I only needed to use <your.region> as the value for LuisAPIHostName and the app started working because the full Endpoint was written in the Luis Recognizer (code from Microsoft docs, link provided below) with string interpolation.
Back to the current issue, I tried to isolate the problem by bypassing the LUIS logic in my app, and published it again, and the bot started working just fine in Azure Web Chat.
So, I'm guessing the problem may be with the LUIS configuration. But if it works locally with the previous solution, the LUIS service is hosted in the same subscription as the bot, what does it take to make it work on Azure? I tried a few combinations for LuisAPIHostName, including the whole string provided by Azure and adding an extra "/" at the end, but that didn't change a thing…
The bot is written with:
v4.13.0 Bot Builder libraries
.NET Core 3.1 framework
In Azure hosted as a Web App Bot, with a corresponding AppService
UPDATE:
Adding how LUIS is configured in my app
Recognizer in BotServices can be found at Microsoft LUIS docs
public BotServices(IConfiguration configuration)
    {
        // Read the setting for cognitive services (LUIS, QnA) from the appsettings.json
        // If includeApiResults is set to true, the full response from the LUIS api (LuisResult)
        // will be made available in the properties collection of the RecognizerResult

        var luisApplication = new LuisApplication(
            configuration["LuisAppId"],
            configuration["LuisAPIKey"],
           $"https://{configuration["LuisAPIHostName"]}.api.cognitive.microsoft.com");

        // Set the recognizer options depending on which endpoint version you want to use.
        // More details can be found in https://learn.microsoft.com/en-gb/azure/cognitive-services/luis/luis-migration-api-v3
        var recognizerOptions = new LuisRecognizerOptionsV2(luisApplication)
        {
            IncludeAPIResults = true,
            PredictionOptions = new LuisPredictionOptions()
            {
                IncludeAllIntents = true,
                IncludeInstanceData = true
            }
        };

        SampleQnA = new QnAMaker(new QnAMakerEndpoint
        {
            KnowledgeBaseId = configuration["QnAKnowledgebaseId"],
            EndpointKey = configuration["QnAEndpointKey"],
            Host = configuration["QnAEndpointHostName"]
        });

        Dispatch = new LuisRecognizer(recognizerOptions);
    }

    public LuisRecognizer Dispatch { get; private set; }
    public QnAMaker SampleQnA { get; private set; }
}

How services are called from the bot, can be found at Microsoft docs
//First, we use the dispatch model to determine which cognitive service(LUIS or QnA) to use.
var recognizerResult = await _botServices.Dispatch.RecognizeAsync(turnContext, cancellationToken);

// Top intent tell us which cognitive service to use.
var (intent, _) = recognizerResult.GetTopScoringIntent();

// Next, we call the dispatcher with the top intent.
await DispatchToTopIntentAsync(turnContext, intent, recognizerResult, cancellationToken, botUser);

A: It looks like the LUIS application isn't public.
Check for this in the LUIS portal:

UPDATE: Added the LUIS configuration page in Azure portal

To get the api keys and hostname, you have to check the Keys and Endpoint section on your LUIS PUBLISHING resource in Azure (you shouldn't use the AUTHORING resource, b/c it has a limited request count and you might deplete it).

A: In the Azure hosted bot App Service (not the Web App bot), there is a configuration tab on the left and by default once clicked it selects the Application settings tab on the right (see img)

I created these keys and endpoints as I was creating the LUIS AI service.
As it turns out, Application Settings in Azure overrides appsettings.json or web.config (what have you) as stated here. So if the values are correct in your appsettings file but are different from the Application settings in Azure, the app chooses the ones in Azure.
Because in the recognizer I had string interpolation, I just wrote the region from the LUIS endpoint, and in Azure for LuisAPIHostName I had <your.region>.api.cognitive.microsoft.com. In the end the Endpoint would look like https://<your.region>.api.cognitive.microsoft.com.api.cognitive.microsoft.com/
This is why it worked locally, but not when hosted in Azure.

A: I got that error because I was incorrectly concatenating the Uri.
Example:
string endPointUrl: "https://sampleresource-authoring.cognitiveservices.azure.com";
var uri = $"{endPointUrl}luis/authoring/v3.0-preview/apps....";

And the error gave me: "No such host is known"
the error is that I was missing: "/" after {endPointUrl}, where it should be like this:
var uri = $"{endPointUrl}/luis/authoring/v3.0-preview/apps....";

I would recommend that you check your final url. I hope it helps.


text:
Q: HTML CSS :hover only border color not changing and only effects inner elements? So I'm making some download links for my website. But when i hover over the elements inside, the border-color of the div doesnt change. And the only time anything changes is when i hover over the elements inside the div. So how can i make it so the border-color does change and so it detects whether I'm hovering over the div not the elements inside it

div.db {
    font-size: 30px;
    color: white;
    margin: 5px;
    float: left;
    border-style: solid;
    border-color: blue;
    text-align: center;
}

.db :hover {
    border-color: red;
}
div.db :not(:hover){
    border-color: blue;
}

div.db img {
    width: 220px;
    height: 180px;
}

div.db a {
    text-decoration: none;
}

Downloads:

Windows

Linux

Apple

the downloads div class doesnt have any code for it.

A: Wrong syntax caused by extra spaces.
Using .db: hover is incorrect, change it to .db:hover
and so on...

div.db {
    font-size: 30px;
    color: white;
    margin: 5px;
    float: left;
    border-style: solid;
    border-color: blue;
    text-align: center;
}

.db:hover {
    border-color: red;
}
div.db:not(:hover){
    border-color: blue;
}

div.db img {
    width: 220px;
    height: 180px;
}

div.db a {
    text-decoration: none;
}

Downloads:

Windows

Linux

Apple


text:
Q: Continuous database backups? I have the following scenario:
Our system is running a SQL Server Express 2005 database locally (on each users desktop, if you will). The system is storing a lot of production data from a machine. There are high demands on the safety of the data, and doing a backup each night, or even each hour is not enough. We need a backup strategy that will ensure almost instantaneous/continuous backup of the database.
Is there anyone out there that has successfully implemented a system similar to this, and/or has got some ideas of how to accomplish it? The only thing I can think of right now is to have mirrored drives (raid) to hold the data, but that would be complicated and expensive.
I would appreciate any and all thoughts on this, since it is a real issue for me and my company. Thanks in advance!
Update:
I was not clear enough in my description of the scenario. The system is storing data in a vehicle that has no connection to anything. A centralized database is therefor not possible. Neither can we use a standard/enterprise version of SQL Server, since it would be to expensive (each vehicle would need a license). Thanks for your input!

A: Switch your database into "Full" recovery mode. Do full backup every night and do delta backup after major user action. The delta backups can be done to the flash memory or different hard-drive, and all data can be synchronized with server when online.
Another simple way is to trace all user changes and important data in a text file that stored on a separate drive. If SQL database crashes the user or other operator can repeat steps to restore data.

A: One way I've seen this done is by using DoubleTake.

A: I will assume that a central database on a server is not feasible because your systems are running standalone and are not connected to anything.  So this is what I would do
Set up RAID on the computer.  This insures you against simple disk failure.
Any SQLSever database can be recovered to the point of the last commited transaction if you have a full database backup and a set of transaction logs available.  Basically you simply restore the last full backup then apply the transaction logs going forward.  See these links.
http://www.enterpriseitplanet.com/storage/features/article.php/11318_3776361_3
https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/datacenter/?p=132
So what you need to do is set up a periodic full backup of both the database and transaction logs, and more regular transaction log backups (and ensure that your transaction log can never run out of space).
In the event of failure you restore the last full backup, then apply the transaction logs going forward.
Myself, if these are critical systems, I would be inclined to add an additional drive to the system and make sure that the backups are copied over to that.  This is because as good as raid is it does sometimes have issues - raid controllers fail, disks get wiped accidentally in parallel, disk failures go unnoticed so your just running on one disk etc. If you ensure backups are copied to a separate disk then you can always recover to the last transaction log backup.  You should also ensure tape backups of course, but they are generally a last resort in the event of trouble.
If for some reason you cannot set up raid then you should still install a second disk, but place the database file on one drive and the transaction log on the other and copy backups to both disks.  In the event of failure of the C drive, or some other software issue crashing the database you can still recover to the last commited transaction.  Failure on the D drive limits you to the last transaction log backup (Oracle used to allow you to mirror the transaction log from the database, which again would completely cover you, but I don't think this facility exists in SQL Server)
If you are looking for a scheduler for SQL Server Express (which doesn't come with one) then I've been using SQLScheduler quite happily without problems, and it's free.

A: Raid isn't that expensive, but it is also not the best option. If you really want high availability data you should upgrade to sql server standard on a remote server where each user connects to and use transaction based replication to an sql server (express) instance on another machine. Raid doesn't always protect you from dataloss. If the data is that important for you then the costs should not be that much of an issue.
Update in response to the question update.
If you can't use remote servers then there a couple of options:

*

*You write a trigger which initiates a backup script on each insert or update and stores it on a seperate harddrive.

*You use raid. But beware that if the raid controller fails that you still got a problem.

A: The most obvious answer would be to ditch SQL Server Express running locally and use a single source for your data (such as a standard SQL server install on a central storage location). Unless your system requires individual back ups of every single person's own individual instance of SQL Server Express.
If your requirements are so stringent as to call for instantaneous backups on every operation, you should definitely think about a different method of storage than local instances of SQL Server Express.

A: Wouldn't it be easier to just use one centralized SQL Server and back that up every hour or so? If you truly need instantaneous backup, your company (which seems not to want to spend money by installing Express on each machine) will need to spring for two servers and two SQL Server Enterprise licenses to implement Mirroring.

A: RAID is not expensive. Use RAID to protect against hard drive failure. You also need monitoring though. No point in having this if you let both drives fail.
Also, implement hourly incremental backups, then daily incremental backups and finally weekly full backups.
You need all of these strategies working together because they protect against different things. RAID does not protect against human or coding errors destroying data. Hourly and weekly backups don't protect against hard drive failure.


text:
Q: protractor elementExplorer I'm trying to use protractor elementExplorer and not sure why I can't do it (I'm using Mac).
according to the documentation - http://angular.github.io/protractor/#/debugging I'm going to the protractor directory (use/local/bin) and type
node ./bin/elementexplorer.js

I'm getting the following error:
module.js:340
throw err;
      ^
Error: Cannot find module '/usr/local/bin/bin/elementexplorer.js'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3

any help?
thanks.

A: You need to cd into the protractor directory:
cd node_modules/protractor
node ./bin/elementexplorer.js

where node_modules in your case should be under /usr/local/lib/.

A: If you have protractor installed globally as the docs at https://angular.github.io/protractor/#/ suggest you should be able to start protractor --elementExplorer anywhere and then issue commands such as browser.get('http://angular.github.io/protractor/#/ as per the api at https://angular.github.io/protractor/#/api
You can check your protractor install and version by doing protractor --version
Current verison is 3.0.0

A: Since you are already in protractor/bin directory try,
node elementExplorer.js

The best way to access elementExplorer is (if protractor installed globally):
protractor --elementExplorer

(If protractor installed in a specific folder), try:
Go to the specific folder, then:
node_modules/.bin/protractor --elementExplorer

A: If you are in Windows, try C:\Users\{username}\AppData\Roaming\npm\node_modules\protractor\bin
Here you can find elementexplorer.js
You can do node elementexplorer.js it will start selenium standalone server and it will open empty browser.. Here you can test your desired web page.


text:
Q: Outer Join in Linq or EF I have two tables
T1     T2
-------------
id1    id2
-----------
1      3
2      5
3
4

I want to get a outer join so that I get 1,2,3,4,5
I am using following Linq command
   var newList = (from i in T1
                   join d in T2
                   on i.id1 equals d.id2 into output
                   from j in output.DefaultIfEmpty()
                   select new {i.id});

The out put I get i 1,2,3,4 missing 5. How can I get it to give me newList 1,2,3,4,5
Help Please

A: There is no direct alternative to OUTER JOIN in LINQ. You have to solve it like this:
Within query you wrote only the i's that also exists in T2 because of the on i.id1 equals d.id2.
var result = T1.Select(item => item.id1).Union(T2.Select(item => item.id2));

A: You could use Union like:
var result = T1.Union(T2);
You can refer to this C# linq union question


text:
Q: Why do so many primes such that $2^q\equiv4\pmod{q+2}$ end in $7$? Originally, I was investigating the divisibility of $p^q-q^p$ by $p+q$ for primes $p,q$, but I quickly discovered that even $p=2$ is not easy at all.
When $p=2$, we have $2^q-q^2\equiv0\pmod{q+2}\iff2^q\equiv4\pmod{q+2}$, or equivalently, $\operatorname{ord}_{q+2}(2)\mid(q-2)$.
We know that $q$ cannot be $3$ modulo $10$, as otherwise it is necessary that $2^{10k+3}\equiv4\pmod5$, but this is a contradiction.
We also see that $q=5$ satisfies the congruence, but subsequent solutions up to $\approx10^{11}$ seem to display a pattern.
\begin{array}{cccccc}\hline\small6462647&\small259195007&\small1654549877&\small22442226767&\small41344905167&\small53085400877&\small86123562527\\\small130647917&\small277628447&\small12746032157&\small\color{red}{22677320759}&\small46649950877&\small77652121367&\small\color{red}{105780380351}\\\small218206487&\small1043030837&\small19745250527&\small26427995687&\small46726848677&\small82396696727&\small149661517007\\\hline\end{array}
Why are solutions with $7$ modulo $10$ so common?


text:
Q: Symfony Prod Cache clear returns error: The service "validator.builder" has a dependency on a non existent service "validat or.mapping.cache.apc" When trying to clear cache on prod I get:
The service "validator.builder" has a dependency on a non existent service "validat or.mapping.cache.apc".
Symfony app is on ver 3.0.9. It works well in development on Dev Environment.
How do  I fix this?

A: I found the problem for anyone who bumps into this.
Somehow the config file created by Symfony when I created the project had in the config_prod.yml the line
framework:
    validation:
        cache: validator.mapping.cache.apc

The cache needed to be changed to
        cache: validator.mapping.cache.doctrine.apc


text:
Q: Dynamic programming: how to design algorithm for when there are two factors to consider? I have the following problem and I only have a slight idea about it:
Consider a tape storage problem. Given n files of length l1,...,ln and frequencies with which they are accessed f1,...,fn, where sum of all frequencies is 1 and 0<fi<1. "Optimal" means to minimize the average retrieval time of these files. For example, if you have two files, each of length 10, 4 and frequency 0.8, 0.2, if store file 1 first, the average retrieval time is 10 x 0.8 + 14 x 0.2 = 10.8.
Design an algorithm to find the optimal order and prove that it works.
My thoughts:
Larger frequencies & larger length in front of the order, but which factor should be given a higher priority?

A: There is no need for Dynamic Programming for this problem. It is a simple sorting problem, with a slight twist.
Find frequency / length for each file. This gets you, how frequent is each unit length access for the file. Sort these in descending order since each file is "penalized" by the previous file's length.
Proof:
Assume that the order is fixed somehow. Then, swapping any two adjacent files will not affect any of the other li * fi other than the location of the swap. Call the left one in the swap x and other one y == x+1. Then, the change in average retrieval time is ly*fx - lx*fy. If fx/lx < fy/ly, then ly*fx < lx*fy which means ly*fx - lx*fy < 0, which means that the average retrieval time decreased. This means that we are at an advantage to do this swap. We keep doing such swaps whenever fx/lx < fy/ly and we will get to a point when this is no longer possible. This must be the optimal answer.
Swapping adjacent things whenever left < right, is similar to bubble sorting in descending order, so we can just generally use any sort instead.

A: just let files of length as ascending(l1<l2<l3<l4<...<ln) and frequencies as descending orders.
because
average retrieval time =
ART1 =
(l1)*f1 +
(l1+l2)*f2 +
(l1+l2+l3)*f3 +
...

let assume we swap l1 and l2. so we broke the ascending order of length.
ART2 =
(l2)*f1 +
(l2+l1)*f2 +
(l1+l2+l3)*f3 +
...

if it makes (ART1 < ART2), it made the situation worse.
look at this.
we should check ART1-ART2 < 0?
ART1-ART2 =
{ (l1)*f1 + (l1+l2)*f2 }
-
{ (l2)*f1 + (l2+l1)*f2 }

= l1*f1-l2*f1
= (l1-l2)*f1.

from assumption l1<l2, we conclude ART1-ART2<0.
so lengths should be ascending order.
similarly you can probe that frequencies should be descending orders if you swap f1 and f2.

A: DP will work but is not a good solution of this problem because while a brute-force method checking all options take O(n!) time, a DP method takes time proportional to the number of different subproblems. Say, firstly we make all possible n choices, then we would be left with n subproblems of size (n-1) all different. For DP to work, optimal solution to main problem should result from optimal solution to subproblems. Now, for size (n-1) problems, lets say we know the solutions, so
total average retreival time = (length of first chosen file * 1) + (retrieval time for (n-1) size problem)

Because of above equation, overlapping subproblems will emerge, but total number of distinct subproblems would be
nC1 + nC2 + ... nCn = 2^n

still exponential.
So, DP will reduce the complexity, but nature of problem would still be exponential.


text:
Q: How to follow the progress of a linux command? I am currently working with a large data set where even the file format conversion takes at least an hour per subject and as a result I am often unsure whether my command has been executed or the program has frozen. I was wondering whether anyone has a tip to how to follow the progress of the commands/scripts I am trying to run in linux?
Your help will be much appreciated.

A: In addition to @basile-starynkevitch answer,
I have a bash script that can measure how much file did you processed in percents.
It watch into procfs get current position from fd information (/proc/pid/fdinfo), and count this in percents, relative to total file size.
See https://gist.github.com/azat/2830255
curl -s https://gist.github.com/azat/2830255/raw >| progress_fds.sh \
&& chmod +x progress_fds.sh

Usage:
./progress_fds.sh /path/to/file [ PID]

Сan be useful to someone

A: If the long-lasting command produces some output in a file foo.out, you could do watch ls -l foo.out or tail -f foo.out
You could also list /proc/$(pidof prog)/fd to find out the opened files of some prog

A: You can follow the syscalls of a program by using strace, which will enable you to follow the open calls.

A: You can use verbose output, but it will slow things down even more.

A: I guess there can't be a general answer to that, it just depends on the type of program (that doesn't even has to do anything with Linux, see the "halting problem").
If you happen to use a pipe during the conversion I find the pv(1) tool pretty helpful. Even if pv can't know the total size of the data it helps to see if there is actual progress and how good the datarate is. It isn't part of most standard installations though and probably has to be installed explicitly.


text:
Q: A follow up to "Showing that a sequence of a cofibration is exact" After reading through the explanation that Tyrone gave on this page Showing that a sequence of a cofibration is exact.
I am curious on how one would use that information to fully prove that if $A \rightarrow B$ is a cofibration with cofiber $C$, then for any pointed space $X,$ the sequence $[C,X] \rightarrow [B,X] \rightarrow [A,X]$ is an exact sequence of pointed sets.

A: Recall that $C_f$ is obtained from $B$ and $CA:=A\times[0,1]/A\times\{1\}$ by identifying $(a,0)\in CA$ with $f(a)\in B$. Next, recall that Tyrone defines a cofiber sequence as follows

A cofiber sequence is a sequence $A\xrightarrow fB\xrightarrow gC$, together with an homotopy $H:gf\rightarrow *$ such that the induced map $\chi:C_f\rightarrow C$ is an homotopy equivalence.

In particular, since we're looking at homotopy classes of maps, precomposition with $\chi$ induces an isomorphism $$[C,X]\xrightarrow\simeq [C_f,X]$$ and the sequence $[C,X]\rightarrow [B,X]\rightarrow [A,X]$ is equivalent to $[C_f,X]\rightarrow[B,X]\xrightarrow{f_*}[A,X]$, so we only need to show exactness of the latter to derive exactness of the former.
It should be clear now how you conclude exactness from this property of $C_f$: Since $C_f$ is obtained by gluing $B$ and $CA$, a morphism $C_f\rightarrow X$ is equivalent to morphisms $\beta:B\rightarrow X$ and $\alpha:CA\rightarrow X$ that are compatible with the way $B$ and $CA$ are glued, meaning $$\beta(f(a))=\alpha(a,0)$$Moreover, since $CA$ is obtained by taking $A\times I$ and collapsing $A\times\{1\}$ to a point, a morphism $\alpha:CA\rightarrow X$ is equivalent to a morphism $H:A\times I\rightarrow X$ such that $H(-,1)=*$ (in this general scenario, $*$ need not be the point of $X$, but in the proof of exactness it will be), hence an homotopy between $*$ and $H(-,0)=\alpha(-,0)=\beta\circ f$. Do you see how to conclude?


text:
Q: Number of ways to divide a group of n people into groups of size m to m-1 A group of n people will be partitioned into groups given a maximum group size of m like so:
There are $⌈\frac{n}{m}⌉$ amount of groups in total. A person is added to the first group and then the second group and so on in a loop until there is no more people to add. How many combinations of groups can be created?
Or more formally:
How many different partitions does the set $\{1,…,n\}$ have when there are $⌈\frac{n}{m}⌉$ subsets in total where $⌊\frac{n}{⌈\frac{n}{m}⌉}⌋$ of them has a cardinality of $m$ and $n\%⌈\frac{n}{m}⌉$ of them has a cardinality of $m-1$?
Where $n≥m⋅2-1≥3$
$\%$ is the modulos operator
By combination I mean the order of people in each group and the order of groups does not matter.


text:
Q: How do I convert List[String] to List[ServerAddress]? I'm new to Scala and am struggling with this silliest thing.
I have a List[String] and I want to parse the list and produce a new List[ServerAddress] (ServerAddress is a mongo thing.  What I am conceptually trying to do is convert a List of one Type to a different Type).  How do I do this?  My current attempt fails to populate my List[ServerAddress]
scala> val seeds: List[String] = List( "bobk-mbp.local", "bobk-mbp.local:27018" )
seeds: List[String] = List(bobk-mbp.local, bobk-mbp.local:27018)

scala> val serverAddrs = List[ServerAddress]()
serverAddrs: List[com.mongodb.casbah.Imports.ServerAddress] = List()

scala> for (seed <- seeds ) { new ServerAddress(seed) :: serverAddrs }

scala> serverAddrs
res12: List[com.mongodb.casbah.Imports.ServerAddress] = List()

Brother, could you spare a clue?

A: You could do this:
val serverAddrs = seeds.map((s) => new ServerAddress(s))

Edit:
Here is a more concise way:
val serverAddrs = seeds.map(new ServerAddress(_))

A: The :: operator creates a new list rather than mutating the old one, so you're just creating a bunch of one-element lists and then discarding them.
The idiomatic way to do what you want in a functional language like Scala is just to map the list:
val serverAddrs = seeds.map( s => new ServerAddress(s) )

A: See @Chuck's comments about ::.
Here's a working for expression which is syntactic sugar for map:
scala> val seeds: List[String] = List( "bobk-mbp.local", "bobk-mbp.local:27018" )
seeds: List[String] = List(bobk-mbp.local, bobk-mbp.local:27018)

scala> class ServerAddress(address: String)
defined class ServerAddress

scala> for(seed <- seeds) yield new ServerAddress(seed)
res0: List[ServerAddress] = List(ServerAddress@1985828e, ServerAddress@c3e45b9)


text:
Q: I am Global Admin in Azure but I cannot see any Billing Scope I have a client that gave me Global Admin to set up a new infrastructure but I cannot see any Billing Scope, therefore I cannot create subscriptions or do much at all.
In another client I can see a tick box over the Billing Scopes that allows me to see all Billing Scopes as Global Admins but the tickbox is not there in this client.
The current owner of the account is the finance director of the company, therefore I don't have easy access to his account.
Any ideas?


text:
Q: exporting svg image from matlab surface plot I need some to produce some publication-quality figures. I first export the figures from matlab in .svg format, and then I do some post-processing in inkscape. I am no problem with figures generated using plot or scatter, but when I export figures generated using surf (in view(2)), I run into problems. If I use plot or scatter, I am able to ungroup and process various parts like the title, axes, scattered points, lines, etc. in inkscape. For surf, however, matlab just exports one single figures with all various parts grouped into one single unit. I can't separate individual part, and when I zoom very close I can actually see the bitmap resolution for the axes and titles (if I use plot, the titles and axes have 'infinite' resolution when I zoom very close). I am fine with the surface plot having finite resolution, but I need to at least be able to process the axes and titles (which I currently cannot do). What should I do so that I can 'separate' the title and axes from the main plot, just like figures generated from plot and scatter?

A: I used to use Inkscape for my scientific publications as well, but I found that a lot of the time you can get better results with pgfplots in latex, together with the matlab2tikz matlabscript. There's a ton of resources about this online, but here's how my workflow would look adopted to your surf situation. I have macOSX with latex, matlab and matlab2tikz installed. Will work with little to no modifications on linux.
In Matlab:
surf(peaks(25))
matlab2tikz('plot.tikz')

Then I have the following bash-script (just a script in the same folder as the image, which is executed by mere double-click). (Needs to be chmod-ed as an executable for that).
#!/bin/bash

cd ~/Desktop
rm *.eps

cat > plot.tex << EOF
\documentclass{standalone}
\usepackage{pgfplots}
\pgfplotsset{max space between ticks=50}
\pgfplotsset{scaled ticks = false}
\pgfplotsset{compat=1.6}
\pgfplotsset{xticklabel style={/pgf/number format/fixed}}
\pgfplotsset{yticklabel style={/pgf/number format/fixed}}
\begin{document}
\input{plot.tikz}
\end{document}
EOF

pdflatex plot.tex
pdf2ps   plot.pdf
ps2eps   plot.ps

Note that the row cd ~/Desktop above should be changed as to reflect which folder the script is supposed to be run from (a bit crappy, but needed since Finder doesn't properly pass along the folder from a program is executed, afaik).
This yields high-quality images in eps or pdf or what you like, with a ton of settings for axes and ticks etc. And it all uses native latex fonts.
Edit:
Recently I've begun to use patch() in matlab and then export it to tikz in the same manner as above, with great results. That's another suggestion!

A: I stumbled across this question, since I encountered the same problem.
As mentioned by @vindarmagnus, it is possible to use tikz and get rather nice results. However, tikz experiences problems with large data sets in my experience as present when using surf etc..
Solution, that worked for me:
Change the renderer to painters and the exported .svg file will retain its vectorgraphic properties when opened e.g. in inkscape:
figure('Renderer','Painters');

A: You can use also:
set(gcf,'Renderer','Painters')


text:
Q: Flex Mobile - TileLayout performance issues
I'm building mobile application for tablet devices.
I have huge performance issue with List component with tile layout.
I'm showing pages with around 20-24 items on the screen and the user can scroll trough the pages. Unfortunately the list component generates the new page extremely slow.
Overall I tested standalone List with tile layout and it's performance in every scenario is extremely slow (I have tested it on iPad1 & iPad2 ).
Please advice if you know some solution to the problem.
Thanks.

A: Generally the Tile is very slow in flex. This is because it allows variable size for each item renderer and the measure / updateDisplayList takes a lot of time.

*

*I would suggest you use a custom (own made) tile list and drop the flex component in this case. If you use it just for layout you can manually/programaticaly compute the positions of each item in the tile and move it to right x/y pixel.

*Also be careful with effects! They may work ok in an AIR simulator or in the desktop browser but eat a lot of resources on mobile devices.

*If you still want to go for the flex tile component, and not create your own tile control, then I suggest you use fixed with renderers for all items you display inside, and also specify columnWidth and rowHeight inside the TileList declatation. This may improve a little the performance... :)
Also positing some sample code does not hurt. Maybe you are doing somethig wrong somehwre... donno: extra invalidation, bad rendering etc...!

A: Its been a while so I don't remember specifics. Here is the code that I used but please keep in mind, that the components I wrote are are for specific purpose and include some bad practices to accomplish a specific problem for very short time. However I hope to be useful.
pagedList
package components.pagedList
{
    import components.pagedList.vo.PageItemVo;
    import mx.collections.ArrayCollection;
    import mx.collections.IList;
    import mx.core.IFactory;
    import mx.core.UIComponentGlobals;
    import mx.events.CollectionEvent;
    import mx.events.CollectionEventKind;

    import spark.components.List;
    import spark.layouts.HorizontalLayout;

/**
 *
 */
public class PagedList extends List
{

    //--------------------------------------------------------------------------
    //
    //  Constructor
    //
    //--------------------------------------------------------------------------

    public function PagedList()
    {
        super();
    }

    //--------------------------------------------------------------------------
    //
    //  Variables
    //
    //--------------------------------------------------------------------------

    /**
     * Dimentions for the inner items should be specifyed because
     * this component needs to know how many items can be placed in
     * one page, but don't have the ability to create this items.
     * Default value is 1 to avoid division by zero.
     */
    public var innerItemWidth:Number = 1;

    public var innerItemHeight:Number = 1;

    /**
     * When inner item dimentions are set the component calculates how many items
     * (per row and col) can be shown on one scren and pass these data to the page
     * trough the dataProvider for the page.
     */
    private var pageRowCount:int = 1;

    private var pageColCount:int = 1;

    /**
     * Count of the items that can fit in one page.
     * This count is used to slice the data into picies
     * with the same length.
     */
    private var itemsPerPage:int = 0;

    /**
     * Original data provider is saved here so we can re-slice it when
     * size change occure and listen for data change event.
     *
     * TODO: implement the data chage listener
     */
    private var _originalDataProvider:IList;

    /**
     *
     */
    private var cachedUnscaledWidth:Number = 0;
    private var cachedUnscaledHeight:Number = 0;

    //----------------------------------
    //  Custom tiles data
    //----------------------------------

    private var _customTilesData:Array;

    private var customTilesDataChanged:Boolean;

    public function set customTilesData(value:Array):void
    {
        _customTilesData = value;
        customTilesDataChanged = true;
        invalidateProperties();
    }

    public function get customTilesData():Array
    {
        return _customTilesData;
    }

    //----------------------------------
    //  dataProvider
    //----------------------------------

    private var originalDataProviderChanged:Boolean;

    [Inspectable(category="Data")]
    /**
     *
     */
    override public function set dataProvider(value:IList):void
    {
        if (_originalDataProvider)
            _originalDataProvider.removeEventListener(CollectionEvent.COLLECTION_CHANGE, originalDataProvider_collectionChangeHandler);

        originalDataProviderChanged = true;

        if (value)
            value.addEventListener(CollectionEvent.COLLECTION_CHANGE, originalDataProvider_collectionChangeHandler, false, 0, true);

        _originalDataProvider = value;
        updatePagedData();
    }

    /**
     *
     */
    private function originalDataProvider_collectionChangeHandler(event:CollectionEvent):void
    {
        //trace('data changed:', event.kind, 'location:', event.location);
        if (event.kind == CollectionEventKind.REPLACE)
        {
            updateReplacedItem(event.location);
        }

    }

    /**
     *
     */
    private function updateReplacedItem(index:int):void
    {
        if (dataProvider)
        {
            var pageNumber:int = int(index / itemsPerPage);
            var itemIndex:int = index - (pageNumber * itemsPerPage);
            if (dataProvider[pageNumber])
            {
                var pageData:PageItemVo = PageItemVo(dataProvider[pageNumber])
                pageData.data[itemIndex] = _originalDataProvider[index];
            }
        }
    }

    //----------------------------------
    //  innerItemRenderer
    //----------------------------------

    private var _innerItemRenderer:IFactory;

    private var innerItemRendererChanged:Boolean;

    public function set innerItemRenderer(value:IFactory):void
    {
        _innerItemRenderer = value;
        innerItemRendererChanged = true;
        invalidateProperties();
    }

    public function get innerItemRenderer():IFactory
    {
        return _innerItemRenderer;
    }

    //----------------------------------
    //  gaps
    //----------------------------------

    /**
     *
     */
    public function set verticalGap(value:Number):void
    {
        _verticalGap = value;
        gapsChanged = true;
        invalidateProperties();
    }

    public function get verticalGap():Number
    {
        return _verticalGap;
    }

    /**
     *
     */
    public function set horizontalGap(value:Number):void
    {
        _horizontalGap = value;
        gapsChanged = true;
        invalidateProperties();
    }

    public function get horizontalGap():Number
    {
        return _horizontalGap;
    }

    private var _verticalGap:Number;

    private var _horizontalGap:Number;

    private var gapsChanged:Boolean;

    //--------------------------------------------------------------------------
    //
    //  Overridden methods
    //
    //--------------------------------------------------------------------------

    protected function updatePagedData():void
    {
        if (_originalDataProvider)
        {
            var pagedData:IList = createPagedData(_originalDataProvider);
            super.dataProvider = pagedData;
            invalidateProperties();
        }
    }

    private function createPagedData(value:IList):IList
    {
        var nestedData:Array = [];
        var dataList:Array = value.toArray();
        var pageData:PageItemVo;
        if (itemsPerPage)
        {
            var customTilesCount:int = customTilesData ? customTilesData.length : 0;
            var normalItemsPerPage:int = itemsPerPage - customTilesCount;
            while (dataList.length)
            {
                pageData = new PageItemVo();
                var data:Array = dataList.splice(0, normalItemsPerPage);
                for (var i:int = 0 ; i < customTilesCount ; i++)
                {
                    data.push( customTilesData[i] );
                }
                pageData.data = new ArrayCollection( data );
                pageData.colsCount = pageColCount;
                pageData.rowsCount = pageRowCount;
                pageData.itemWidth = innerItemWidth
                pageData.itemHeight = innerItemHeight;
                pageData.horizontalGap = horizontalGap;
                pageData.verticalGap = verticalGap;
                pageData.innerItemRenderer = _innerItemRenderer;
                nestedData.push(pageData);
            }
        }
        return new ArrayCollection(nestedData);
    }

    //----------------------------------
    //  Component lifecycle
    //----------------------------------

    override protected function commitProperties():void
    {
        if (gapsChanged || innerItemRendererChanged || customTilesDataChanged)
        {
            updatePagedData();
            gapsChanged = false;
            innerItemRendererChanged = false;
            customTilesDataChanged = false;
        }
    }

    override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
    {
        super.updateDisplayList(unscaledWidth, unscaledHeight);
        caluclateItemsPerPage(unscaledWidth, unscaledHeight);
        // We have to update the dataProvider so it can re-slice the pages
        // in case of orientation rotation or some other resize
        if (_originalDataProvider)
            if ( cachedUnscaledWidth != unscaledWidth || cachedUnscaledHeight != unscaledHeight )
                dataProvider = _originalDataProvider;

        cachedUnscaledWidth = unscaledWidth;
        cachedUnscaledHeight = unscaledHeight;
    }

    protected function caluclateItemsPerPage(unscaledWidth:Number, unscaledHeight:Number):void
    {
        var myLayout:HorizontalLayout = HorizontalLayout(layout);
        var horizontalPaddings:Number = myLayout.paddingLeft + myLayout.paddingRight;
        var verticalPaddings:Number = myLayout.paddingTop + myLayout.paddingRight;
        pageRowCount = (unscaledHeight - verticalPaddings) / (innerItemHeight + verticalGap);
        pageColCount = (unscaledWidth - horizontalPaddings) / (innerItemWidth + horizontalGap);
        itemsPerPage = pageRowCount * pageColCount;
    }

}
}

PageItemRenderer
package skins.pagedList
{
    import components.pagedList.vo.PageItemVo;

    import flash.display.DisplayObject;

    import mx.collections.ArrayCollection;
    import mx.core.IDataRenderer;
    import mx.core.IFactory;
    import mx.core.UIComponent;
    import mx.events.FlexEvent;

    import spark.components.IItemRenderer;

//--------------------------------------
//  Events
//--------------------------------------

/**
 *  Dispatched when the data property changes.
 *
 *
When you use a component as an item renderer,
 *  the data property contains the data to display.
 *  You can listen for this event and update the component
 *  when the data property changes.

 *
 *  @eventType mx.events.FlexEvent.DATA_CHANGE
 */
[Event(name="dataChange", type="mx.events.FlexEvent")]

/**
 *
 * ASDoc comments for this item renderer class
 *
 */
public class PageItemRenderer extends UIComponent
    implements IDataRenderer, IItemRenderer
{

    //--------------------------------------------------------------------------
    //
    //  Constructor
    //
    //--------------------------------------------------------------------------

    public function PageItemRenderer()
    {
        super();
        cacheAsBitmap = true;
    }

    //--------------------------------------------------------------------------
    //
    //  Variables
    //
    //--------------------------------------------------------------------------

    //----------------------------------
    //  data
    //----------------------------------

    /**
     *  @private
     */
    private var _data:PageItemVo;

    private var dataChanged:Boolean;

    [Bindable("dataChange")]

    /**
     *  The implementation of the data property
     *  as defined by the IDataRenderer interface.
     *  When set, it stores the value and invalidates the component
     *  to trigger a relayout of the component.
     */
    public function get data():Object
    {
        return _data;
    }

    /**
     *  @private
     */
    public function set data(value:Object):void
    {
        _data = PageItemVo(value);
        colCount = _data.colsCount;
        rowCount = _data.rowsCount;
        itemWidth = _data.itemWidth;
        itemHeight = _data.itemHeight;
        horizontalGap = _data.horizontalGap;
        verticalGap = _data.verticalGap;
        innerItemRenderer = _data.innerItemRenderer;
        _tilesData = ArrayCollection(_data.data);

        dataChanged = true;

        if (hasEventListener(FlexEvent.DATA_CHANGE))
            dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));

        invalidateProperties();
    }

    //----------------------------------
    //  gaps
    //----------------------------------

    /**
     *
     */
    public function set verticalGap(value:Number):void
    {
        _verticalGap = value;
        gapsChanged = true;
        invalidateProperties();
    }

    public function get verticalGap():Number
    {
        return _verticalGap;
    }

    /**
     *
     */
    public function set horizontalGap(value:Number):void
    {
        _horizontalGap = value;
        gapsChanged = true;
        invalidateProperties();
    }

    public function get horizontalGap():Number
    {
        return _horizontalGap;
    }

    private var _verticalGap:Number = 5;

    private var _horizontalGap:Number = 5;

    private var gapsChanged:Boolean;

    //----------------------------------
    //  itemIndex
    //----------------------------------

    private var _itemIndex:int;

    public function get itemIndex():int
    {
        return _itemIndex;
    }

    public function set itemIndex(value:int):void
    {
        if (value == _itemIndex)
            return;

        invalidateDisplayList();
        _itemIndex = value;
    }

    //----------------------------------
    //  showsCaret
    //----------------------------------

    private var _showsCaret:Boolean = false;

    public function get showsCaret():Boolean
    {
        return _showsCaret;
    }

    /**
     *  @private
     */
    public function set showsCaret(value:Boolean):void
    {
        if (value == _showsCaret)
            return;

        _showsCaret = value;
        invalidateDisplayList();
    }

    //----------------------------------
    //  selected
    //----------------------------------

    private var _selected:Boolean = false;

    public function get selected():Boolean
    {
        return _selected;
    }

    public function set selected(value:Boolean):void
    {
        if (value == _selected)
            return;

        _selected = value;
    }

    //----------------------------------
    //  dragging
    //----------------------------------

    private var _dragging:Boolean = false;

    public function get dragging():Boolean
    {
        return _dragging;
    }

    public function set dragging(value:Boolean):void
    {
        _dragging = value;
    }

    //----------------------------------
    //  label
    //----------------------------------

    private var _label:String;

    public function get label():String
    {
        return _label;
    }

    /**
     *  @private
     */
    public function set label(value:String):void
    {
        _label = value;
    }

    //----------------------------------
    //  item properties
    //----------------------------------

    /**
     * Dimentions for the inner items should be specifyed because
     * this component needs to know how many items can be placed in
     * one page, but don't have the ability to create this items.
     * Default value is 1 to avoid division by zero.
     */
    public var itemWidth:Number = 1;

    public var itemHeight:Number = 1;

    /**
     * When inner item dimentions are set the component calculates how many items
     * (per row and col) can be shown on one scren and pass these data to the page
     * trough the dataProvider for the page.
     */
    public var rowCount:int = 1;

    public var colCount:int = 1;

    private var _tilesData:ArrayCollection;

    private var sizeChanged:Boolean;

    private var _tileContainer:UIComponent;

    /**
     *
     */
    private var innerItemRenderer:IFactory;

    //--------------------------------------------------------------------------
    //
    //  Overridden methods
    //
    //--------------------------------------------------------------------------

    //----------------------------------
    //  Component lifecycle
    //----------------------------------

    override protected function commitProperties():void
    {
        super.commitProperties();

        if (dataChanged)
        {
            dataChanged = false;
            createTiledContent();
        }
        if (gapsChanged)
        {
            createTiledContent();
        }
    }

    override protected function measure():void
    {
        super.measure();

        measuredMinHeight = measuredWidth =  parent.width;
        measuredMinHeight = measuredHeight = parent.height;
    }

    override protected function updateDisplayList(unscaledWidth:Number,
                                                  unscaledHeight:Number):void
    {
        super.updateDisplayList(unscaledWidth, unscaledHeight);
        var tileCntWidth:Number = colCount * (itemWidth + horizontalGap);
        _tileContainer.x = 0.5 * (unscaledWidth - tileCntWidth);
    }

    //--------------------------------------------------------------------------
    //
    //  Methods
    //
    //--------------------------------------------------------------------------

    protected function createTiledContent():void
    {
        clearChildren();
        _tileContainer = new UIComponent();
        var itemsCount:int = _tilesData.length;
        var row:int, col:int, item:DisplayObject;
        for (var i:int = 0 ; i < itemsCount ; i++ )
        {
            row = int( i / colCount );
            col = i - row * colCount;
            if (_tilesData[i].hasOwnProperty("itemFactory"))
            {
                item = IFactory(_tilesData[i].itemFactory).newInstance();
            }
            else
            {
                item =  innerItemRenderer.newInstance();
            }
            Object(item).data = _tilesData[i];
            item.x = col * (itemWidth + horizontalGap);
            item.y = row * (itemHeight + verticalGap);
            _tileContainer.addChild(item);
        }
        addChild(_tileContainer);
        invalidateSize();
        invalidateDisplayList();
    }

    //--------------------------------------------------------------------------
    //
    //  Helper methods
    //
    //--------------------------------------------------------------------------

    private function clearChildren():void
    {
        var numChildren:int = this.numChildren;
        for (var i:int = 0 ; i < numChildren ; i++ )
        {
            this.removeChildAt(0);
        }
    }

}
}

PagedItemVo
package components.pagedList.vo
{
    import flash.events.EventDispatcher;
    import flash.events.IEventDispatcher;

    import mx.collections.IList;
    import mx.core.IFactory;

    [Bindable]
    public class PageItemVo extends EventDispatcher
    {

        public var data:IList;

        public var rowsCount:int;

        public var colsCount:int;

        public var itemWidth:Number;

        public var itemHeight:Number;

        public var verticalGap:Number;

        public var horizontalGap:Number;

        public var innerItemRenderer:IFactory;

        public function PageItemVo(target:IEventDispatcher=null)
        {
            super(target);
        }
    }
}

ScrollingListSkin
package skins.pagedList
{
    import flash.display.Graphics;
    import flash.display.Sprite;
    import flash.events.MouseEvent;

    import mx.core.DPIClassification;
    import mx.core.ScrollPolicy;
    import mx.events.FlexEvent;
    import mx.events.TouchInteractionEvent;

    import spark.events.IndexChangeEvent;
    import spark.events.RendererExistenceEvent;
    import spark.skins.mobile.ListSkin;
    import spark.skins.mobile.supportClasses.MobileSkin;

    public class ScrollingListSkin extends ListSkin
    {
        private var pageIndicator:Sprite;
        private var indicatorSize:uint;
        private var _isHorizontal:Boolean;
        private var _suspendPageIndicatorShortcut:Boolean;

        public function ScrollingListSkin()
        {
            super();

            switch (applicationDPI)
            {
                case DPIClassification.DPI_320:
                {
                    indicatorSize = 32;
                    break;
                }
                case DPIClassification.DPI_240:
                {
                    indicatorSize = 24;
                    break;
                }
                default:
                {
                    indicatorSize = 16;
                    break;
                }
            }
        }

        //--------------------------------------------------------------------------
        //
        //  Overridden methods
        //
        //--------------------------------------------------------------------------

        override protected function createChildren():void
        {
            super.createChildren();

            scroller.setStyle("skinClass", PagedListScrollerSkin);

            // page indicator
            pageIndicator = new Sprite();

            // TODO (jasonsj): extend pageIndicator hit area to use the entire
            // width/height of the List as a shortcut. Currently this only works
            // in the tiny area where the indicators are.
            //pageIndicator.addEventListener(MouseEvent.MOUSE_DOWN, pageIndicaterMouseHandler);
            //pageIndicator.addEventListener(MouseEvent.MOUSE_UP, pageIndicaterMouseHandler);
            //pageIndicator.addEventListener(MouseEvent.MOUSE_MOVE, pageIndicaterMouseHandler);

            addChild(pageIndicator);

            // listen for changes to the list
            dataGroup.addEventListener(FlexEvent.UPDATE_COMPLETE, dataGroupUpdateComplete);
            scroller.addEventListener(TouchInteractionEvent.TOUCH_INTERACTION_START, touchInteractionStart);
            scroller.addEventListener(TouchInteractionEvent.TOUCH_INTERACTION_END, positionChanged);
        }

        override protected function commitProperties():void
        {
            super.commitProperties();

            // isHorizontal
            /*var hScrollPolicy:Boolean = getStyle("horizontalScrollPolicy") == ScrollPolicy.ON;
            var vScrollPolicy:Boolean = getStyle("verticalScrollPolicy") == ScrollPolicy.ON;
            _isHorizontal = hScrollPolicy && !vScrollPolicy;*/
            _isHorizontal = true;
        }

        override protected function drawBackground(unscaledWidth:Number, unscaledHeight:Number):void
        {
            super.drawBackground(unscaledWidth, unscaledHeight);

            var pos:Number = (isHorizontal) ? scroller.viewport.horizontalScrollPosition :
                scroller.viewport.verticalScrollPosition;
            var viewportSize:Number = (isHorizontal) ? scroller.viewport.width :
                scroller.viewport.height;

            var selectedIndex:int = Math.round(pos / viewportSize);
            var numElements:int = dataGroup.numElements;

            var g:Graphics = pageIndicator.graphics;
            g.clear();

            // if we have only one page there shouldn't be any scrollbar visuals
            if (numElements == 1) return;

            var axisPos:Number = 0;
            var centerPos:Number = indicatorSize / 2;
            var radius:Number = indicatorSize / 4;
            //TODO: make so the color could be specifyed outisde
            var selectionColor:Number = 0x000000; //getStyle("selectionColor");

            //var elementsPerPage:int = Math.floor(unscaledWidth/FileIconItemRenderer.ITEM_WIDTH) * Math.floor(unscaledHeight/FileIconItemRenderer.ITEM_HEIGHT);

            for (var i:uint = 0; i < numElements; i++)
            {
                if (i == selectedIndex)
                    g.beginFill(selectionColor, 1);
                else
                    g.beginFill(0, .25);

                if (isHorizontal)
                    g.drawCircle(axisPos + centerPos, centerPos, radius);
                else
                    g.drawCircle(centerPos, axisPos + centerPos, radius);

                g.endFill();

                axisPos += indicatorSize;
            }

            var pageIndicatorX:Number = (isHorizontal) ? (unscaledWidth - axisPos) / 2 :
                unscaledWidth - (indicatorSize * 1.5);
            var pageIndicatorY:Number = (isHorizontal) ? unscaledHeight - (indicatorSize * 1.5):
                (unscaledHeight - axisPos) / 2;

            setElementPosition(pageIndicator, Math.floor(pageIndicatorX), Math.floor(pageIndicatorY));
        }

        override public function styleChanged(styleProp:String):void
        {
            super.styleChanged(styleProp);

            var allStyles:Boolean = !styleProp || styleProp == "styleName";

            if (allStyles || styleProp == "horizontalScrollPolicy" ||
                styleProp == "verticalScrollPolicy")
            {
                invalidateProperties();
                invalidateDisplayList();
            }
        }

        private function get isHorizontal():Boolean
        {
            return _isHorizontal;
        }

        //--------------------------------------------------------------------------
        //
        //  Event Handlers
        //
        //--------------------------------------------------------------------------

        private function dataGroupUpdateComplete(event:FlexEvent):void
        {
            invalidateDisplayList();
        }

        private function touchInteractionStart(event:TouchInteractionEvent):void
        {
            _suspendPageIndicatorShortcut = true;
        }

        private function positionChanged(event:TouchInteractionEvent):void
        {
            invalidateDisplayList();
            _suspendPageIndicatorShortcut = false;
        }

        private function pageIndicaterMouseHandler(event:MouseEvent):void
        {
            event.preventDefault();

            if (_suspendPageIndicatorShortcut)
                return;

            // Mouse events on the pageIndicator sprite will jump to the selected page
            var pos:Number = (isHorizontal) ? event.localX : event.localY;
            var size:Number = (isHorizontal) ? pageIndicator.width : pageIndicator.height;

            pos = Math.min(Math.max(pos, 0), size) - (indicatorSize / 2);

            var viewportSize:Number = (isHorizontal) ? scroller.viewport.width : scroller.viewport.height;
            viewportSize = viewportSize * dataGroup.numElements;

            var viewportPosition:Number = (pos / size) * viewportSize;

            if (isHorizontal)
                scroller.viewport.horizontalScrollPosition = viewportPosition;
            else
                scroller.viewport.verticalScrollPosition = viewportPosition;
        }
    }
}

Example:
<pagedList:PagedList id="displayList"
                 width="100%" height="100%"
                 itemRenderer="skins.pagedList.PageItemRenderer"
                 innerItemRenderer="components.pagedList.tiles.FolderTileItem"
                 innerItemWidth="146" innerItemHeight="150"
                 skinClass="skins.pagedList.ScrollingListSkin"
                 verticalScrollPolicy="off"
                 horizontalScrollPolicy="on"
                 pageScrollingEnabled="true"
                 horizontalGap="15" verticalGap="20"
                 contentBackgroundAlpha="0"
                 selectionColor="0xFFFFFF">
<pagedList:layout>
    <s:HorizontalLayout columnWidth="{displayList.width}"
                        variableColumnWidth="false"
                        gap="0"
                        paddingTop="30"/>
</pagedList:layout>

Unfortunatly I can't share the FolderTileItem source with you, but its simple a simple component that extends Sprite.


text:
Q: Align text in the putText() in OpenCV I have a list of strings like this
['standUp', 'front', 'lookU', 'lookF', 'lookDF', 'HandOnHipR']

I want to print it in the following manner on my video:
['standUp',
'front',
'lookU',
'lookF',
'lookDF',
'HandOnHipR']

I have tried this:
offset = 1
x, y = 5, 400
for idx, list in enumerate(lbls):
    cv2.putText(frame, str(lbls), (x, y+offset*idx), font, 1, (0, 0, 255), 1)

The label is a list of lists mentioned at the top. I am confused with the org argument in the putText().

A: Parameters are as follows:
cv2.putText(img, text, (org), font, fontScale, color, thickness, linetype)
img: your image
text: a string of text to print on image
org: bottom-left corner of the text string in the image (x,y)
font: font type
fontScale: font scale
color: text color (B,G,R)
thickness: text line thickness
lineType: line type (8)
Here is an example that may help.
Test image:

Code:
import cv2

lbls = ['standUp', 'front', 'lookU', 'lookF', 'lookDF', 'HandOnHipR']

img = cv2.imread("road.jpg")

h,w,c = img.shape

offset = 0

font = cv2.FONT_HERSHEY_SIMPLEX

for itr, word in enumerate(lbls):
    offset += int(h / len(lbls)) - 10
    cv2.putText(img, word, (20, offset), font, 1, (0, 255, 0), 3)

cv2.imwrite("road_OUT.jpg", img)

Result:

A: The org argument is used to choose the position of the text in the image, and the bottom left corner of the text is put at the point org.  If you want the text more to the right, you increase the x value, and if you want it lower, you increase the y value.  So each line will be lower because you are increasing the y value with the offset*idx.
As you have it, the second argument str(lbls) will print out the entire array, that should be changed to the variable for the single element, which you have as list.  (However, it's best not to use list as a variable because it will replace the built-in function list().  I'll use lbl instead.)
Here's an example where the words in the list are printed:
import cv2
import numpy as np
import matplotlib.pyplot as plt

frame = np.ones([400,400,3])*255
lbls = ['standUp', 'front', 'lookU', 'lookF', 'lookDF', 'HandOnHipR']

offset = 35
x,y = 50,50
for idx,lbl in enumerate(lbls):
    cv2.putText(frame, str(lbl), (x,y+offset*idx), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 2)

plt.imshow(frame)
plt.show()

If you want to have the brackets and punctuation like you show above, you could possibly print them manually.  The first and last elements would need to be printed separately:
cv2.putText(frame, '[\''+str(lbls[0])+'\',', (x,y), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 2)
for idx,lbl in enumerate(lbls[1:-1]):
    cv2.putText(frame, '\''+str(lbl)+'\',', (x,y+offset*(idx+1)), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 2)
cv2.putText(frame, '\''+str(lbls[0])+'\']', (x,y+offset*(idx+2)), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 2)

Otherwise, you could change the elements to actually include the punctuation in them.


text:
Q: How to replace the comma with a space when I use the "MultiAutoCompleteTextView" I'm doing a simple program using MultiAutoCompleteTextView to prompt the common words when I input several letters.
code:
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_dropdown_item_1line,
            ary);
    MultiAutoCompleteTextView textView = (MultiAutoCompleteTextView) findViewById(R.id.editText);
    textView.setAdapter(adapter);

    textView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

    private String[] ary = new String[] {
       "abc",
       "abcd",
       "abcde",
       "abcdef",
       "abcdefg",
       "hij",
       "hijk",
       "hijkl",
       "hijklm",
       "hijklmn",
    };

Now,when I input 'a' and choose "abcd" but the result become to "abcd,". How to replace the comma with a space?
Thank you!

A: public class SpaceTokenizer implements Tokenizer {

public int findTokenStart(CharSequence text, int cursor) {
int i = cursor;

while (i > 0 && text.charAt(i - 1) != ' ') {
    i--;
}
while (i < cursor && text.charAt(i) == ' ') {
    i++;
}

return i;
}

public int findTokenEnd(CharSequence text, int cursor) {
int i = cursor;
int len = text.length();

while (i < len) {
    if (text.charAt(i) == ' ') {
        return i;
    } else {
        i++;
    }
}

return len;
}

public CharSequence terminateToken(CharSequence text) {
int i = text.length();

while (i > 0 && text.charAt(i - 1) == ' ') {
    i--;
}

if (i > 0 && text.charAt(i - 1) == ' ') {
    return text;
} else {
    if (text instanceof Spanned) {
        SpannableString sp = new SpannableString(text + " ");
        TextUtils.copySpansFrom((Spanned) text, 0, text.length(),
                Object.class, sp, 0);
        return sp;
    } else {
        return text + " ";
    }
}
}
}

A: The way to do it would be to implement your own Tokenizer.  The reason the comma comes up is because you're using CommaTokenizer, which is designed to do exactly that.  You can also look at the source code for CommaTokenizer if you need a reference for how to implement your own SpaceTokenizer.

A: Check my question/answer
How to replace MultiAutoCompleteTextView drop down list
you will find a SpaceTokenizer class

A: I have used Kotlin for a white space tokenizer. This also caters tabs, trailing spaces and line feeds.
object : Tokenizer {
            override fun findTokenStart(text: CharSequence, cursor: Int): Int {
                val spaceIndex = text.indexOfFirst { Character.isWhitespace(it) }
                return if (spaceIndex > cursor)
                    spaceIndex
                else cursor
            }

            override fun findTokenEnd(text: CharSequence, cursor: Int): Int {
                val lastSpaceIndex = text.indexOfLast { Character.isWhitespace(it) }
                return if (lastSpaceIndex > cursor)
                    lastSpaceIndex
                else cursor
            }

            override fun terminateToken(text: CharSequence): CharSequence {
                val i = text.length

                return if (i > 0 && text[i - 1] == ' ') {
                    text
                } else {
                    if (text is Spanned) {
                        val sp = SpannableString("$text ")
                        TextUtils.copySpansFrom(
                            text as Spanned?, 0, text.length,
                            Any::class.java, sp, 0
                        )
                        sp
                    } else {
                        "$text "
                    }
                }
            }

        }


text:
Q: Can a relativizer be modified by PP phrase
The level of responsibility which the client carries for the whole development process with time & materials is much higher than with fixed-price or milestone projects.

It can be understood that a gap exists behind the verb carries

The level of responsibility which the client carries _______ for the whole development process ...

So the relativizer which serves as the object of carries.
And since the PP pharse for the whole development process follows the gap (known as which),
is it right to say that the PP phrase (which acts as an adjective) modifies the relativizer which?


text:
Q: How can I write a custom algorithm that works on either a vector or map iterator I want to write my own algorithm (just a function really) that takes a range of iterators. If the iterators are from a map, I want to use the data (iterator->second) value. If the iterator is "normal" like a vector or list, I just want to use the dereferenced iterator value.

A: I think, value-getter idea is right here, but you can implement it without c++11 and without structs at all, only using functions:
template <typename T>
const T& get(const T& t)
{
    return t;
}

template <typename T, typename V>
const V& get(const std::pair<T,V>& t)
{
    return t.second;
}

int main()
{
    std::vector<int> v = {1};
    std::cout << get(*v.begin());

    std::cout << "\n----\n";

    std::map<int, std::string> m;
    m.insert(std::make_pair(0, "sss"));
    std::cout << get(*m.cbegin());
}

A: You can make a value-getter class that extracts the value you're interested in. Note that this approach doesn't work if you store pairs in any container (it transforms all pairs, whether in a map or not). I'd think it would be a much clearer approach to only accept "regular" iterators and let it be callers job to transform map iterators appropriately (as suggested in the comments to your question.)
template<typename T>
struct get {
  static auto val(const T& t) -> const T&
  {
    return t;
  }
};

template<typename U, typename V>
struct get<std::pair<U, V>> {
  static auto val(const std::pair<U, V>& p) -> const V&
  {
    return p.second;
  }
};

// use like
get<decltype(*iter)>::val(*iter);

Convenience function could look like:
template<class T>
auto getval(const T& t) -> decltype(get<T>::val(t))
{
  return get<T>::val(t);
}

A: You can overload the function based on the input:
void foo(const std::vector<int>::iterator& it1, const std::vector<int>::iterator& it2)
{
   //use *it
}
void foo(const std::map<int,int>::iterator& it1, const std::map<int,int>::iterator& it2)
{
   //use it->second
}

Edit:
I think this is the closest you can get to what you want to achieve:
template <typename T, typename X>
void foo(T const& x, X const& y)
{

}

template <typename T, typename S>
void foo(const typename std::map<T,S>::iterator& x, const typename std::map<T,S>::iterator& y)
{

}

int main()
{
    std::map<int,int> x;
    std::vector<int> y;
    foo(x.begin(), x.end()); //will call second version
    foo(y.begin(), y.end()); //will call first version
}

A: A trait should do the trick. First the type-deducing helper:
template <typename Iter>
typename iter_value<Iter>::value_type & iter_deref(Iter it)
{
    return iter_value<Iter>::deref(it);
}

All we need is something like this:
template <typename Iter>
class iter_value
{
    template <typename T> struct aux
    {
        typedef T type;
        static type & deref(Iter it) { return *it; }
    };
    template <typename U, typename V> struct aux<std::pair<U const, V>>
    {
        typedef V type;
        static type & deref(Iter it) { return it->second; }
    };

    typedef typename std::iterator_traits<Iter>::value_type type;

public:
    typedef typename aux<type>::type value_type;

    static value_type & deref(Iter it)
    {
        return aux<type>::deref(it);
    }
};

A: You can create a function that extracts the value out of the iterator. Then you can overload that based on the type of the iterator. You can use that function in your algorithm. Assuming a vector of ints and a map of string->int, it could look like this:
int getValue(const std::vector<int>::iterator& it)
{
    return *it;
}

int getValue(const std::map<std::string, int>::iterator& it)
{
    return it->second;
}

Then the algorithm can use the function getValue() to get a value from the iterator.


text:
Q: Парсинг всплывающего окна На сайте https://cinemahall24.ru/seances отображены фильмы, которые идут в кинотеатре. При нажатии на фильм появляется окно, которое нужно распарсить, для этого использую selenium, но при вызове browser.page_source я получаю html код сайта без этого окна, хотя в консоли браузера html вместе с окошком. Как получить html код сайта вместе с окошком?
Код:
browser = webdriver.Chrome()
browser.get('https://cinemahall24.ru/seances')
time.sleep(3)

cards = browser.find_elements(By.CLASS_NAME, 'widget-overlay')

for card in cards:
    browser.execute_script("arguments[0].click();", card)
    time.sleep(5)
    print(browser.page_source)

Так тоже не работает
for card in cards:
    browser.execute_script("arguments[0].click();", card)
    time.sleep(5)
    page = browser.find_element(By.TAG_NAME, 'html')
    print(page.get_attribute('innerHTML'))


text:
Q: Как поменять цвет фона и шрифта компонента webBrowser? Компонент webBrowser отображает файлы и папки при помощи данного кода. Фон всегда белый, мне это совсем не нравится. Можно ли изменить цвет фона и шрифта на другой?
private void Form1_Load(object sender, EventArgs e)
    {
        webBrowser1.Navigate(@"C:\");
    }


text:
Q: async and recursion with tokio::task::LocalSet and !Send Having a bit of a rough time with async Rust here.
Consider the following piece of (garbage) code, intended to be run on a single thread with tokio::LocalSet, since I couldn't figure out how to make async_recursion work without ?Send in this case:
use std::{time::Duration};

use mlua::{Lua, Result as LuaResult, UserData};
use async_recursion::async_recursion;
use tokio::{time::sleep, task};

#[derive(Debug, Clone)]
struct Sleeper;

impl UserData for Sleeper {
    fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) {
        methods.add_async_function("sleep", |lua, (sleeper, millis): (Self, u64) | async move {
            println!("sleeping for {millis} ms");
            sleep(Duration::from_millis(millis)).await;
            println!("woke up :)");
            Ok(millis)
        });
    }
}

#[async_recursion(?Send)]
async fn fn1(lua: &'static Lua) -> LuaResult<()> {
    let recurse: u32 = lua.globals().get("recurse")?;
    if recurse < 5 {
        lua.globals().set("recurse", recurse+1)?;
        task::spawn_local(lua.load("SLEEPER:sleep(1000)").exec_async()).await.unwrap()?;
        task::spawn_local(fn1(lua)).await.unwrap()
    }
    else {
        Ok(())
    }
}

#[tokio::main]
async fn main() -> LuaResult<()> {
    let local = task::LocalSet::new();

    local.run_until(async move {
        let lua: &'static mut Lua = Box::leak(Box::new(Lua::new()));
        lua.globals().set("recurse", 0u32)?;
        lua.globals().set("SLEEPER", Sleeper)?;
        task::spawn_local(fn1(lua)).await.unwrap()
    }).await
}

Without Box::leak() shenanigans, the compiler gives the following error:
error[E0597]: `lua` does not live long enough
  --> src/main.rs:44:31
   |
44 |         task::spawn_local(fn1(&lua)).await.unwrap()
   |                           ----^^^^-
   |                           |   |
   |                           |   borrowed value does not live long enough
   |                           argument requires that `lua` is borrowed for `'static`
45 |     }).await
   |     - `lua` dropped here while still borrowed

Based on my current knowledge, leaking lua seems to be the only way to make something like this work. Anyone have better ideas? :D


text:
Q: Fotorama gallery on pages I'm trying to load fotorama on a cms page and some category pages which are custom.
The JS doesn't load on it's own so I thought I was being clever and added this to one of my theme's js files.
// my-custom-theme-script.js
requirejs([
    'jquery',
    'fotorama/fotorama'
], function($, fotorama){
});

This almost worked. I see my code is causing fotorama to load on the page, but strangely, I'm getting this error in console:
Uncaught Fotorama requires jQuery 1.8 or later and will not run without it.

So to further debug I changed my theme js to this
// my-custom-theme-script.js
requirejs([
    'jquery',
    'fotorama/fotorama'
], function($, fotorama){
    console.log($.fn.jquery); //-> 1.11.0
});

So now I'm thinking this is a requiredjs configuration issue on my part. If I add something to the fotorama.js file on about line 98 where the above error comes from, I see that $ is false.
// fotorama.js
var JQUERY_VERSION = $ && $.fn.jquery.split('.');

if (!JQUERY_VERSION
    || JQUERY_VERSION[0] < 1
    || (JQUERY_VERSION[0] == 1 && JQUERY_VERSION[1] < 8)) {

    console.log($); //-> false
    throw 'Fotorama requires jQuery 1.8 or later and will not run without it.';

How exactly am I suppose to add a custom fotorama gallery to a cms page or block outside of where fotorama is already loading? I'm guessing I'm way off here.
From what I can tell I need to manually define jquery as a dependency in my requirejs-config, however this seems counter intuitive for a js resource that Magento 2 natively includes. Any suggestions?


text:
Q: How do I configure an IKEv2 VPN behind a Cisco ASA 5505? I'm sure everyone is aware that Mac has released an update to OSX and iOS that removes support for PPTP VPNs. Because they are simple and almost entirely plug & play, most of our customers have PPTP VPNs set up. But with this latest update, we need to find another solution.
Both Windows and Mac clients support IKEv2, it's already configured on our Windows server, and no 3rd party VPN client is required on either OS. This solution would be completely transparent to all Windows end users, requiring us to only reconfigure Mac clients. All we need to do is set up the firewall for it.
We host the current PPTP VPN on a Windows 2012r2 server. The server is behind a CISCO ASA 5505 running ASA 8.4(7). Based on what I've researched, I need to create Access Rules and NAT Rules to forward ports 500 and 4500. I've also read that I either need to create a 1:1 static NAT for ESP or that some versions of IOS (and I presume ASA) support "IPsec NAT Transparency", which encapsulates ESP in an IP packet over port 4500 (similar to the GRE passthrough for PPTP). Unfortunately, all of the documentation regarding this feature is missing from Cisco's website and redirects to a generic "End Of Life" landing page.
I've configured Access Rules to forward UDP ports 500 and 4500. When I create NAT rules for these ports, I get the error message (from ASDM):
 [ERROR] nat (inside,Outside-Comcast) static interface service udp 500 500
     NAT unable to reserve ports.

I don't know why this is failing. I assume there is a conflict on the ASA, perhaps from a Cisco VPN configuration installed on the ASA by default.
I also do not know how to enable IPsec NAT Transparency or even if this version of ASA supports it.
Cisco Adaptive Security Appliance Software Version 8.4(7)
Device Manager Version 7.3(3)
I realize that the NAT error message is very specific to my configuration, and I can share the current running config if necessary, but I'm hoping someone might know off the top of their head "oh yeah, XYZ is on by default and you have to turn it off first".
Any advice on the IPsec NAT would be most helpful. If there is documentation that tells me if this version of ASA supports it or if there's another, newer feature we can enable that does the same thing.

A: You need to allow IPSEC passthrough on the firewall. If you have an available public IP address do a 1:1 NAT from the public IP address to the private IP address of the VPN server. All have have to do at that point is add an ACE that allows  the ports to connect to the VPN server.
A discussion about this can be found on Cisco support's site. https://supportforums.cisco.com/discussion/10160506/ipsec-passthrough-asa5505