C# - How do I check if a file exists in a certain directory (based on its content, not the file name)?

Question: I am creating a program that will grab files from a Result Directory (Original Folder) and move those files to a Working Directory (Another Folder). Here the file's name is being changed when the file is moved from one directory to another. Before I move them, I need to check that the Working Directory does not contain that file I am trying to move already. Since the file name is being changed, I need something that will check if the file exists already based on the content inside of the file.
Let's say I have:
FilesRD - (The files in the Original Folder/Result Directory)
FilesWD - (The files in the Other Folder/Working Directory)
and the files inside of those directories will look like this...
Before (In Result Directoy):
Log_123.csv
After (In Working Directory):
Log_123_2015_24_6.csv
Comment: If the files are identical you could get a hash\crc of the file contents and compare them.  Quite a broad question for SO tbh
Comment: I imagine, you will need file content comparison, between all the files in target directory and current file. This could take a lot of time depending on the number of files and size of the files. This could be a starting point. [How to create a File-Compare function in Visual C#](https://support.microsoft.com/en-us/kb/320348)
Comment: I came here to say the same as @MartinParkin,.. you can try hashing the content of the file.. and the results are the same.. then you´ll now.
Comment: If it is a single program you have access to all aspects of it I assume (or do you use external stuff?). Can't you keep track of what files have been moved already or at least what is the new name of the file?
Comment: Does the file in the working directory always start with the original name? Which program does the renaming?
Comment: If only your software can change files name, and then if you follow some common naming convention, you can easily discover the old file name (in your example by removing the date)?
Comment: The file in the Working Directory does not always start with the same name, but it could. So I added the UTCtime so I can differ them if that ever happens. And I'll look into "hashing." Thanks.
Comment: A deterministic mapping between the filenames would be best, or otherwise a lookup table somewhere. If you do use hashes, see if you can keep them around, as generating a hash still must read a file in its entirety. If that's not possible, and depending on the content and size of your files, you may want to read files piece by piece, comparing the pieces against the original file as you go. This allows you to bail out as soon as you find a difference, which can be more efficient (unless files only differ near their ends).
Answer: I would try the following function it's far from being perfect:
<code>    private bool CheckIfFileAlreadyExist(string WorkingDirectory, string FileToCopy)
    {
        string FileToCheck = File.ReadAllText(FileToCopy);
        foreach (string CurrentFile in Directory.GetFiles(WorkingDirectory))
        {
            if (File.ReadAllText(CurrentFile) == FileToCheck)
                return true;
        }
        return false;
    }
</code>
UPDATE:
Another way is to read out the ByteArray this would solve the Image Problem. But the function still get's slow over time.
<code>    private bool CheckIfFileAlreadyExist(string WorkingDirectory, string FileToCopy)
    {
        byte[] FileToCheck = File.ReadAllBytes(FileToCopy);
        foreach (string CurrentFile in Directory.GetFiles(WorkingDirectory))
        {
            if (File.ReadAllBytes(CurrentFile) == FileToCheck)
                return true;
        }
        return false;
    }
</code>
Comment: Although this appears to solve the OPs problem, doing a textual comparison of the files may be exceptionally slow.  You'd be better off creating a hash of the file contents and comparing it.
Comment: out of curiousity, what happens if the files are images?
Comment: @user1666620 This would fail as it assumed that they are text.  Hence the use of a hash :)
Comment: You'll want to use `Enumerable.SequenceEqual` here instead of `==`, because you want to compare their content, not their identity.
Answer: you need to check in the destination folder using system.io namespace for example:
<code>string destination = "c:\myfolder\";
string [] files   Directory.GetFiles(destination , "Log_123");
if(files.Length == 0)
{
   //move the file to the directory
}
</code>
you can add pattern to the getfiles function, only if it found file match to the pattern it's return it.
Comment: the query is to find duplicate file content, not file names
Comment: This does not ascertain whether the file __contents__ are the same which is what the OP asked for.
Comment: if you want to check by content you need to create unique MD5 for each file and compare between the new md5 if there is a match so it mean that content already exists... http://stackoverflow.com/questions/10520048/calculate-md5-checksum-for-a-file
Answer: Try comparing the files hashes.
Here's an example:
<code>        private static string GetFileMD5(string fileName) {
            using (var md5 = MD5.Create()) {
                using (var fileStream = File.OpenRead(fileName)) {
                    return BitConverter.ToString(md5.ComputeHash(fileStream)).Replace("-", "").ToLower();
                }
            }
        }
        private static bool DoesFileExist(string workingDir,string fileName) {
            var fileToCheck = GetFileMD5(fileName);
            var files = Directory.EnumerateFiles(workingDir);
            return files.Any(file => string.Compare(GetFileMD5(file), fileToCheck, StringComparison.OrdinalIgnoreCase) == 0);
        }
</code>
Comment: And how do you think a hash is calculated for a given stream...?


Local Dependency in Gem .gemspec

Question: I am working on a gem (Gem A) which uses another gem (Gem B) that I have also written. Until this point Gem B has been added in the gemspec for Gem A:
gem.add_dependency "gem_a", "~> 0.0.4"

But I now find the need to debug using my local version.
To declare a local dependency in a Gemfile I could do:
gem 'gem_a', path: "/local/path/to/gem_a"

But how do I declare a local dependency in a .gemspec?
Comment: Not sure if this can be done, but it would be useful if gems are being co-developed. Trouble is the two declarations of dependency are for two different installers to process. What would `gem build` do with a local dependency? The resulting package couldn't be reliably distributed.
Answer: Just so folks can find the answer (slightly) faster...
If you're creating a gem, and need to add a local dependency (while developing), in your gem's Gemfile, do something like:
source 'https://rubygems.org'

# Specify your gem's dependencies in mygem.gemspec
gemspec

gem "local_gem", path: "/path/to/local_gem"

When you bundle you should see it's now using the local path
Using local_gem 0.1.0 from source at `/path/to/local_gem`

Comment: Late to the party - but, if I develop a gem locally, then `gem install my_new_gem.gem` to install it locally, I still cannot add it as a dependency in a `gemspec` file right?  It appears that installing a gem locally doesn't  really do anything?
Answer: Hm...what about adding it in gem's Gemfile in :development group?
UPD:
I found similar question, maybe this helps
How to add dependency of a local gem to a rails plugin/engine, in .gemspec file
Comment: Thanks, but unfortunately that doesn't work. I've tried it before and after the `gemspec` call. For some reason it can't see the gem - I get a '…  in `require': cannot load such file -- gem_b (LoadError)'

Local Dependency in Gem .gemspec


how to Read /Write all Whatsapp Messages in backup file using Python or JAVA

Question: I want to read all the WhatsApp messages from the backup taken from the Windows phone and write those messages in a document or in the iPhone.
I have read many questions, that were limited to crypt5 only as the WhatsApp has changed a lot. Following the order of my backup file.

How to read and write the WhatsApp messages from this backup file.
Comment: Have you read http://stackoverflow.com/questions/8856874/get-all-messages-from-whatsapp?
Answer: Your system detects file extension of "messages" as "Data Base File",
you have to get exact messages file extension, and open that database with corresponding tool.
Comment: do you know any tool to perform such action?
Comment: do you got exact file extension?


interesting service behaviour in silverlight

Question: I have a Silverlight project which takes some encrypted string thru its Service Reference: DataService (service which is done in an ASP.NET project).
The method from TransactionServices.cs to get the encrypted string is:
 public void GetEncryptedString(string original)
    {
        DataService.DataServiceClient dataSvc = WebServiceHelper.Create();
        dataSvc.GetEncryptedStringCompleted += new EventHandler<SpendAnalyzer.DataService.GetEncryptedStringCompletedEventArgs>(dataSvc_GetEncryptedStringCompleted);
        dataSvc.GetEncryptedStringAsync(original);
    }

On completing, put the result in encodedString var (which is initialized with an empty value):
void dataSvc_GetEncryptedStringCompleted(object sender, SpendAnalyzer.DataService.GetEncryptedStringCompletedEventArgs e)
    {
        if (e.Error == null)
        {
            try
            {
                if (e.Result == null) return;
                this.encodedString = e.Result;
            }
            catch (Exception ex)
            {
                Logger.Error("TransactionService.cs: dataSvc_GetEncryptedStringCompleted: {0} - {1}",
                    ex.Message, ex.StackTrace);
                MessageBox.Show(ex.ToString());
            }
        }
    }

Now I want to get the encoded string from my MainPage.xaml like:
TransactionService ts = new TransactionService();
                    ts.GetEncryptedString(url);
                    Console.WriteLine(ts.encodedString);

I do not uderstand why ts.encodedString is empty. When I do the debug I see that it actually prints out empty and AFTER that it goes to the void dataSvc_GetEncryptedStringCompleted to take the result and fill it.
Can you point me what I've done wrong? Is there a way to wait for the encodedString to be fetched and only after that to continue?
Thanks a lot.
Answer: When you call the ts.GetEncryptedString(url); you just started async operation. And therefor the value you are accessing is will be set only in the callback method.
But you access it before the value is modified by the callback.
The solution which I am using will looks similar to folowing:
Redefine the GetEncryptedString method signature.
public void GetEncryptedString(string original, Action callback)
    {
        DataService.DataServiceClient dataSvc = WebServiceHelper.Create();
        dataSvc.GetEncryptedStringCompleted += (o,e) =>
{
dataSvc_GetEncryptedStringCompleted(o,e);
callback();
}
        dataSvc.GetEncryptedStringAsync(original);
    }

Call it like this:
ts.GetEncryptedString(url, OtherLogicDependantOnResult);
where
OtherLogicDependantOnResult is
void OtherLogicDependantOnResult()
{
//... Code
}

Comment: And is there any way to make it sync? I want to redirect to the url that it's beeing encrypted so how can I wait for the value to be loaded by the callback?
Comment: I was searching for the solution for a while, but then I just get used to it. Anyway you can make this call synchronous. Take a look at http://blog.benday.com/archive/2010/05/15/23277.aspx
Comment: Thanks a lot. Seems that using lambda expressions was the key!


Equation involving complex conjugate

Question: Can someone show me how
$$\frac{1-\bar{z}}{(1-z)(1-\bar{z})}=\frac{1-\bar{z}}{2(1-Re(z))}.$$
Comment: Do you wish to include that $|z|=1$?  If you let $z=3$, then $(1-3)(1-3)=4$, but $2(1-3)=-4$.
Comment: If you did any work at all (like, perhaps, multiplying out the bottom) it would be good to include it to convince readers you made some progress :)
Answer: Hint: Use the fact that $$Re(z) = \frac{z + \bar{z}}{2}$$
Answer: For every $z \in\mathbb{C}\setminus \{1\}$:
$$\frac{1}{1-z}=\frac{1-\bar{z}}{(1-z)(1-\bar{z})}=\frac{1-\bar{z}}{1-z-\bar{z}+z\bar{z}}=\frac{1-\bar{z}}{1-2\Re{z}+|z|^2},$$
therefore
$$\frac{1-\bar{z}}{(1-z)(1-\bar{z})}=\frac{1-\bar{z}}{2(1-\Re(z))}$$
if  $|z|=1.$
Comment: You should add that $z \ne 1$.
Comment: @Mercy Thanks for remark!
Answer: Let $z=x+iy$
Cancelling the numerators we get, $\{1-(x+iy)\}\{1-(x-iy)\}=2(1-x)$
or, $(1-x)^2-(iy)^2=2-2x$
or, $x^2+y^2=1\implies \mid z\mid =1$

Equation involving complex conjugate


Algebra, analysis and inequality signs involving modulus signs

Question: How do you derive that
| |x|-|y| |<= |x-y|
Comment: This is known as the reverse triangle inequality, see [here](https://math.stackexchange.com/questions/127372/reverse-triangle-inequality-proof).
Answer: If you already have the triangle inequality -
$$ |x| = |x-y+y| \leq |x-y| + |y|. $$
Subtract from both sides to conclude that
$$ |x| - |y| \leq |x-y|. $$


Is there a way to add CSS to a title element in a SVG file?

Question: I am working on an SVG file that has a number of <path> tags. I also have a <title> tag for each of these <path> tags. I have text inside the <title> tag such that when I hover over the <path> element, it displays the text. However, the text is the default format, bland text with an ugly looking border box etc.
Is there a way where I can use CSS to modify the <title> tag so that it can look better?
This is what I have thus far:
 <title>
      Title Tag!!!
 </title>
 <path d="M696.393,-204.269C703.418,-219.592 708.202,-238.899 697,-252 671.205,-282.169 562.896,-290.806 492.399,-293.194" fill="none" stroke="green" stroke-width="3"></path>

Answer: Unfortunately this is browser element and you cannot style it.
If that helps you could make custom tooltip by yourself, look for example here.
Making custom tooltip will probably require some amendments in your code though.


Warning: you may need to increase the main.cf smtp_destination_concurrency_limit - but it is set?

Question: We have a huge delivery of emails right now and emails are not delivered as fast as I think they would:
In the mail log (Postfix v3.4.13 ) I see the following message
Dec  8 14:34:28 s29 postfix/qmgr[2773433]: warning: mail for iu-mail.org is using up 20000 of 20000 active queue entries
Dec  8 14:34:28 s29 postfix/qmgr[2773433]: warning: you may need to increase the main.cf smtp_destination_concurrency_limit from 1
Dec  8 14:34:28 s29 postfix/qmgr[2773433]: warning: please avoid flushing the whole queue when you have
Dec  8 14:34:28 s29 postfix/qmgr[2773433]: warning: lots of deferred mail, that is bad for performance
Dec  8 14:34:28 s29 postfix/qmgr[2773433]: warning: to turn off these warnings specify: qmgr_clog_warn_time = 0

I checked my main.conf but it clearly sets
smtp_destination_concurrency_limit = 10
smtp_destination_rate_delay = 1s
smtp_extra_recipient_limit = 10

I have no clue where the value of 1 is coming from. Do you have any ideas what to check to resolve this issue?
Answer: Ugh. Figured it out:
Setting a smtp_destination_rate_delay forces the value for concurrency automatically to 1.
Removing that parameter resolved the issue.


Can't get child views to load in AngularJS with ui-router

Question: I'm trying to understand the concept of using the ui-router (v0.2.10) with AngularJS (v1.2.15) through converting an old project that previously used ngRoute and have been unable to figure out why it isn't working. I have an ASP.NET MVC website that shows the base page with something similar to the following:
index.cshtml
<!DOCTYPE html>

      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      @Styles.Render("~/Content/css")

      @Scripts.Render(*all the angular, jquery and other script references here)

app.js
angular.module('home') ['ui.router'])
  .config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
    $urlRouterProvider.when("", "/");
    $urlRouterProvider.otherwise("/");

var root = {
  name: 'root',
  url: '/',
  abstract: true,
  templateUrl: '/Scripts/home/templates/root.html',
  controller: 'RootController'
};

var home = {
  name: 'root.home',
  url: '/home',
  parent: root,
  templateUrl: 'Scripts/home/templates/home.html',
  controller: 'HomeController'
};

$stateProvider
  .state(root)
  .state(home);

$locationProvider.html5Mode(true);
};

rootCtrl.js
angular.module('home').controller('RootController', function() {
});

homeCtrl.js
angular.module('home').controller('HomeController', function() {
});

root.html
<navbar/>

navbar.js
angular.module('home').directive('navbar', function() {
  return {
    restrict: 'E',
    replace: true,
    templateUrl: '/Scripts/home/templates/directives/navbar.html'
  };
});

The navbar directive template simply contains the bootstrap navbar.
footer.js
angular.module('home').directive('footer', function() {
  return {
    restrict: 'E',
    replace: true,
    templateUrl: '/Scripts/home/templates/directives/footer.html'
  };
});

Except that nothing shows up on the page except for the CSS references at the top, the following, and then the javascript references at the bottom:

Why doesn't the root.html view show up on the screen when I load up the page? Thanks!
Answer: As per another answer on this site, one cannot self-close the tags for custom directives. Thus, if I change the tags in root.html to the following:
<navbar></navbar>

It works fine.


Text highlighting in html page

Question: I am working in HTML with jquery.
I want to make a webpage to highlight some text lines (line nos 15, 22, 32) in that page at a time. This can be done by left click in mouse and drag that line, so that the text line is selected with blue background.
I am able to get the selected lines as follows using jquery,
    function getText() {
        var text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        } else if (document.selection && document.selection.type != "Control") {
            text = document.selection.createRange().text;
        }
        console.log('text-----------'+text)
    }

When I am clicking other line, first selected line was disappears. I need that line also be available. (In MSword, we can hold ctrl and drag the lines and it will be available)
For multiple selection, I know there is more plugins available in web. But I am looking for doing this selection using Javascript or jquery.
This is what I am looking for to do in my page, want to select texts and get them in my javascript function.

How may we do this?
Comment: so you copied this answer http://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text changed the function name and want us to do the work?
Comment: this question is not clear. Can you try and explain clearer?
Comment: You can style selected text using `::selection ` pseudo class.
Comment: `For multiple selection` What is your final goal? Just style? Or you want that you could `copy` the selection texts?
Comment: @MoshFeu, Yes I want to copy that texts.
Comment: And if you will do `paste` it will paste all the texts together?
Comment: Copying requires Flash for some reason, might not work on Firefox.
Comment: Ok, is there possible to mark the background color of the texts in webpage?
Comment: @MoshFeu, thats fine. is that possible?
Comment: @caramba he wants to do this but with multiple selection.
Comment: @MoshFeu I'm just trying to say that he didn't try anything really showing any effort how he could solve the "multy-selection" part..
Comment: @caramba, do you know I didn't do anything? mind your words, especially over the web. If you dont know what to do, then just leave it. This is what the difference between poor or ordinary developers like you and complete professionals. Complete professionals knows well what happened in background. You proved it here.
Answer: This answer is combined of some issues.

Get the selection text
Mark it.
Copy to clipboard

It's not the full solution but there are all the parts.
So:

var output = '';
$('#test').mouseup(function () {
    output += getSelectedText();
    highlightSelected();
    copyOutput();
    $('#result').html(output);
});

function getSelectedText() {
    if (window.getSelection) {
        return window.getSelection().toString();
    } else if (document.selection) {
        return document.selection.createRange().text;
    }
    return '';
}

function highlightSelected() {
    var SelRange;
    if (window.getSelection) {
        SelRange = window.getSelection().getRangeAt(0);
    } else if (document.getSelection) {
        SelRange = document.getSelection().getRangeAt(0);
    } else if (document.selection) {
        SelRange = document.selection.createRange();
    }

    if (SelRange.pasteHTML) {
        SelRange.pasteHTML('' + SelRange.text + '');
    }
    else {
        var newNode = $('')[0];
        SelRange.surroundContents(newNode);
    }
}

function copyOutput() {
    var emailLink = document.querySelector('#result');
    var range = document.createRange();
    range.selectNode(emailLink);
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);

    try {
        var successful = document.execCommand('copy');
    } catch (err) {
        console.log('Oops, unable to copy');
    }

    window.getSelection().removeAllRanges();
}
textarea {
  width:100%;
  height:150px;
}

.hilited1 {
  background:red;
  color:#fff;
}

I am working in HTML with jquery.
  I want to make a webpage to highlight some text lines (line nos 15, 22, 32) in that page at a time. This can be done by left click in mouse and drag that line, so that the text line is selected with blue background.
I am able to get the selected lines as follows using jquery,

<textarea placeholder="Try to paste here"></textarea>
Comment: Thank you so much @Mosh.This looks similar. I got some ideas to get some thoughts from your help. My requirement is bit different. Anyway, this is very much helpful for me.
Comment: I glad to hear! Good luck!
Comment: If I am having two  tag inside the div id test, then this highlight doesn't works. Can we get this? also can we remove the bit of  content from the selected content. For example, If initially I selected 100 chars wrongly, can we change it to 80 chars by not highlighting the remaining 20 chars by aain select them.
Comment: Mosh, Can you give some suggestions on my above comment

Text highlighting in html page


PLot Realtime data using MATLAB

Question: I am trying to plot real-time data from a sensor that has a frequency of 25 Hz. I read data from the sensor using TCPIP protocol, parse it and then plot the data. However, the plotting part is not very fast and starts to lag after some time. So for e.g. if I move the sensor, I see the response 5 seconds later. I used Serial Plotter in Arduino (which has much less specifications than my laptop) but it is able to plot real-time data without any delays / problems.
My code looks a bit like the following
<code>IMUData = nan(1500,6);
InterfaceObject = tcpip('my_ip_address',50001);
InterfaceObject.BytesAvailableFcn ={@PlotSensorData};
</code>
And the PlotSensorData function looks like
<code>    function PlotSensorData(~,~)

        RecievedData = fscanf(InterfaceObject,'%s');
        Identifier = RecievedData(6); % 6th byte is the sensor identifier

        DataStartIdx = 28; % For each sensor, data start position is common

        if Identifier == 'I'

            DataEndIdx = DataEndPosition(RecievedData, 1);

            SlicedData = RecievedData(DataStartIdx:DataEndIdx);
            ParsedData = textscan(SlicedData,'%f', 'Delimiter',',');

            % Append new data to IMUData matrices
            prevval = IMUData;
            val = [prevval(2:end,:); ParsedData{1}'];
            IMUData = val;

            set(PlotHandle{1},'ydata',val(:,3));
            set(TopAxes,'ylim',[-15 15]);
            drawnow limitrate;
       end

  end
</code>
Also, instead using plot, I have already tried animatedLine. It seems faster initially as it plots very fast, but after sometime, it starts to lag as well and the lag is more than 10 Sec.
So my questions are

What can be done to speed up the real-time data in MATLAB.
Also, I have already tried plotting the data after a certain number of samples (say 10, 20) are received instead of plotting after every received sample, but the results are still lagging and the GUI hangs as well. Is there any other strategy that I can use? In Python I used Multi-threading, but can I use it here as well? Or is there a better approach to handle this data rate?
I understand that Arduino is only running one script but the computer has a lot of overhead, but how is Arduino able to plot the data so fast while MATLAB just hangs up?

Thanks
Comment: Have you profiled your code to check it is the plotting, and not the ever-growing array which you assign to and from, which is lagging? Do you need to always set the `ylim` property when it remains constant?
Comment: Hi, Thanks for coming back. I do initialize my arrays
Comment: You do not in this case, this line is appending new data to `IMUData` via the intermediate `val` and `prevval` variables: `val = [prevval(2:end,:); ParsedData{1}'];`. Have you used the profiler, or at least `tic`/`toc` to check where the bottleneck is?
Comment: Hi Wolfie profiler shows the most time goes in fscanf and also in prevval = IMUData and IMUData = val.
Comment: Now we're making progess - if that's the case then plotting isn't causing your lag! Please provide a [mcve] to show what `InterfaceObject` looks like, perhaps you can do something more efficient that `fscanf`. Then as I say, taking advantage of pre-allocation would improve speed and avoid the two assignments you say take a long time. You initialise `IMUData` as an array of NaNs, but immediately extend it instead of indexing into it. Create a counter (which increments each iteration) and assign data into row `x` of `IMUData` instead of using `prevval` and `val`.
Answer: Reading Data Asynchronously instead of continuously solved my problem.

PLot Realtime data using MATLAB


Python xlsxwriter filtering by columns and posting to another worksheet

Question: I think I am going beyond the realms of my amateur Python knowledge.  I am using xlsxwriter to filter a txt file and grab data surrounding a specific string match.  The captured data I place into an Excel table related to 4 columns of TIMESTAMP, STRING_MATCH_VALUE, VALUE1, VALUE2 (like the table below) I am ok up to here.

My next task is to try and filter the Excel worksheet by VALUE1 column.  This is where my Python knowledge is being stretched.  I am looking to filter for ranges between -88.00 and -88.99 and -89.00 and -89.99 and then post the filtered data to specific worksheets in the Excel.  I looked at xlsxwriter filtering and have produced some code below after reading the xlsxwriter documents, but I think I am struggling with the correct wording.  Any hints would be greatly appreciated.
worksheetFILTER.autofilter(0, 0, FILTERtot, 3)
worksheetFILTER.filter_column(2, 'x > -89 and x < -88')

# Hide rows here if they don't match
rowfilt = 1
for row_data in (worksheetFILTER):
    value1 = row_data[2]

    # does it match?
    if value1 == (r'88.\d{2}'):
        # yes.
        pass
    else:
        # No - hide rows.
        worksheetFILTER.set_row(rowfilt, options={'hidden': True})

    # Place matched rows to different worksheet
    worksheetFILTERED.write_row(rowfilt, 0, row_data)

    # Move to next row.
    rowfilt += 1

Comment: why don't you filter when you are getting the data from the text file?
Comment: Hi Padraic - Yeah, your right, that would make the best sense - apologies for the stupid question - It was good to get a second opinion though.  Thanks
Comment: Don't worry it is not  a stupid question. I am sure there is a way to do what you want but I imagine it is easier just to filter initially.
Answer: Something like the following should work:
# Does it match our criteria.
if value1 > -89 and value1 < -88
    # Yes. Then don't filter this row.
    pass
else:
    # No. Then hide the row.
    worksheetFILTER.set_row(rowfilt, options={'hidden': True})

Basically the condition should match the autofilter condition you set up earlier:
worksheetFILTER.filter_column(2, 'x > -89 and x < -88')

For more details see the Working with Autofilters section of the docs and the autofilter sub-examples in autofilter.py.


MySQL select the average timedifference between two timestamp columns for a particular id in a table

Question: I have a table visits that looks like this:
+--------------+-------------+------+-----+---------------------+----------------+
| Field        | Type        | Null | Key | Default             | Extra          |
+--------------+-------------+------+-----+---------------------+----------------+
| id           | int(11)     | NO   | PRI | NULL                | auto_increment |
| vis_id       | int(11)     | NO   | MUL | NULL                |                |
| unit         | int(11)     | NO   | MUL | NULL                |                |
| time_in      | timestamp   | NO   | MUL | CURRENT_TIMESTAMP   |                |
| time_out     | timestamp   | NO   | MUL | 0000-00-00 00:00:00 |                |
| in_username  | varchar(16) | NO   | MUL | NULL                |                |
| out_username | varchar(16) | NO   | MUL | NULL                |                |
+--------------+-------------+------+-----+---------------------+----------------+

I use this to keep track of visitors coming in and out of my building.
What I'd like is to be able to see the "average length of visit" in hours by a particular visitor (defined by vis_id). If the average visit length is less than an hour it should round up to 1.
Here's an example of what I'd like for output:
+--------+------+----------+
| vis_id | unit | avg_time |
+--------+------+----------+
|    156 |  216 | 5        |
|   1230 |  103 | 2        |
|    533 |  112 | 1        |
|    802 |  201 | 3        |
|   1445 |  431 | 4        |
+--------+------+----------+

Suggestions?
Answer: Use AVG() grouping function. As far as I see, you'll need two grouping fields, like below:
SELECT
  vis_id,
  unit,
  ROUND(AVG((UNIX_TIMESTAMP(time_out)-UNIX_TIMESTAMP(time_in))/3600)) AS avg_time
FROM
  visits
GROUP BY
  vis_id,
  unit

Note, that I'm using ROUND() since you've not defined rules for dealing with non-integer values. ROUND() will use algebraic rule, but may be you'll want to drop non-integer part. Then look to FLOOR() - or, instead, add integer part (i.e. round to greatest) - then look to CEIL()
Comment: That works well, but `ROUND` brings it down to `0` instead of up to `1`... can I change it to _always_ round up no matter what?
Comment: Thanks, will accept as the answer when the timer runs down!


Error Message when Trying to Run the Sample Cocos-2DX Android Project on Eclipse

Question: After following the directions on the Cocos-2DX site to get the android environment set up, I'm coming across this issue when trying the run the project as an Android application

[2013-12-03 22:12:10 - HelloCpp] Unable to resolve target 'android-13'
  [2013-12-03 22:21:10 - HelloCpp]     (skipping file '.gitignore' due to ANDROID_AAPT_IGNORE pattern '.*')
  [2013-12-03 22:21:10 - HelloCpp]       Unable to add 'D:\Cocos-2DX\cocos2d-x-2.2\samples\Cpp\HelloCpp\proj.android\assets\app.icf': Zip add failed
  [2013-12-03 22:21:10 - HelloCpp] ERROR: unable to process assets while packaging 'D:\Cocos-2DX\cocos2d-x-2.2\samples\Cpp\HelloCpp\proj.android\bin\resources.ap_'
  [2013-12-03 22:21:10 - HelloCpp] ERROR: packaging of 'D:\Cocos-2DX\cocos2d-x-2.2\samples\Cpp\HelloCpp\proj.android\bin\resources.ap_' failed

All my path and environment variables have been set up, so I'm not sure what could be causing the issue. Any assistance is greatly appreciated
Answer: Try this :
Right click project --> go to properties --> select Android from there --> and from the list of target name select Android 3.2 or lesser
Error means that you do not have api level 13 installed in your sdk manager. So you can download api 13 using android sdk manager.
Also check this : SO Post for this
Hope this helps.
Comment: [2013-12-04 19:04:19 - HelloCpp] (skipping file '.gitignore' due to ANDROID_AAPT_IGNORE pattern '.*')
[2013-12-04 19:04:19 - HelloCpp] Unable to add 'D:\Cocos-2DX\cocos2d-x-2.2\samples\Cpp\HelloCpp\proj.android\assets\app.icf': Zip add failed
[2013-12-04 19:04:19 - HelloCpp] ERROR: unable to process assets while packaging 'D:\Cocos-2DX\cocos2d-x-2.2\samples\Cpp\HelloCpp\proj.android\bin\resources.ap_'
[2013-12-04 19:04:19 - HelloCpp] ERROR: packaging of 'D:\Cocos-2DX\cocos2d-x-2.2\samples\Cpp\HelloCpp\proj.android\bin\resources.ap_' failed
Comment: any solution to this? I am experiencing the same issue and cannot find any help
Comment: Clean the project and try to run again.


Is there a name for the linear maps $u_i: E_i \to \prod_k E_k$ defined by $u_i(t) = (0,...,0,t,0,...,0)$?

Question: Let $E_1,...,E_n$ be vector spaces. We know that a function $p_i: \prod_k E_k \to E_i$, $p_i(x_1,...,x_n) = x_i$ is called a projection function.
I often have to use the function $u_i: E_i \to \prod_k E_k$, $u_i(t) = (0,...,0,t,0,...,0)$ (i.e. $t$ at the $i$th position, and $0$ everywhere else).
Is there a common name for such a function? If not, have you ever seen someone using a certain name for it?
Comment: What about *immersion*? Is it too vague?
Comment: Injection may be?
Answer: This is often called an inclusion (map). The term applies to more than linear maps, and is generally used to describe an injective map $$\iota: X \hookrightarrow Y$$ in situations where we want to regard $X$ as a particular subset of $Y$ by identifying $X$ with $\iota(X)$ via $\iota$.
For spaces $X_i$ with preferred respective points $a_i \in X_i$, we get canonical (natural) inclusions $\iota_i: X_i \hookrightarrow \prod_j X_j$ defined by $$\iota_i(x) := (a_1, \ldots, a_{i - 1}, x, a_{i + 1}, \ldots), $$
and the inclusions $u_i$ in the question are just the special case of these for which $X_i = E_i$ and the $a_i$ are the respective zero elements of $E_i$. By construction, the canonical inclusion $\iota_i$ is a right inverse for the canonical projection $\pi_i : \prod_j X_j \to X_i$ defined by $\pi_i(x_1, x_2, \ldots) = x_i$, that is, $\pi_i \circ \iota_i = \operatorname{id}_{X_i}$.


$f(2x)$ confusion

Question: I know that if we have some function $f(x)$ we can transform it like doing, say, $f(x) + a$ to shift it $a$ units up/down or even $f(x-a)$ which shifts the graph $a$ units left or right. The confusion starts when you squash the graph, say I found $f(2x)$, obviously I did not say $x=2x$ as this is just rubbish that only holds for $x=0$, yet we know $x$ can take any real (or perhaps complex if we allow it) value. What is the right line of reasoning between the lines $y=f(x)$ and $y=f(2x)$, because its definitely not $x=2x$
Comment: Would you have the same trouble with $f(x+1)$?
Comment: Yes, that's right. We could also let $g(x)=f(2x)$ for all $x$ , then "$g$" is the name of the function which takes in a number, say $x$, and spits out the value $f(2x)$. The function $g$ is known as the *composition* of the function $f$ and the function $x\mapsto 2x$. In general, if $p$ and $q$ are functions, then their composition is called $p\circ q$: it is the function with the property that $(p\circ q)(x)=p(q(x))$ for all $x$.
Comment: If the point $(c,d)$ lies on the graph of $y=f(x)$, then the point $(c/2,d)$ lies on the graph of $y=f(2x)$. So the graph transformation corresponds to halving all of the $x$-coordinates, i.e. a horizontal "squash" of scale factor $2$.
Comment: Yes I know that, very well. What I am asking is that if I have $f(x)$ then I want to do say, $f(y/2)$ it is perfectly valid to say $ x = y/2$, but when I am working with the same variable, what is the correct line of reasoning, as I cannot write $x=2x$
Comment: Yes as you cannot say $x=x+1$ unless you are a computer scientist.
Comment: Have you learned about composition of functions?
Comment: I am not quite sure what you mean by that, like $f(g(x))$ for some functions $f$ and $g$?
Comment: That's exactly what I mean.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/147050/discussion-between-nav-bhatthal-and-lee-mosher).
Answer: You correctly understand that the plot of $f(x-a)$ is the plot of $f(x)$ shifted $a$ units to the right.
In a similar way, the plot of $f(ax)$ is the plot of $f(x)$ compressed by a scale factor of $a$.
In no case are we asserting that $x=x-a$ or $x=ax$.
I think what you are trying to express is a composition of functions. For example, let $g(x)=ax$, then we can write
$$
f(ax)=f(g(x)).
$$
In other words, the function $g$ modifies $x$ by scaling it, then passes its output into $f$.
Answer: The idea is that we are applying the operation of composition. Suppose we have $f$ a function with real domain, such that we can write $f = f(x)$. We can now write, for instance $g(x) = f(2x)$, meanning $g$ is the composition of $f$ with the multiplication of $x$ by $2$. In other words, we know that the multiplication by $2$ is also a real function and we can compose it with $f$. To visualize this we can simply name that multiplication as $h(x)$, yiedling $h(x) = 2x$ and then obtaining $g(x) = (f \circ h)(x) = f(h(x)) = f(2x)$. What cannot be done is assigning both $f(x)$ and $f(2x)$ to the same literal in the same context, as in your example $y = f(x)$ and $y = f(2x)$. In that case, that would only hold true if $f(x) = f(2x)$. A proper way to write it would be $y_1 = f(x)$ and $y_2 = f(2x)$, for instance.
Answer: The variable $x$ in the expression $f(x)$ is a dummy variable, and you should not regard it as being identical to the $x$ in the expression $f(2x)$.
One way to keep this all straight is to make good use of function composition notation, and to introduce an extra dummy variable.
First write $f(2x)=f(g(x))$, where we define the new function $g$ by the formula $g(x)=2x$.
Now introduce a new dummy variable $y$ as the input variable for the function $f$ (in place of the old dummy variable $x$ that you started with). Let this variable $y$ also serve as the output variable of the function $g$, and so $y=g(x)$ or $y=2x$. You can then write
$$f(y)=f(g(x))=f(2x)
$$
Generally speaking, mathematicians are not always as careful with their variables as is required in computer science. So, you have to get used to this somewhat ambiguous concept of a "dummy variable".
Answer: This is a very good question.
So the transformation $f(x - a)$ is a right horizontal shift by a units. The transformation $f(x) + a$ is an upwards vertical shift by a units. Now what does the transformation $f(2x)$ do?
There are many ways of describing the behavior of $f(2x)$. Here are some ways:

The transformation $f(2x)$ compresses the graph towards the y-axis by a factor of 2.
The transformation $f(2x)$ is a horizontal scaling (relative to the y-axis) by a factor of $1/2$.
The distance between $f(2x)$ and the y-axis is half the distance between $f(x)$ and the y-axis (which becomes more apparent when you trace a horizontal line through both of the graphs).

It helps to get out a graphing calculator and graph the functions $f(x) = x^2$ and $y = f(2x)$. You can see how the graph of $f(2x)$ is compressed towards the y-axis by a factor of 2.
In the general case, where $y = f(kx)$ for some real number $k \neq 0$, we say that $y$ is a horizontal scaling of $f$ by a factor of $1/k$. If $k > 1$, then the graph of $f$ gets compressed towards the y-axis.

$f(2x)$ confusion


Why is my border top color not showing after I had use the right border syntax

Question: I've been trying to apply a colour to the the border top of my div but it isn't working out.
I've use the right border syntax.
  border: 1px solid white;
  border-top-color: red;
Comment: Welcome to Stack Overflow! Please provide a minimal reproduction code with your HTML and CSS so that we can help you figuring what isn't working.
Answer:

Just test

Just test

I've given you two ways solve your problem

Just test

Just test


Why use fewer features to fix high variance in a machine learning algorithm

Question: How does getting a smaller feature space result in combating high variance in a machine learning algorithm? What I currently understand is the following:

With fewer features the hypothesis can easier fit the data and therefore it helps against high bias (underfitting).
With more features the hypothesis can harder fit the data and therefore it helps against high variance (overfitting).

Please point out to me what is wrong with my thought process.
Comment: Isn't 1 and 2 the opposite (fewer vs. more)?
Comment: "With fewer features the hypothesis can easier fit the data" <- this seems wrong. Adding features almost by definition makes fitting the data easier (or not harder) - the model can basically ignore features that don't help fit the data. Similarly, "With more features the hypothesis can harder fit the data" seems wrong.
Answer: You have it backwards.  I'm not sure what your reasoning is for your connections (you just stated a belief, not the reasons for that those beliefs), but here are the correct chains of reasoning.
When you expand the number of features under consideration, you create more options for the final, fit model.  When there are more options, you can use your greater flexibility to find a result that is closer to recreating the data as is.  The more you recreate the data as is (i.e. the "harder" you fit the data), the more sensitive your final model is to the data being a bit different.  This sensitivity to the data being a bit different is called variance, so more features means more variance.  More variance is almost by definition more susceptibility to overfitting.
Less variables makes it more likely you left out an important (or even marginally beneficial) predictor.  This means you are less likely to capture the truth accurately, so more bias.
<code>More features => More varaince => Easier to overfit.
Less features => More bias => Easier to underfit.
</code>
Comment: So basically with more features the algorithm has a higher chance to find the "essential" truth and therefore be more prone to overfitting. Thank you, this makes sense.
Comment: @SharifElfouly, overfitting is not about finding the "essential" truth, it is about finding noise in the data (the opposite to the "essential" truth).


Is this an equivalent definition for chain homotopy?

Question: $\newcommand{\del}{\partial}$This is the definition of chain homotopy I am using:

Two chain maps $f,g$ are chain homotopic iff $f-g=\del T + T\del$ for some chain map $T$.

For any two chain maps $f-g$ is also a chain map, so $\del(f-g)=(f-g)\del$. But if $f,g$ are chain homotopic, we have additionally that $\del(f-g)=(f-g)\del=0$, and thus that $\del f=\del g = g\del=f\del$.
Since $T$ is a chain map, $\del T+T\del =2\del T = 2T\del$ (2 here means iterated addition). In particular, $2T$ is a chain map.

Question: The above conditions are necessary for $f,g$ to be chain homotopic, but are they sufficient? I.e., does: $$\del f=\del g =g\del=f\del \implies \exists\text{ a chain map } \psi \text{ such that }f-g=\del\psi?$$ This sort of seems like it would be "integrating" $f-g$, and since I have no special assumptions, I assume as a result that the answer is no. (E.g. the same way that not all closed forms are exact.)
Also, why is the condition for $f$ and $g$ to be chain homotopic not stated as $f-g=\del\psi$ for some chain map $\psi$, since that's all that we need for the homomorphisms of $f$ and $g$ to coincide on homology? (I am aware that most likely not every chain map $\psi$ can be decomposed as $\psi=T+T$ for another chain map $T$, so that $f-g=\del\psi=\psi\del$ does not imply $ f-g = \del (T+T)= \del T + T\del$.)
Would it be correct to say that $f-g=\del\psi$ for some chain map $\psi$ means that they are "chain homologous" (i.e. $f$ and $g$ induce the same homomorphisms on homology, but the condition is necessary but not sufficient to be chain homotopic)?
Comment: First of all, your definition of chain homotopy seems to be wrong: $T$ is not a morphism of chain complexes, it's a map that shifts the degree by $1$, i.e. $T^n\colon C^n \to D^{n-1}$ (in cohomological numeration).
Answer:
If $f^\bullet, g^\bullet\colon C^\bullet\to D^\bullet$ are chain maps, then the correct definition is the following.

A chain homotopy between $f^\bullet$ and $g^\bullet$ is a family of
  morphisms $T^n\colon C^n\to D^{n-1}$ such that for all $n\in \mathbb{Z}$ holds
  $$f^n - g^n = \partial^{n-1}_D \circ T^n + T^{n+1}\circ \partial^n_C.$$

$T^\bullet$ is not a chain map in any sense. The definition just tells that $\partial^{\bullet-1}_D \circ T^\bullet + T^{\bullet+1}\circ \partial^\bullet_C$ is a chain map, which is equal to $f^\bullet - g^\bullet$.

Chain maps that induce the same maps in (co)homology are not necessarily homotopic. Probably the easiest example is the following: fix some $n=2,3,4,\ldots$ and consider the following complex of abelian groups
$$C^\bullet\colon \quad 0 \to \mathbb{Z} \xrightarrow{\times n} \mathbb{Z} \to \mathbb{Z}/n\mathbb{Z} \to 0$$
It is an exact sequence, its (co)homology is trivial, hence the identity morphism $id$ on $C^\bullet$ induces the same morphisms on (co)homology as the zero morphism $0$. But it is easy to see that there is no chain homotopy between $id$ and $0$:
Comment: @William A chain map is a collection of maps $f^n\colon C^n \to D^n$ that commute with the boundary operators in all degrees, that's correct. However, a chain homotopy is not a chain map, and when you write identities like "∂T + T∂ = 2∂T = 2T∂", it's wrong.
Comment: @William I recommend you to write the involved identities with all the indices to see what they really mean degree-wise. You are asking about "$f-g = \partial \psi$" where $\psi$ is a chain map. But if $\psi$ is really a chain map (= a collection of maps $\psi^n\colon C^n\to D^n$ commuting with the boundary operators), then the composition $\partial^n \circ \psi^n$ shifts the degree by one, it's not a chain map and it makes no sense to compare it to $f^n - g^n$.
Comment: This is a good counterexample and makes a lot more sense to me now. Just to confirm I understand your answer before accepting it, is the condition I gave above for two chain maps to induce the same map in homology correct? I was able to prove it was sufficient but not that it was necessary.
Comment: This is sort of how I am interpreting this proofwiki page but im not sure: https://proofwiki.org/wiki/Homotopic_Chain_Maps_Induce_Equal_Maps_on_Homology
Comment: also I should clarify that when I said "chain map" (I don't know if this definition is correct) I meant sequences of homomorphisms of chain complexes which commute with the boundary operator of any degree (not necessarily zero)


How to check if frame source has changed and open source in new window

Question: We are creating a web-based mobile app.  The app has an ad that loads in a narrow frame.  In testing on the iPhone, we noticed that when the ad is clicked, it loads within the ad frame (of the native app), instead of opening in a new window.
We are now looking to detect whether an ad has been clicked by checking the source of the frame.  If the source has changed, we would like to grab that URL and open it in a new window using Javascript.  Then, we would like to reset the source of the frame to the original.
Here is the code we have so far.

<frameset cols='50%,50%'>
   <frame src='play.php?showad' name=adframe>
   <frame src='http://google.com'>
</frameset>

Thanks.
Comment: does appending `&lt1=_new` to the `src` of iframe solve the problem
Comment: Not sure if this matters, but I'm using frames, not iframes.

Just tried and it didn't do anything.  I'm looking to create a new window only when something inside the frame is clicked.
Comment: o0ps! sorry i hurriedly read it and commented...
Answer: From your code, it looks like the ad lives on the same domain? If that is the case, it's probably easiest to just inject a target="_blank" to all a tags in that frame.
Using jQuery (which you included in your example so I'm assuming that is okay to use), this should do it:
    $(adframe.document.body).find('a').attr('target', '_blank');

Comment: The ad actually doesn't live on the same domain and the ad code is also generated via javascript.  For testing purposes, what I have in "play.php?showad" is just a javascript include to a .js file.  Inside the js file, it only has one line of code: document.write("google.com");  In other words, inside the HTML of "play.php?showad" itself, there is no  tag.


Is there a sentence $\phi$ that is entailed by all sentences with the same properties as $\phi$? Does $\phi$ entail all of these sentences?

Question: I'm in an introductory logic class, and I have both of these problems.

Is there a sentence $\phi$ with the following properties? If so, what is it? If not, why?

$\phi$ together with Fa entails Fb
$\phi$ is entailed by all the sentences that, together with Fa, entail Fb

Is there a sentence $\phi$ with the following properties? If so, what is it? If not, why?

$\phi$ together with Fa entails Fb
$\phi$ entails all the sentences that, together with Fa, entail Fb.

For (1), I've reached the conclusion that we want to see if $\phi$ can be derived from all the sentences $\psi$ in the set $\Gamma$ of sentences that, together with Fa, entail Fb.
For (2), I've reached the conclusion that we want to see if every $\psi$ can be derived from one $\phi$.
I reached these conclusions by noting that, by Completeness theorem and Soundness theorem, a sentence is a logical consequence of a set of premises if and only if it is derivable from those premises.
However, I am totally lost on how to prove if my conclusions can be satisfied. On one hand, I feel like the sentence $Fa \rightarrow Fb$ should be able to derive all other satisfactory sentences and vice versa. But on the other hand, the juxtaposition of these two problems leads me to believe that only one of them has a satisfactory sentence $\phi$, and I have no clue how I would determine such a thing if that is the case.
Comment: What are $Fa$ and $Fb$?
Answer: For 1, you can indeed take $Fa \to Fb$:

Together with $Fa$, it implies $Fb$
It is entailed by any $\psi$ that, together with $Fa$ implies $Fb$

Proof: take any such a $\psi$ and any interpretation that sets $\psi$ to true. Now, if this interpretation does not set $Fa \to Fb$ to True, then that means that it sets $Fa$ to True but $Fb$ to false. So, this interpretation would set $\psi$ and $Fa$ to True but $Fb$ to False, which contradicts that $\psi$ together with $Fa$ implies $Fb$. So, any interpretation that sets any such $\psi$ to True must also set $Fa \to Fb$ to True.
For 2, you can simply take $\bot$: this statement by itself implies everything, and so will:

Together with $Fa$ imply $Fb$ ... because $\bot$ implies $Fb$
Imply any $\psi$ for which it is true that $\psi$ and $Fa$ together imply $Fb$ ... because $\bot$ implies any $\psi$


eigen3.3.7 segment fault when std::cout

Question: Describe
I'm writing a toy code with Eigen. But  when I try to print the matrix I, unfortunately, meet the segment fault when cout. The following first code is my project code that meets the segmentation fault. I know that if I just write a tiny code as the second code, it works fine. So I don't know what's the matter with my project code for that it failed in the cout as the pictures show.
C++ Code
The most minimum test code is https://godbolt.org/z/GePx5b
#pragma pack(1)
#include <iostream>
#include <Eigen/Dense>
#include <string>
#include <fstream>
#define BUFFER_SIZE 256
#define WORK_SPACE "PositioningSystem/"

using Eigen::Matrix3d;

int main(int argc, char const *argv[]) {
            Eigen::Matrix3d m;
            m << 1, 2, 3,
                4, 5, 6,
                 7, 8, 9;
            std::cout << m << std::endl;
            return 0;
}

If you write the first code #pragma pack(1), you will meet segmentation fault, and if you delete it, all work fine.
Finally find the bug
In an include file, I write such a code as the following
#pragma pack(1) //指示struct不进行内存对齐

When I delete this code, all is right. Anyone has any thoughts about this bug?
more about this
The same code with the #pragma pack(1) could run on the arm but failed on x86 platform as discussed above.
x86

OS Linux wang-X556UQK 5.4.0-54-generic #60-Ubuntu SMP Fri Nov 6 10:37:59 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
ubuntu 20.04 release
gcc Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
eigen 3.3.7

arm

OS Linux iTOP4412-ubuntu-desktop 3.0.15 #20 SMP PREEMPT Tue Mar 31 22:03:51 CST 2020 armv7l armv7l armv7l GNU/Linux
ubuntu 12.04 customed by vender Linaro 12.04 (GNU/Linux 3.0.15 armv7l)
gcc Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
eigen 3.0.5
Comment: Works for me https://godbolt.org/z/n7zP7T with address sanitizer enabled. Please provide [mcve]. Make sure you have rebuilt project properly.
Comment: @HarryPotter You are not supposed to leak packing overrides outside your private headers. See for example [pragma pack(push) without corresponding pop leads to stack smashing](https://stackoverflow.com/questions/58197050/pragma-packpush-without-corresponding-pop-leads-to-stack-smashing).
Comment: Thanks, I edit my problem. And I try to run the tiny code in a separate cpp file, it works fine. But it meets segmentation fault in my project and I don't know why the cout is wrong.
Comment: I'm guessing that somewhere in your project there is a global variable/constant which initialization contains Undefined Behavior. MSVC 2019 has experimental address sanitizer, so try enable that to locate actual source of problem. You can also try some static code analysis tool. With current information it is impossible to help you. You can also try with other compiler clang/gcc address sanitizer to locate problem.
Comment: If the "Restart from scratch" approach to produce a [mre] does not work, try the "divide and conquer" approach: Keep removing `#include` lines, and if that is not possible anymore, start removing lines from the include files themselves. Make sure to post a self-contained example (as the last step you need to copy the contents of all non-standard headers into your example).
Comment: At the moment, your first code snippet won't even compile, since you removed the `using Eigen::Matrix3d;` -- unless some of the headers also had that line (or even worse, had a conflicting class/typedef with the same name ...)
Comment: Hi, guys, I finally find the bug. I write such a code in an include file
```c++
#pragma pack(1)
```
But I don't know why this make such a serious error, I delete the code and all is right.
Comment: Thanks, I learned the ```#pargma pack ```, and now I know how to solve the errors.
Comment: This got cross-posted as Eigen issue: https://gitlab.com/libeigen/eigen/-/issues/2074 (and rejected)
Answer: Yes, I finally successfully overcome the issue. It's the wrong with the #pragma pack. So, please use the sentence following the #pragma pop, just like the new and delete must be the same to make sure the program is right.

pragma pack(push) without corresponding pop leads to stack smashing
https://gitlab.com/libeigen/eigen/-/issues/2074

eigen3.3.7 segment fault when std::cout


Como faço para inserir um botão depois de uma listview?

Question: Olá, preciso inserir um botão logo após minha listview. Ou seja, quando acabar de deslizar minha listview terá um botão no final.
Estou tentando fazer da seguinte forma:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.gerdaumanagement.gerdaumanagement.tipoMensal"
    android:orientation="vertical">

    <ListView
        android:id="@+id/lista"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true">
    </ListView>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Enviar"
        android:textAllCaps="true" />

</LinearLayout>

Mas ele não aparece no final.
Minha listView está sendo populada:
public List<AvaliacaoMensal> todosMensal() {
        List<AvaliacaoMensal> dados = new ArrayList<AvaliacaoMensal>();
    dados.add(new AvaliacaoMensal("As máquinas e equipamentos possuem selo de liberação por um líder Gerdau e está dentro do prazo de validade?", 'A', "Condição Fisica"));

Comment: É uma lista simples ou esta usando adapter customizado?
Comment: @acklay Adapter customizado.
Answer: Você pode usar Um RelativeLayout, alinhar o Button na parte inferior, fazer com que o ListView ocupe todo o espaço acima de Button, conforme abaixo:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.gerdaumanagement.gerdaumanagement.tipoMensal">

<ListView
    android:id="@+id/lista"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/botao"
    android:layout_alignParentStart="true">
</ListView>
<Button
    android:id="@+id/botao"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Enviar"
    android:textAllCaps="true"
    android:layout_alignParentBottom="true"/>
</RelativeLayout>

Comment: Já tentei assim, mas ele fica sobre minha listview, queria que ele aparecesse só no final da listview. @David Carvalho
Comment: Há realmente necessidade de que seja feita dessa forma? Não é muito recomendável tendo em vista que caso a lista seja longa, o usuário tenha o trabalho de rolar a tela inúmeras vezes apenas para executar a ação de clique do botão. Caso realmente seja isso, o exemplo do Mystic será satisfatório.
Answer: Como estas a usar ListView, você pode usar o método addFooterView, no qual adicionará uma View no rodapé de sua lista, como se fosse o ultimo item. Veja:
Button btnFooter = new Button(this);
btnFooter.setText("Botão Rodapé");
listview.addFooterView(btnFooter);

Outra opção caso você queria que esse botão seja fixo no rodapé do layout, deves usar um RelativeLayout, que seria a sugestão do David. É possível ajustar sua ListView para que ela não fique abaixo do botão.
Comment: PERFEITO! Agora como que eu customizo esse botão? @acklay
Comment: @LucasCharles isso já é outra pergunta. Sugiro que verifique se há aqui no stackoverflow formas de customizar um botão programaticamente. Caso não haja, você pode fazer uma nova pergunta. Se houver mais alguma dúvida a respeito dessa pergunta, podes fazer aqui.
Answer: Adiciona o botão como um item da ListView, você poderá detectar quando o botão foi clicado de duas formas vendo "int id" e "int position" de onItemClick, ou poderá setar "setOnClickListener" no botão.
Exemplo básico:
ListView listView = new ListView(context);

Button button = new Button(context);

button.setText("Enviar");

button.setLayoutParams(new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.WRAP_CONTENT
));

/* Opção 1: Evento diretamente no botao */
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        /*[...]*/
    }
});

listView.addView(button);

/* Opção 2: Detectar se o item clicado é o botão */
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

    }
});

Fiz o exemplo programaticamente sem xml apenas para que possa entender
Comment: E como eu implemento button.setLayoutParams/*[...]*/? @Mystic teria como me dar um exemplo com o XML? Por favor?
Comment: @LucasCharles Adicionei texto no botão e os parâmetros, me diga como está adicionando itens nessa ListView
Comment: Editei la como eu estou adicionando itens na minha lista. Não consigo adicionar apenas o botão. Ele pede outros parâmetros.
Answer: tu pode fazer outra abordagem também.
Demarcando para sua ListView terminar antes do Buttom e usando um scrollView para exibir o conteudo completo da lista, ficaria mais ou menos assim:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/buttom">
    </ListView>

    <Buttom
        android:id="@+id/buttom"
        android:text="Teste"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" >
    </Buttom>
</RelativeLayout>

Nesse exemplo o botão ficará abaixo da tua lista, mas ela irá precisar de um scroll para ser vista por inteira, outra abordagem é ter um scroll na tela inteira e deixar o ListView com tamanho dos conteúdos, ficamdo mais ou menos assim:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ListView
                android:id="@+id/list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_above="@+id/buttom">
            </ListView>

            <Buttom
                android:id="@+id/buttom"
                android:text="Teste"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true" >
            </Buttom>
        </LinearLayout>
    </ScrollView>
</RelativeLayout>

Fora esses pode colocar como último elemento da tua ListView o botão, mas isso tu não vai conseguir fazer direto no xml, é mais fácil seguir o exemplo do amigo Mystic.


nlme() convergence error code = 1

Question: I was trying to use the nlme package in r to do a multilevel linear model.
I have yield as response variable and rainfall as predictor variable for 60 years for 6 different locations (State). I am trying to see whether rainfall has same level of effect on yield in all locations or different effects. In principle, I am trying to see if slope of yield vs rainfall significantly varies between locations. Therefore rainfall is my random effect. I built my model like this:
 # baseline model which only includes intercept
mdl1<-gls(yield ~ 1,data = data, method="ML")

#intercept as random effect
mdl2<-lme(yield ~ 1,data=data,random = ~1|state,method="ML")

 # slope as random effect
mdl3<-lme(yield ~ rain, data = data, random = ~rain|state,method="ML")

##compare the three model
anova(mdl1,mdl2,mdl3)
##this shows me when I add slope as random effect, my model shows better fit compared to baseline model (mdl1)

this is all working fine. The problem starts when I do the same analysis using an another predictor variable (a count data)
 # baseline model which only includes intercept: Works fine
mdl4<-gls(yield ~ 1,data = data, method="ML")

#intercept as random effect - works fine
mdl5<-lme(yield ~ 1,data=data,random = ~1|state,method="ML")

 # include different predictor (break) this time instead of rain
mdl6<-lme(yield ~ break, data = data, random = ~break|state,method="ML")

when i run the mdl 6, this gives me the error
Error in lme.formula(res_yld ~ brk, data = data, random = ~brk | state,  :
nlminb problem, convergence error code = 1
message = iteration limit reached without convergence (10)

I have absolutely no clue why is this happening. Everything worked fine for my first predictor but this does not work on another predictor. What am I doing wrong here? I tried reading about this online but the posts are not very clear to me. I would really appreciate of anyone could me out on this.
Thanks
Comment: How many values of break do you have within each state, i.e., the cross table of break and state w.r.t yield?
Comment: my break data for each State is 48 i.e. i have 48 years of yield data (48 observations of yield) and 48 years of break days (48 observations for break days) for each State. and i am trying to see whether the relationship between yield and break days is similar or different across the States.
Comment: How many different values of yield for each combination of break and state? As your error-code shows, nlme is using the nlminb-procedure. I've experienced strange behaviour of that procedure which for instance shows values for the target function for estimates which can in fact not be evaluated. I would recommend using optim if no bounds are specified and to reduce the number of break and state combination say in half, run nlme, if no problem occurs then increase until error occurs. Then look at the data. This trail and error ususally finds the error quite quickly.
Comment: Another idea is to supply starting values for the optimization. Your process might converge if it started closer to the actual parameter values rather than starting from a random location.
Answer: It probably has something to do with the number of levels of Break, which makes the model to be overparametrized. You should increase the maximum number of iterations for nlminb, see nlmeControl(), the defaul value is 50, then try with higer values:
mdl6<-lme(yield ~ break, data = data, random = ~break|state,method="ML", control=(msMaxIter=100))

Comment: Increasing iterations didn't work for me but this solution did: https://stats.stackexchange.com/questions/40647/lme-error-iteration-limit-reached

nlme() convergence error code = 1


What is setElementConverter and how does it work in Selenium WebDriver?

Question: I have a problem in finding element where page gets refreshed. Now trying to do anything on the element throws below StaleElementReferenceException with a message Element is no longer valid
Looking up this url
there's a note on the above ref url about :
Should you wish to head down this route, the simplest hook point is to call setElementConverter
what or how is the setElementConverter used ? googled up for a bit and couldn't find an actual implementation of the method mentioned.
Comment: Can you give a code snippet which does not work?
Comment: Same here, cannot find info about `setElementConverter`, even in the doc itself and in the source code. And `setElementConverter` (from class `RemoteWebDriver`) is `protected`, so in their cryptic "Should you wish..." hint they also seem to be implying that their "down this route" involves extending `RemoteWebDriver` and calling `setElementConverter` from somewhere in the subclass.
Comment: @bandeesh-r-sirga In case this is an XY question and you're actually just trying to get things working with Selenium, you need to re-find the element once it's stale. If you get a StaleElementException, driver.findElement(By) again and the element will no longer be stale. Elements go "stale" if the DOM tree changes at that node or above it in the hierarchy. Would finding the element again suit your needs, or do you absolutely have to deal with the same stale element that you originally found?
Answer: I think you may be heading down the wrong path by focusing on setElementConverter. As the documentation page you linked suggests, you should simply try to find the element again if it went stale.

If the element has been replaced with an identical one, a useful strategy is to look up the element again.

I think that if you are a beginner Selenium user, you should follow this advice and stop here. Try-Catch the stale element exception and just find the element again without worrying about setElementConverter.

If you are looking into more advanced behavior of Selenium or are dead set in satisfying your curiosity into setElementConverter, then the following lines will matter more.

If you do this automatically, be aware that you may well be opening your tests to a race condition and potential flakiness.
...
Should you wish to head down this route, the simplest hook point is to call setElementConverter.

The documentation is saying that you may try to write something clever in order to automatically repeat the find for the element, but that causes flakiness and race conditions. I don't think anybody in practice actually tries to overcome StaleElementExceptions this way because it's complicated and flaky, and the easiest solution is to re-find the element in your own code.
As @SantiBailors pointed out in his comment, setElementConverter is a protected method in RemoteWebDriver.

Selenium API Documentation for RemoteWebDriver setElementConverter
Selenium source code on GitHub for RemoteWebDriver setElementConverter

JsonToWebElementConverter Class in the source code

It looks like you would extend RemoteWebDriver and inject additional behavior into the "hook" of setElementConverter, or provide your own JsonToWebElementConverter to change that behavior to automatically retry or deal with the stale element.
How you would do this, I'm not sure. This is where my knowledge ends, and I've never heard of anyone taking this advice to hook into setElementConverter. Again, I'd like to reiterate that this probably isn't what you want to be doing, and most likely you just want to find the element again in your own code, which can be done so much more simply by using a try-catch for StaleElementException and trying again after some ThreadSleep or WebDriverWait.
Answer: You can't directly access setElementConverter method of RemoteWebDriver as it is protected. It can be used by extending webdriver.
One of the example of how the setElementConverter can be used, is in QAFExtendedWebDriver of QAF where QAF has extended webdriver and webelement to have additional features like listeners, inbuilt assertion, verification, wait, self-descriptive locator and so on.


installing microsoft server 2008 on RAID drive

Question: Using RAID 1 on a HP G165 G5 server and trying to install windows server 2008, however right at the install screen the windows installation wont find any hard drives.
Ive tried installing HP 4/8 Internal Port SAS HBA with RAID and SCxxGe series HBA Driver for Windows Server 2008 x64 Editions driver, but windows installer wont take it since its unsigned.
Any suggestions on how to accomplish this?
Comment: Just so you understand these things, Windows neither knows nor cares that you are using RAID. What it DOES care about is that you supply the correct drivers. If in doubt, read the documentation.
Comment: I believe the quickspecs note only applies to Windows Server 2003 installations. Server 2008 installer is capable of reading drivers off a USB stick.
Comment: What disks have you got in there and can you confirm you've installed the SC40Ge controller?
Comment: There's also a note in the quickspecs that says "NOTE: A diskette drive is needed to install storage controller drivers during a Windows operating system installation from CD." - have you done this? also what EXACT operating system are you installing, as in very specific version please.
Answer: is that a software RAID? if so, then most likely you need to install the drivers first. I remember I had the same issue with a software RAID server setup too, and I had to install the drivers for the RAID at the beginning of the setup, otherwise windows wouldn't find the disk drives.
Answer: Are you sure you've got the right driver? Did you try the SATA controller driver as well?


django admin ordering not working

Question: in this as you can saw we change order 1, and order 0

while running it still the same
you can saw

using the shell
  title at top and Whats the deal with strings?

while this has to be reverse according to the order`
Courses/model.py
<code>from django.db import models

# Create your models here.
class Course(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=255)
    description = models.TextField()

    def __str__(self):
        return self.title

class Step(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField()
    order = models.IntegerField(default=0)
    course = models.ForeignKey(Course)

class Meta:
    ordering = ['order', ]
</code>
Comment: Is the `class Meta` inside the `class Step` ?
Answer: You have an indentation error. The Meta class for Step, which contains the ordering directive, is not actually inside the Step class. It needs to be indented one level.

django admin ordering not working


Trying to deploy Laravel 4 website on godaddy shared hosting results into exception

Question: I am trying to deploy my laravel4 website in shared hosting where.
I have a website http://healthscapeseries.com so now when I write http://healthscapeseries.com/myappname/public/ I want my app to open . I uploaded myappname inside the folder that corresponds to my websites index page .
I am getting following error:
Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException

11. Symfony\Component\HttpKernel\Exception\NotFoundHttpException
…\vendor\laravel\framework\src\Illuminate\Routing\RouteCollection.php148
10. Illuminate\Routing\RouteCollection match
…\vendor\laravel\framework\src\Illuminate\Routing\Router.php1054
9. Illuminate\Routing\Router findRoute
…\vendor\laravel\framework\src\Illuminate\Routing\Router.php1022
8. Illuminate\Routing\Router dispatchToRoute
…\vendor\laravel\framework\src\Illuminate\Routing\Router.php1001
7. Illuminate\Routing\Router dispatch
…\vendor\laravel\framework\src\Illuminate\Foundation\Application.php775
6. Illuminate\Foundation\Application dispatch
…\vendor\laravel\framework\src\Illuminate\Foundation\Application.php745
5. Illuminate\Foundation\Application handle
…\vendor\laravel\framework\src\Illuminate\Session\Middleware.php72
4. Illuminate\Session\Middleware handle
…\vendor\laravel\framework\src\Illuminate\Cookie\Queue.php47
3. Illuminate\Cookie\Queue handle
…\vendor\laravel\framework\src\Illuminate\Cookie\Guard.php51
2. Illuminate\Cookie\Guard handle
…\vendor\stack\builder\src\Stack\StackedHttpKernel.php23
1. Stack\StackedHttpKernel handle
…\vendor\laravel\framework\src\Illuminate\Foundation\Application.php641
0. Illuminate\Foundation\Application run
…\public\index.php97

Answer: Have you found any solution yet? If not then this might be one of the solution. What needs to be done is as follqws:

Copy all the files and folders including the public folder of your app to the "public html" folder of the shared hosting.
Copy all the contents of the laravel public folder to the "public html" folder.
Now just remove the Laravel's public folder.
Now Open up laravel's bootstrap/paths.php file and then change the change the path
'public' => DIR.'/../public',

to
'public' => __DIR__.'/..',

Now open up the index.php file which was actually in your laravel's public folder but now in the "public html" folder and change
require DIR.'/../bootstrap/autoload.php';
$app = require_once DIR.'/../bootstrap/start.php';

to
require __DIR__.'/bootstrap/autoload.php';

$app = require_once __DIR__.'/bootstrap/start.php';

Now you are good to go. Let me know the update. Good luck.


365 email temporary delay from one source

Question: This happened in the past and is no longer an issue. Status emails about planes are sent frequently and there was a period of time where those mails were delayed by hours. To try and include only pertinent information here is a couple of hops from one message header
<code>Received: from flyht.aero (18.104.22.168) by
 YT3CAN01FT014.mail.protection.outlook.com (10.118.140.148) with Microsoft
 SMTP Server id 15.20.6363.21 via Frontend Transport; Tue, 2 May 2023 17:08:14
 +0000
Received: from ARIA [192.168.1.131] by flyht.aero with ESMTP
  (SMTPD-18.104.22.168) id f4ac00852b1614ec; Tue, 2 May 2023 07:38:46 -0600
</code>
The message was created at 5/2/2023 9:38:46 AM and sent to flyht.aero which passed it off to Microsoft SMTP Server at 5/2/2023 1:08:14 PM. There was several other MS servers it passed though before it reached the recipient but it was a matter of seconds.
My question is how do I interpret this delay. Was the delay in

flyht.aero sending it? or
Microsoft SMTP Server receiving it.

I am not certain because its not outlandish to think the MS throttled them on this day. I am ultimately trying to figure out if I have enough information to prove it was as unknown 3rd party issue of if our MS tenant was telling them to pump the brakes.
If the latter I need to know how to recognize that if it happens again or possibly "whitelist" this sender from throttling... which isnt likely possible. Any insight could be helpful.
Answer: If there aren't other hops in the header between flyht.aero and Exchange Online, the cause may possibly be with throttling.
If the issue happens again, on Exchange Online side you can run message trace for this delayed message and see if you can see this message in "Received" event:
A delay of xx seconds took place prior to Exchange Online.
And if you have access to the SMTP send logs of the flyht.aero server, you can check if you can see following response from Exchange online:
4.5.3 Too many recipients (AS780090)
4.7.500 Server busy. Please try again later from [XXX.XXX.XXX.XXX]. (S77719)
4.7.500 Server busy. Please try again later from [XXX.XXX.XXX.XXX]. (AS77712XXX)
4.7.500 Access denied, please try again later. For more information please go to http://go.microsoft.com/fwlink/?LinkId=526653 . (AS63)
If yes, the delay is caused by throttling in Exchange Online.
You can create a receive connector for this sender to get a much higher throughput before getting throttled.
(By default if messages use the default connector, the throughput would be lower)


Spamassassin DKIM DNS issue

Question: Here is the setup where I encounter my issues :
My computer has the IP 10.6.2.5.
There is a DNS server ns.isp6.lab with the IP 10.6.2.4 (I can reach it).
My computer has Postfix + Dovecot + SpamAssassin installed. I receive emails signed with DKIM from the domain isp6.lab.
They're signed with this domain key : mail._domainkey.isp6.lab
When I do dig mail._domainkey.isp6.lab TXT I get an answer with the public RSA key.
The problem is that Spammassassin doesn't find it, here is a part the header of a received email :
X-Spam-HAM-Report:
* -1.0 ALL_TRUSTED Passed through trusted hosts only via SMTP
*  0.1 DKIM_SIGNED Message has a DKIM or DK signature, not necessarily
*      valid
*  0.0 T_DKIM_INVALID DKIM-Signature header exists but is not valid

So I activated the debug logs in SpamAssassin and here is what I found :
cat spamd.log | grep dkim

Tue Oct  7 16:38:50 2014 [21673] dbg: dkim: performing public key lookup and signature verification
Tue Oct  7 16:39:00 2014 [21673] dbg: dkim: DKIM, email@example.com, d=isp6.lab, s=mail, a=rsa-sha256, c=relaxed/simple, invalid, matches author domain
Tue Oct  7 16:39:00 2014 [21673] dbg: dkim: signature verification result: INVALID (PUBLIC KEY: DNS QUERY TIMEOUT FOR MAIL._DOMAINKEY.ISP6.LAB)

I checked my /etc/resolv.conf:
domain isp6.lab
search isp6.lab
nameserver 10.6.2.4
I am now searching for hours on this issues (it doesn't seem well documented), I checked that I had all CPAN required modules, etc; I really have no idea what else I could do.
Thanks in advance for your help.
Edit : Maybe something can be done in the NET::DNS module? I don't really understand how all these modules are used, configured, and interact with each other.
Answer: Maybe you hit bug related with NET::DNS and spamassassin. It explained in this blog and this SA mailing list. The excerpt from the blog

Net::DNS version 0.76 changed the field name holding a set of nameservers in a Net::DNS::Resolver object: it used to be 'nameservers', but is now split into two fields: 'nameserver4′ and 'nameserver6′.
Mail/SpamAssassin/DnsResolver.pm relied on the internal field name of a Net::DNS::Resolver object to obtain a default list of recursive name servers, so the change in Net::DNS broke that.

Solution:
Check your repo, if they have fixed the issue in newer release. If not, you can apply the patch manually from here
Comment: Thanks !! After seeing your answer, I updated most of my modules with CPAN, and also realized the new versions weren't installed at the same path than the previous ones. I just deleted the previous version of DnsResolver and some others, and it worked :)

Spamassassin DKIM DNS issue


No. of 4 digit numbers such that any two digits differ by more than 1.

Question: Let $\;a_1a_2a_3a_4\;$ be the decimal representation of a $4$-digit number. This number is said to be "non-
adjacent" if for any pair $(i, j)$, where $1 \leq i, j \leq 4$ and $i \neq j$, $|ai – aj| > 1$.
Let P be the probability that a $4$-digit number chosen randomly is "non-adjacent", then P is equal to?
The sample space is obviously $9*10^3$, but I am almost clueless on how to approach the favorable cases. Suppose, that $0$ is not a part of our number. There are 9 ways to chose the first digit, and $7$ for the second, but after the second, the cases start branching out and there seems to be too many possibilities.
The "solution" to this problem, simply states (without explanation):
Non-adjacent numbers with $0$ = $\binom{6}{3}*3*3!$
Non-adjacent numbers without $0$ = $\binom{6}{4}*4!$.
I fail to see the significance of $6$ here.
Comment: Still stuck. What next, after chosing 2 digits from the 4 in total?
Comment: The use of the word "adjacent" is confusing me.  I presume that $1358$ is acceptable.  What about $1324$?
Comment: I believe 1324 isnt acceptable. There is no additional constraint on $i$ and $j$. ANY two digits must differ by more than , i.e, any two digits arent adjacent, is the way I see it.
Comment: So, imagine that the digits need to be ascending.  How many possibilities are there e.g. $1357$, $1358$, etc.  I guess that $0$ is not accepted as an initial digit so that it will need some extra handling,
Answer: Regarding the significance of $6$ in given solution:
Without $0$, we first choose $4$ distinct numbers $y_0<y_1<y_2<y_3$ from $\{1,2,3,4,5,6\}$. We have $\binom{6}{4}$ options. Then let $x_i=y_i+i$ be the four digits of our number. There are $4!$ permutations of these digits, for the total of $\binom{6}{4}\times 4!$ qualifying numbers in this case.
With $0$, the method is similar, with $x_0=y_0=0$, and not counting permutations that begin with $0$.
Answer: Let the four digits be $a, b , c, d$ with $a< b< c< d$ and we know $d\ge c+2\ge b+4 \ge a+6$.  And $0\le a < a+6 \le d \le 9$ so  $0\le a \le 3$ and $6\le d\le 9$.
If we let $b' = b-2; c'=c-4; d'=d-6$ we have a case we $a\le b' \le c'\le d'$ and $0\le a,b',c',d' \le 3$ which should be a more familiar problem.
We can use stars and bars to solve this.  There are $4$ stars (the digits $a,b',c',d'$ aligned in a row) and there are $3$ bars (stakes to place between the variables to indicate when the values switch from one value of $0,1$ or $2$ to the next value $1,2$ or $3$)--- [so for instance the case where $a=0;b'=1;c'=2;d'=3$ would be represented as $[\text{start at }0]a[\text{switch to }1]b[\text{switch to }2]c[\text{switch to } 3]d]\approx a1b2c3d \approx *|*|*|*$ while, going the other way the pattern $|**||**$ would mean $1ab23cd\approx [\text{start at }0][\text{switch to }1]ab[\text{switch to } 2][\text{switch to }3]$ which means $a=b'=1; c'=d'=3$.]---
So there are ${7\choose 3} = \frac {7!}{3!4!} = 35$ ways of choosing the values of $a, b', c', d'$ and $35$ ways of choosing $a, b=b'+2, c=c'+4, d=d'+6$.
And once you have $a,b,c,d$ there and $4!$ ways to arrange them so that there are $35*4! = 840$ such numbers.... except none of them can start with the digit $0$ (else it'd be a $3$ digit number)
So must subtract the case $a=0$ and $a$ is placed in the front and .... oh, bugger....
Okay without $0$ then if we did all the above we would have $1\le a,b',c',d' \le 3$ and when we get to the stars and bars part with have essentially $2$ bars and $4$ stars as we must always start with a fixed bar (we must immediately switch from $0$ to $1$).
So there are ${6\choose 2} = {6\choose 4}$ ways to do that and ${6\choose 4}4!$ total ways with no $0$s.
....
Now lets consider with a $0$.  Well, that would be the same as finding a $3$ digit non-adjacent number with no $0$s and sticking $0$ zero in it somewhere.
For three digit number with no $0$ was have, like above $2$ bars, and $3$ stars and $3!$ ways of arranging that digits so ${5\choose 2}3!$.  and ther are $3$ places to put the zero into it.
So ${5\choose 2}3!*3$.
Answer: A "non-adjacent" number will have four distinct digits. Here are the possibilities:
$$\begin{array}{c} \{0,2,4,6\} \\ \{0,2,4,7\} \\ \vdots \\ \{0,5,7,9\} \\ \{1,3,5,7\} \\ \vdots \\ \{3,5,7,9\}\end{array}$$
In each of these possibilities, we want to choose a system of finding "available" numbers. So, we say that when a digit is chosen, so too is the digit one less than it. So, choosing $9$ also chooses $8$. Choosing $8$ also chooses $7$. Etc. Down to choosing $0$, which does not choose any additional numbers as there are no digits smaller than zero. Thus, with any selection of digits that includes $0$, you wind up with $3$ digits that cannot be chosen. With any selection of digits that does not include zero, you have $4$ digits that cannot be selected.
Suppose we have a $0$ in the number. We know that we cannot start a number with zero, so it must be one of the three digits after the leading digit. There are still three more numbers to choose. There are also three "forbidden" numbers. So, of the $9$ remaining digits, we cannot choose $3$, and there are $6$ remaining. Of those six, choose $3$. Then choose a position for the $0$ (there are three possibilities). Then permute the other three digits.
Suppose we do not have a $0$ in the number. Now, there are four forbidden numbers. Of the ten digits, four cannot be used, so there are six possibilities. We must choose four of them. Then, we permute them.


Dimple x2 axis needs position bind to x

Question: So this question is all about a secondary X Axis and controls I need to render my chart properly.
I have x, x2, y on a stacked bar chart.
I am trying to get x2 series text stuff positioned at the top (success).
I need the x (order by date) bound to the x2 (seems to work).
Now I need to align x2 directly over x. How does this work?
Here is the code:

And here is my jsfiddle work in progress.
Answer: Here was the answer.
Take:
myChart.addSeries("arbNmbr", dimple.plot.area, [x2,y]);
and change it to this:
myChart.addSeries("arbNmbr", dimple.plot.area, [x,y]);
That aligned my X series.

Dimple x2 axis needs position bind to x


Showing the Lie bracket of vector fields is a vector field (from definition)

Question: I have seen a number of proofs that the Lie bracket $[X,Y]$ of two vector fields $X$ and $Y$ is a vector field but I fail to see this from the definition of a vector as the directional derivative $v_\gamma$ along the curve $\gamma :\mathbb{R}\rightarrow M$.
In particular, given $\delta,\sigma$ two curves through a point $p\in M$ corresponding to the vector fields $X, Y$ respectively (not only at $p$, possibly along an open interval of the curve parameters including $p$), can we construct a curve $\gamma$ such that at the point $p$ it corresponds to the Lie bracket $[X,Y]$?
If not, then what would be a more demonstrative proof using the definition of vector fields as smooth sections of the tangent bundle?
Edit: I think I should clarify why I'm struggling with it and where I need it. Sometimes I see definitions of certain vector(tensor) fields are given as they act on some arguments. For example, in this particular case, $[X,Y]: C^\infty(M)\rightarrow C^\infty(M)$ is an $\mathbb R$-linear map such that $[X,Y]f:=X(Yf)-Y(Xf)$. However, I also understand that the set all $\mathbb R$-linear maps $C^\infty(M)\rightarrow C^\infty(M)$ is not the same as the set of all (iii)smooth (ii)sections of the (i)tangent bundle. My effort here is to show property (i) for the Lie bracket. Properties (ii) and (iii) are clear to me.
A similar case that I understand is when proving that set of all such sections is an $\mathbb R$-vector space, I had to prove that the pointwise sum two vector fields $X$ and $Y$ is a vector field. It (i) pointwise belongs to $T_pM$ because sum of two vectors at $p$ is a vector at $p$, is (ii) a section: trivial and (iii) smooth because sum of two smooth functions is smooth under the corresponding topologies and charts.
Comment: What is your definition of Lie bracket?
Comment: @ArcticChar It is defined as $[X,Y]f = X(Yf) - Y(Xf)$. Where the action of a vector field $X$ on a function $f$ on the manifold is defined as pointwise evaluation of the action of the vectors at different points of the manifold. This is where I'm stuck. How can I show that neither $XY$ nor $YX$ are vector fields but the commutator $[X,Y]$ is one, from definition? (I can show how they fail to transform correctly under a chart transition, but I want to have a better understanding of exactly what fails in the definition).
Comment: You can see vector fields as derivations, i.e. those linear maps $C^\infty(M)\to C^\infty(M)$ that verify Leibniz identity: $X(fg)=fX(g)+gX(f)$. Then it is easy to show that if $X$ and $Y$ are derivations that neither $XY$ or $YX$ are, but $[X,Y]$ is a derivation indeed.
Answer: There are usually two definitions for tangent vectors: directional derivatives along curves and derivations of $C^\infty(M)$. While it is somewhat annoying to show that both definitions are equivalent, the fact remains that for some problems one definition is easier to work with than the other (for example, to show that $\mathfrak{X}(M)$ is a Lie algebra, the derivation definition is much easier to work with, but for finding the derivative of the multiplication map in a Lie group the curve definition is much easier to work with), so it is generally useful to be familiar with both definitions and establish early on that they are in fact equivalent.
Now, if we assume the derivation definition, your whole question just turns into a calculation: let $X,Y\in\mathfrak{X}(M)$, and let $f,g\in C^\infty(M)$, then
$$ X(Y(fg)) - Y(X(fg)) = X(Y(f)g) + X(fY(g)) - Y(X(f)g) - Y(fX(g))$$
$$ = X(Y(f))g + Y(f)X(g) + X(f)Y(g) + fX(Y(g)) - Y(X(f))g - X(f)Y(g) - Y(f)X(g) - fY(X(g))$$
$$ = X(Y(f))g - Y(X(f))g + fX(Y(g)) - fY(X(g))$$
$$ = [X,Y](f)g + f[X,Y](g),$$
so that (+the $\mathbb{R}$-linearity properties) $[X,Y]$ is a derivation $C^\infty(M)\to C^\infty(M)$, which makes it into a vector field.


JS, List of dictionary to dictionary of list, based on key

Question: I have a list of dictionaries, which have some attributes, say a url and some information about the url:
[{
    url:"https://example1.com/a"
    something:"ABC"
},{
    url:"https://example1.com/b"
    something:"DEF"
},{
    url:"https://example2.com/c"
    something:"GHI"
},{
    url:"https://example2.com/d"
    something:"JKL"
}]

Now I want to split this into a dictionary of lists, grouped based on the url. For the above, my target data structure is something like this:
{
    "example1.com" : [{
        url:"https://example1.com/a"
        something:"ABC"
    },{
        url:"https://example1.com/b"
        something:"DEF"
    }],
    "example2.com" : [{
        url:"https://example2.com/c"
        something:"GHI"
    },{
        url:"https://example2.com/d"
        something:"JKL"
    }]
}

In python, this might be achieved using the itertools package and perhaps some list comprehension tricks, but I need to do it in javascript/nodejs.
Can someone please steer me in the right direction to do this in javascript?
Cheers.
Comment: Have you tried anything?
Comment: How to group object properties by value has been [asked many times before](https://stackoverflow.com/search?q=%5Bjavascript%5D+object+group+by+value). Surely you can find an existing answer for your problem? Such broad questions will likely be answered with many different approaches, you really should try something first then ask a specific question about an issue you're having with your code.
Answer: data.reduce((groups, item) => {
    let host = new URL(item.url).hostname;
    (groups[host] || (groups[host] = [])).push(item);
    return groups;
}, {});

One-liner (quite cryptic though)
data.reduce((g, i, _1, _2, h = new URL(i.url).hostname) => ((g[h] || (g[h] =[])).push(i), g), {});

Answer:

const dataFromQuestion = [{
    url:"https://example1.com/a",
    something:"ABC"
},{
    url:"https://example1.com/b",
    something:"DEF"
},{
    url:"https://example2.com/c",
    something:"GHI"
},{
    url:"https://example2.com/d",
    something:"JKL"
}];

function listOfDictionaryToDictionaryOfList(input, keyMapper) {
  const result = {};
  for (const entry of input) {
    const key = keyMapper(entry);
    if (!Object.prototype.hasOwnProperty.call(result, key)) {
      result[key] = [];
    }
    result[key].push(entry);
  }
  return result;
}

function getHost(data) {
  const url = new URL(data.url);
  return url.host;
}

console.log(listOfDictionaryToDictionaryOfList(dataFromQuestion, getHost));
Comment: Yep. Thats it. Can work with that for sure. Cheers.
Comment: `result[key] = (result[key] || []).push(entry);`
Comment: If you initialise *result* as `let result = Object.create(null)` you can dispense with the *hasOwnProperty* test as *result* will only have own properties. And `Object.prototype.hasOwnProperty.call(result, key)` seems needlessly verbose, why not `result.hasOwnProperty(key)`?
Comment: @RobG I didn't want to assume the rest of the OP's program was able to handle null-prototype objects. As for Object.prototype.hasOwnProperty.call, this is to avoid the errors that would occur if there were an item whose key is "hasOwnProperty".
Answer: you can use the reduce method on the array object.
let data = [{
    url:"https://example1.com/a",
    something:"ABC"
},{
    url:"https://example1.com/b",
    something:"DEF"
},{
    url:"https://example2.com/c",
    something:"GHI"
},{
    url:"https://example2.com/d",
    something:"JKL"
}];

let ret = data.reduce((acc, cur) => {
  let host = cur['url'].substring(8, 20); // hardcoded please use your own
  if (acc[host])
    acc[host].push(cur);
  else
    acc[host] = [cur];
  return acc;
}, {})

console.log(ret);