text:
Q: Anybody who succeeded in adding "Email Composer" Cordova plugin to Ionic 5 project (for Android12)? I have created a simple Ionic 5 app and would like to add the functionality that would allow sending emails (including those scheduled).
I have tried the https://ionicframework.com/docs/native/email-composer but found myself stuck with this supporting Android 12. Is there anybody who succeeded?

A: I am use Appery.io to do that, they are based on Cordova and I have no issues with their Ionic 5 app working on Android 12 devices.They offer https://docs.appery.io/docs/ionic-5-mailgun-email-sample-app-with-server-code-plugin, https://docs.appery.io/docs/ionic-5-sendgrid-email-sample-app-with-server-code-plugin.  They also offer to try bulk mailing using their SendGridEmail plugin: https://docs.appery.io/docs/using-sendgrid-plugin-for-bulk-mailing.

A: After searching around for a while, I came across Simon Grimm's video in which he added this exact plugin to an Ionic/Capacitor project. Prior to finding the video I was having trouble figuring out how to add the Android configuration properly to AndroidManifest.xml. When running ionic cap sync, I got a warning that I needed to add the following to AndroidManifest.xml:
<intent>
  <action android:name="android.intent.action.SENDTO"/>
  <data android:scheme="mailto"/>
</intent>

But there was no documentation on how exactly to do this. The solution was in the video:
<manifest ...>

    <queries>
        <intent>
            <action android:name="android.intent.action.SENDTO"/>
            <data android:scheme="mailto"/>
        </intent>
    </queries>

</manifest>

The intent element needs to be placed inside <queries>, which should be placed directly within the <manifest> tag (and not inside <application> or <activity>). After doing this, I was able to get the email composer to open up on Android 12 with Gmail.
Reference: https://www.youtube.com/watch?v=AF0jnmbbpbE


text:
Q: Trying to make a console application run at 20 frames per second I'm trying to create a timing mechanism so that a console application that I'm working on runs at roughly 10 frames a second. When I run this code, rather than being a smooth 20 frames a second it is stuttery and freezes often. I'm having trouble debugging this due to the fact that it relies on the DateTime.Now.Millisecond function, so whenever I insert a break into the code it messes up the timings of the application.
do
{
    frameTimer = DateTime.Now.Millisecond;

    if (firstLoop == true)
    {
        timeTillNextFrame = frameTimer + 100;

        firstLoop = false;
    }

    if (timeTillNextFrame < DateTime.Now.Millisecond && DateTime.Now.Millisecond < 901)
    {
        Console.Clear();

        grid.removeFromGrid(ball.xPos, ball.yPos);
        ball.newPos(gridSizeX, gridSizeY, grid.gridArray);
        grid.addToGrid(ball.xPos, ball.yPos, ball.symbol);

        grid.gridDraw(gridSizeX, gridSizeY);

        timeTillNextFrame = DateTime.Now.Millisecond + 50;

        if (timeTillNextFrame >= 1000)
        {
            timeTillNextFrame -= 1000;
        }

    }

A: You don't want DateTime.Now.Millisecond, you want the total milliseconds:
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

var totalMilliseconds = DateTime.Now.ToUniversalTime().Subtract(Epoch).TotalMilliseconds

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular 2 app - get the duration of a mp3 upload I've been trying for a long time to get the audio time (seconds) of a mp3 file upload in my Angular 2 App.
I've tried some different approaches (one of them), but i haven't been able to get it to work yet.
I was hoping to do it the Angular way - without calling document.querySelector(...) or window.URL for the  URL.createObjectURL().
If i try with @ViewChild('file') and a function on the field called with (change) and call it with $event and the ViewChild:
<input #file type="file" class="form-control-file" (change)="setFileField($event, file)">
None of them contains the duration data, but i am able to get the file data through the event:
let files: FileList = event.target.files;
let file: File = files[0];

// File data from the event
lastModified: 1526819830000
lastModifiedDate: Sun May 20 2018 14:37:10 GMT+0200 (CEST) {}
name: "Det lægende samspil mellem det ydre og det indre mørke_pt1 - med Anders Laugesen.mp3"
size: 18792325
type: "audio/mp3"

If i wait and try to loop through the FormGroup data on the (ngSubmit), the data isn't there as well.
I've read about an event called (loadedmetadata) but i can't get it to function in my app.
What should i do to get the duration of this file upload in an Angular 2 app, if i want to do it the Angular way?

A: The best solution i found was to combine angulars (change) and (canplaythrough).
<input type="file" class="form-control-file" (change)="setFileField($event)">
<audio #dom_audio (canplaythrough)="setDuration($event)" id="audio"></audio>

The setFile gets the file from the files list, creates the object url and sets it in on the audio html tag:
setFile(event) {
  let files: FileList = event.target.files;
  if (files.length > 0) {
    this.file = files[0];
  }
  if(this.file.name.match(/\.(avi|mp3|mp4|mpeg|ogg)$/i)){
    let obUrl = URL.createObjectURL(this.file);
    this.dom_audio.nativeElement.setAttribute('src', obUrl);
  }
}

Then, when the audio file can be played through - the .duration property is ready to be saved:
setDuration(load_event): void {
  this.duration = Math.round(load_event.currentTarget.duration);
}

And then i pass this.duration to the post params on ngSubmit and saves it in the database.

Note: Remember to validate the presence of duration. You don't want the user to save the file without this attribute.

I hope it can help somebody.


text:
Q: Can't get nginx to load PHP on OSX So I'm trying to get nginx and php working on OSX.  I followed this guide:
https://www.sylvaindurand.org/setting-up-a-nginx-web-server-on-os-x/
But set up the root to point to Sites in my home folder and put two simple files in there:
index.htm

Here I am!

NGINX is working.

and
index.php

  <title>PHP Test</title>

 <?php echo '
PHP is working!
'; ?>

When I point a browser directly to the html file or configure the nginx.conf to load it first it works fine.  But I can't get it to load any php files, right now it just says "File not found."  I've looked around and found people with similar problems, but none of the solutions I've found fix mine.  I'm new to PHP so I'm flailing in the dark a bit.  Any ideas what I've done wrong?
Here's my nginx.conf:
user  Maddux staff;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root  /Users/Maddux/Sites/;
            index  index.php index.html index.htm;
    }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

        location ~ \.php$ {
            root           /Users/Maddux/Sites/;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
            include        fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
    include servers/*;
}

A: Your location ~ \.php$ block is confusing as your set the root and them immediately override it.
If you want PHP-FPM to use the same document root as nginx in order to find your PHP scripts, the value for SCRIPT_FILENAME should be set to either:
fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;

or:
fastcgi_param  SCRIPT_FILENAME $request_filename;

In your case, both values are identical.
Also, it is not necessary to put an identical root value into every location block, as root is inherited. It is usual to place a single root directive near the top of the server block, and only place root directives within location blocks where the value is different. See this document for more.


text:
Q: Sticky Footer not in correct place I'm making a multipage website and I'm including a navbar and a footer on each page, the navbar is in place and works just fine but my footer is all over the place. In some pages it's exactly where it should be, others it's in the middle of the page but it was like that before I even added page content.
I've tried a few things I found online but nothing's worked so far.
HTML:

    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">    <link rel="stylesheet" href="css/navFooter.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Choose the type of comparison you'd like to make.

                Quick Comparison

                <a href="/a/comparisons?action=indicators&nid=100&nid=200&nid=300&nid=400&nid=500&nid=600&nid=700&nid=800&nid=900&nid=1000&nid=1100&nid=1200&nid=1300&nid=1400&nid=1500&nid=1600&nid=1700&nid=1800&nid=1900&nid=2000&nid=2100&nid=2200&nid=2300&nid=2400&nid=2500&nid=2600&nid=2700&nid=2800&nid=2900&nid=3000&nid=3100&nid=3200&nid=3300&nid=3400&nid=3400&nid=3500&nid=3600&nid=3700&nid=3800&nid=3900&nid=4000&nid=4100&nid=4200&nid=4300&nid=4400&nid=4500&nid=4600&nid=4600&nid=4700&nid=4800&nid=4900&nid=5000&nid=5100&nid=5200&nid=5300&nid=5400&nid=5500&nid=5600&nid=5700&nid=5800&nid=5900&nid=6000&nid=6100&nid=6200&nid=6300&nid=6400&nid=6500&nid=6600&nid=6700">Compare all counties

                Custom Comparison

                Compare selected counties and/or jurisdictions only

CSS:
   html, body {
    height: 100%;
    width: 100%;
}
body {
    padding-top: 90px;
    position: relative;
    overflow: scroll;
}
.footer {
    position: absolute;
    margin: 0;
    width: 100%;
    background-color: #19D8FF;
    padding: 25px;
    border-top: 4px solid #3399CC;
    min-height: 150px;
    max-height: 250px;
}

Footer HTML:

                    Links |
                    Contact |
                    A-Z Index |
                    Site Map |
                    Disclaimer

© 2017 All rights reserved

A: This code should put you in the right direction. I added bottom: 0 and changed the position to fixed. I also removed an uneeded
* tag you had. This will put it at the absolute bottom of the view and always be fixed at the bottom.

 html, body {
    height: 100%;
    width: 100%;
}
body {
    padding-top: 90px;
    position: relative;
    overflow: scroll;
}
.footer {
    position: fixed;
    bottom: 0;
    margin: 0;
    width: 100%;
    background-color: #19D8FF;
    padding: 25px;
    border-top: 4px solid #3399CC;
    min-height: 150px;
    max-height: 250px;
}


text:
Q: recursively fetch paginatedData from an API using a continuation token The Sonatype REST API paginates data in its response with a continuation token placed inside the response body; if the continuation token is null, you know you're on the last page of results.
I would like to recursively fetch all records from the endpoint with fetch (unless there is a better strategy?), updating the url using a query parameter on each recursive iteration and calling the recursive fetch on it, and building a storage structure containing the complete list of records in the function. I have been unsuccessful.
To get the first page of records, this works:
const requestUrl = `https://{baseURL}/service/rest/v1/components?repository=myRepo&group=myGroup`;

// returns first 10 results
async function fetchData(url) {
  let headers = new Headers();
  headers.append("Accept", "application/json");
  headers.append(
    "Authorization",
    "Basic <BASE64-STRING-HERE>"
  );
  const requestOptions = {
    method: "GET",
    headers: headers,
    redirect: "follow",
  };
  // Fetch request and parse as JSON
  const response = await fetch(url, requestOptions);
  let data = await response.json();

  return data;
}

// called at `/api/get-data`
export default async function getData(req, res) {
  try {
    let result = await fetchData(requestUrl);
    res.status(200).json({ result });
  } catch (err) {
    res.status(500).json({ error: "failed to load data" });
  }
}

This returns an object containing an array of 10 records and the continuation token, a string, e.g.
{"items":[{"id": 1, "name": "itemOne"}, {"id": 2, "name": "itemTwo"}, etc.],"continuationToken":"07929bf0c78cf6c92d4acd0bf5823d80"}}

On the last page of records, the continuationToken is null:
{"items":[{"id": 99, "name": "itemNinetyNine"}, {"id": 100, "name": "itemOneHundred"}, etc.],"continuationToken": null}}

To get the complete set of records using recursion, this is the strategy I have tried, but haven't been successful:

async function recursivelyFetchData(url) {
  let headers = new Headers();
  headers.append("Accept", "application/json");
  headers.append(
    "Authorization",
    "Basic <BASE-64-STRING>"
  );
  const requestOptions = {
    method: "GET",
    headers: headers,
    redirect: "follow",
  };
  try {
    // Fetch request and parse as JSON
    const response = await fetch(url, requestOptions);
    let data = await response.json();
    // create a storage array
    let storage = [];
    // Set a variable for the next page url
    let nextPageUrl;
    // if the initial response contains a continuation token, start to recurse
    if (data.continuationToken) {
      // remove the query param so we don't keep adding it to the url string on each iteration
      let strippedUrl = url.replace(/&continuationToken=.*/g, "");
      // create the url with the query param
      nextPageUrl =
        strippedUrl + `&continuationToken=` + data.continuationToken;
      // store the next response
      let nextPageResponse = await recursivelyFetchData(
        nextPageUrl,
        requestOptions
      );
      // parse
      let nextPageData = await nextPageResponse.json();
      // add to storage
      storage = [...data, ...nextPageData.items];
    }
    // break recursion
    return storage;
  } catch (err) {
    res.status(500).json({ error: "failed to load data" });
  }
}

export default async function getData(req, res) {
  try {
    let result = await recursivelyFetchData(requestUrl);
    res.status(200).json({ result });
  } catch (err) {
    res.status(500).json({ error: "failed to load data in getPackages" });
  }
}

I've tried the approaches found here, here, here, here, and here, but this API is different from other paginated responses in that it relies on a continuation token in the response body, and I can't for the life of me figure out how to recursively add the query parameter to the url, continue iterating until the continuation token is null, then break recursion.
Any help is appreciated.

A: Here is what I think is a simple approach.  fetchAllPages fetches the first page, and then checks to see if the result has a non-nil continuation token.  If it doesn't we just returns the items from the result.  But if it does, we merge that token into a new url and recur, combining the current items with the newly-fetched ones into a single array.
Relying on a helper addToken function that builds our URL, it looks like this:
const fetchAllPages = (url) => fetch (url)
  .then (res => res .json ())
  .then (
    ({items, continuationToken: token}) => token
      ? fetchAllPages (addToken (url, token)) .then (newItems => [...items, ...newItems])
      : items
  )

We alter it slightly to show where your header manipulation and such would fit, in a snippet that uses a dummy fetch function that returns item0 - item33 paginated in groups of ten and an implementation of addToken that does URL manipulation using DOM methods (rather than string parsing/hacking):

const addToken = (base, token) => {
  const url = new URL (base)
  const searchParams = new URLSearchParams (url .search)
  searchParams .set ('continuationToken', token)
  url .search = searchParams
  return url .toString ()
}

const fetchAllPages = (url) => {
  // configure fetch parameters (headers, etc.)
  return fetch (url, /*headers, whatever*/)
    .then (res => res .json ())
    .then (
      ({items, continuationToken: token}) => token
        ? fetchAllPages (addToken (url, token)) .then (newItems => [...items, ...newItems])
        : items
    )
}

fetchAllPages ('https://baseURL.com/service/rest/v1/components?repository=myRepo&group=myGroup')
  .then (console .log)
  .catch (console .warn)
.as-console-wrapper {max-height: 100% !important; top: 0}
<script>
// dummy version of `fetch` to demo without a real server
const fetch = (() => {
  const data = Array .from ({length: 34}, (_, id) => ({id, name: `item ${id}`}))
  const pageSize = 10
  return async (s) => {
    console .log (`fetching '${s}'`)
    const url = new URL (s)
    const searchParams = new URLSearchParams (url .search)
    const start = searchParams .get ('continuationToken') || '0'
    const startIndex = data .findIndex (({id}) => id == start)
    const token = startIndex < 0 || (startIndex + pageSize >= data.length) ? null : data [startIndex + pageSize] .id
    return {json: () => ({
      items: data .slice (startIndex, startIndex + pageSize),
      continuationToken: token ? String (token) : null
    })}
  }
})()
</script>


text:
Q: He {would be / would have been} about twenty when he crossed the Pacific
He would be about twenty when he crossed the Pacific on a yacht alone.
  (From a Korean English grammar textbook)

If I re-write the sentence above in this way

He would have been about twenty when he crossed the Pacific on a yacht alone.

it seems somewhat is awkward.
Is it strange? If yes, what's the reason?

A: Your first sentence is ambiguous; it may represent either of two different uses of would.
If Google is translating your grammar book approximately correctly (which is not something I put a great deal of confidence in!), it seems to offer this sentence as an example of both a) would, used as the past tense of will, and b) would, used to 'speculate about the past'. These two are not entirely compatible.
Let's begin with a) would, used as the past tense of will. In this case, your sentence represents sentence A1 'backshifted' into the past as A2. I've added clauses on the front and back to clarify the time references:

A1. [She says    today    that] he  will  be about twenty when he crosses ...  [next year].
A2. [She said ten years ago that] he would be about twenty when he crossed ... [the next year].

The 'speculative' use of b) would, is different: it represents its clause as uncertain, based on inferences or on counterfactual conditions.

B1. [If he had not died,] he would be about twenty ....
B2. [If her math is right,] he would be about twenty ...

But note that there is a significant difference between B1 and B2. B1 requires he would be, because it is counterfactual. B2, however, may just as correctly be expressed as he is—or even he will be.

B3. [If her math is right,] he will be about twenty ...

(Will is tolerated because where inference is involved, will no longer necessarily bears a 'future' implication. Its sense is still sequential; but the sequence is logical rather than temporal, as when we say "A follows logically from B".)
Accordingly, backshifting this sort of speculative clause can be effected with the same form as in A2:

B4. [If her math was right,] he would be about twenty ...

However, this represents a past speculation about what were then present (or future) contingencies. If you want to represent a present speculation about past contingencies, you need a different construction:

C1. [If her math is right,] he was about twenty ...
OR
C2. [If her math is right,] he would have been about twenty ... [preserving would]

So whether the construction is awkward depends on what you mean.


text:
Q: How to list group of words? I have a column which lists:

Column 1

group A - group B - group C - group D

type A - type B - type C - type D

colour A - colour B - colour C - colour D

How can I separate them into 4 different columns ie

Column 1

group A

type A

colour A

Column 2

group B

type B

colour B

Column 3

group C

type C

colour C

Column 4

group D

type D

colour D

Can anyone help please?

A: I found a solution working :
import pandas as pd

#Initialize a dataframe same as yours
article = {'ID': ['123','456','782'],
            'Location': ["PO9","PO10","PO20"],
            'Reporter': ["Jhon Smith","Mary White","David Mason"],
            'Date': ["20/12/2020","13/05/2020","04/05/2019"],
            'Organisation': ["Best Eastern","Great Supply","Speedy Courrier"],
            'Department': ["Finance","Marketing","Logistic"],
            'Tags': ["Payement - Transfer - Delay - Chase","Design - Artwork - Demo - Service","KPI - Performance - Review - Planning"]
            }

df = pd.DataFrame(article)

#df is Your Dataframe and that is where we start working with it

Tags_column= df['Tags'].values.tolist()

Tags_column = [element.split(" - ") for element in Tags_column]

Results = [[line[index] for line in Tags_column] for index in range(len(Tags_column[0]))]

for index,tag in enumerate(Results):
    df["tag_"+str(index)] = tag

#Show the final dataframe
print(df)
"""
    ID Location     Reporter        Date     Organisation Department                                   Tags     tag_0        tag_1   tag_2     tag_3
0  123      PO9   Jhon Smith  20/12/2020     Best Eastern    Finance    Payement - Transfer - Delay - Chase  Payement     Transfer   Delay     Chase
1  456     PO10   Mary White  13/05/2020     Great Supply  Marketing      Design - Artwork - Demo - Service    Design      Artwork    Demo   Service
2  782     PO20  David Mason  04/05/2019  Speedy Courrier   Logistic  KPI - Performance - Review - Planning       KPI  Performance  Review  Planning
"""


text:
Q: How do I dynamically prevent ASP.NET view state from being validated or deserialized? Given some shared code that is executed on the Init phase and passed a reference to the page the request is being made to, how can I prevent the page's view state from being validated or deserialized?
I've tried the obvious approach of setting the page's ViewStateMode to Disabled, but view state validation still occurs.
In my specific scenario, I have a shared piece of code that knows view state validation is going to fail. I want to prevent the validation exception, as the user is going to be redirected at the beginning of the Load phase. The redirect is done by third-party code, and I don't know where it is going to redirect to, which prevents me from doing the redirect on Init.

A: If your only recourse is to set EnableViewStateMac to false, you're out of luck. ViewState validation is now mandatory.
http://blogs.msdn.com/b/webdev/archive/2014/09/09/farewell-enableviewstatemac.aspx


text:
Q: how to display a numeric value if certain height is reached in a block?(Using jQuery) I have following snippet of html and css

tag1

tag2

tag

tag4

tag5

:root {
  --lh: 1.5rem;
  --max-lines: 3;
}
.tags {
  max-height: calc(var(--lh) * var(--max-lines));
  overflow: hidden;
}

.tags p {
  display: inline-block;
}

So, here the height of the tags is limited to 3 lines by setting the *max-height and any content overflown will be hidden.
Here, I want to display the overflown tags as +1 if one tag is overflown and +2 if two are overflown and so on. For this I could create a span tag and set the text of it to the number but how could I calculate how many tags are overflown.
How could I achieve this with jQuery?

A: This entire task can easily be handled with jQuery. First hide all the tags then show each up to the limit. Below I added a data-limit attribute to the container allowing multiple instances of .tags to each have their own limit.

$(document).ready(function() {
  $('.tags').each(function() {
    let $bag = $(this)
    let $tags = $bag.find('p')
    let limit = parseInt($bag.data('limit'))
    let over = $tags.length - limit
    $tags.hide();
    if (over) {
      $('
+' + over + '
').appendTo($bag)
    }
    $tags.each(function(index, tag) {
      if (index < limit) {
        $(tag).show()
      } else {
        return false
      }
    })
  })
})
.tags {
  border: 1px solid red;
}

tag1

tag2

tag

tag4

tag5

tag1

tag2

tag

tag4

tag5

tag1

tag2

tag


text:
Q: flot legend swatch usage Hello and thanks in advance for the help, guidance and encouragement.  I am something of a crack coder... largely self taught and semi successful.
So here is the challenge.  I have a flot plot, which has a custom built legend with the color swatches, persistent swatches (they don't turn off), data set toggling and everything.  But the swatches only appear if I have the default legend visible.  That is, is I set the legend to "show : false" the swatches do not display in my customized legend either.
Is there a way to turn off / hide the default legend yet still access the color pallet / swatches available for the custom legend?
Here is the code chunk... it has a few other things going on, some of which I cut out for clarity...
  var options = {
      yaxis: { min: 0 },
      xaxis: { tickDecimals: 0 },
      xaxes: [{
            axisLabel: 'Frequency (Hz)',
        }],
        yaxes: [{
        position: 'left',
        axisLabel: 'Power (dB)',
        }],
        series: {
                lines: {
                    lineWidth: 2,
                    show: true
                },
                points: {
                    show: false
                }
        },
        legend: {
            container: $("#labeler<?php echo $i ?>"),
            show: true,
            labelFormatter: function(label, series) {

         }
    },
    grid:{
        hoverable: true
       }

     };

     var track = 0;
    // hard-code color indices to prevent them from shifting as
    // datasets are turned on/off
    var i = 0;
    $.each(datasets, function(key, val) {
        val.color = i;
        ++i;
    });

    // insert checkboxes
    var choiceContainer = $("#choices<?php echo $i ?>");
     choiceContainer.append('

');
    $.each(datasets, function(key, val) {
            track = track + 1;
            if (track == 1){
                choiceContainer.append('Left Channel	');
            } else if(track == <?php echo $tracks ?>){
                choiceContainer.append('

');
                choiceContainer.append('Right Channel	');
            }
            choiceContainer.append('<input type="checkbox" name="' + key +
                               '" checked="checked" id="id' + key + '">' +
                               '
<bar />
'
                                + val.label + '	');

    });
    choiceContainer.append('

');
    choiceContainer.find("input").change(plotAccordingToChoices);

    function plotAccordingToChoices() {
        var data = [];

        choiceContainer.find("input:checked").each(function () {
            var key = $(this).attr("name");
            if (key && datasets[key])
                data.push(datasets[key]);
        });

         if (data.length > 0){
             $.plot($("#placeholder<?php echo $i ?>"), data, options);
         }
    }
    plotAccordingToChoices();

        $('.legendColorBox > div').each(function(i){
            $(this).clone().prependTo(choiceContainer.find("bar").eq(i));
        });

A: From your code it looks like you are appending your "custom" legend to a clone of the legend built by flot. If you disable the flot legend then your $('.legendColorBox > div') selector won't find anything to clone. You can hack it and hide the original flot legend after the clone or remove your requirement on the flot legend entirely.
To hide the original legend, simply do:
$('.legend').eq(0).css('display','none');

After your $.plotcall.


text:
Q: Plotting a Function With Noise I always wondered how such pictures are made:

I am working with the R programming language. I would like to plot a parabola with "random noise" added to the parabola. I tried something like this:
x = 1:100
y = x^2
z = y + rnorm(1, 100,100)

plot(x,z)

But this is still producing a parabola without "noise".
Can someone please show me how I can add "noise" to a parabola (or any function) in R?
Thanks!

A: In this case you need to generate 100 random points or will be adding the same amount of noise to each point (thus no noise).  z = y + rnorm(100, 100,100)
x = 1:100
y = x^2
z = y + rnorm(length(y), 100,100)

plot(x,z)

A: In your code you add the same value to all your points so it just shifts your curve up by that constant. Instead you need to generate a vector of random noise the same length as your y variable. Also you probably want to set the mean = 0 for the rnorm() noise so that it's truly random noise around the true value not systematically 100 units larger.
To get something very similar to your example, you can overplot the second vector with noise using lines() and add a legend with the code below.
x = 1:100
y1 = x^2
y2 = y1 + rnorm(100, 0, 500)

plot(x, y1, type = "l", ylab = "y")
lines(x,y2,type = "l", col = "red")
legend(
  x = "top",
  legend = c("y1", "y2"),
  col = c("black", "red"),
  lwd = 1,
  bty = "n",
  horiz = T
)

Created on 2022-11-08 with reprex v2.0.2


text:
Q: angular, ng-class with function inside repeat I'm trying to put a class on an input if it meets certain requirements and am having problems
it looks like so -
 ng-class="'isPartial': canPartial($index)"

This is inside a repeat, the function it's referring to looks like so
$scope.canPartial = function(index) {
     var needsMet = _.reduce($scope.allAccounts[index].schools, function (memo, schools) {
  return memo + (schools.selected ? 1 : 0);
}, 0);
     console.log(needsMet);
return (needsMet === $scope.allAccounts[index].schools.length);
};

so it's using underscore.js to check if all its children are checked. I know the function works correct, however my issue is passing it as the condition for the ng-class. So if it returns true it will add the class. I'm getting a $parse.syntax error and I cannot seem to figuire out why because I se other examples of ng-class using a function. Perhaps it's because I'm trying to pass the $index, however it is inside a repeat, but I don't know if that causes an issue.
Any help would be much appreciated. Thanks!

A: Your ng-class expression is invalid.
Change your ng-class declaration in order to take an object as a value:
ng-class="{'isPartial': canPartial($index)}"


text:
Q: Regex in Python - Substring with single "re.sub" call I am looking into the Regex function in Python.
As part of this, I am trying to extract a substring from a string.
For instance, assume I have the string:
<place of birth="Stockholm">

Is there a way to extract Stockholm with a single regex call?
So far, I have:
location_info = "<place of birth="Stockholm">"

#Remove before
location_name1 = re.sub(r"<place of birth=\"", r"", location_info)
#location_name1 --> Stockholm">

#Remove after
location_name2 = re.sub(r"\">", r"", location_name1)
#location_name2 --> Stockholm

Any advice on how to extract the string Stockholm, without using two "re.sub" calls is highly appreciated.

A: Sure, you can match the beginning up to the double quotes, and match and capture all the characters other than double quotes after that:
import re
p = re.compile(r'<place of birth="([^"]*)')
location_info = "<place of birth=\"Stockholm\">"
match = p.search(location_info)
if match:
    print(match.group(1))

See IDEONE demo
The <place of birth=" is matched as a literal, and ([^"]*) is a capture group 1 matching 0 or more characters other than ". The value is accessed with .group(1).
Here is a REGEX demo.

A: print re.sub(r'^[^"]*"|"[^"]*$',"",location_info)

This should do it for you.See demo.
https://regex101.com/r/vV1wW6/30#python

A: Is there a specific reason why you are removing the rest of the string, instead of selecting the part you want with something like
location_info = "<place of birth="Stockholm">"
location_info = re.search('<.*="(.*)".*>', location_info, re.IGNORECASE).group(1)

A: this code tested under python 3.6
 test =  '<place of birth="Stockholm">'
 resp = re.sub(r'.*="(\w+)">',r'\1',test)
 print (resp)

 Stockholm


text:
Q: MapBox SDK for iOS fire tapOnCalloutAccessoryControl manually I was wondering if there is a possibility to fire the tapOnCalloutAccessoryControl method for a marker in code? For instance, I have list of all the markers, and when a user clicks a marker in the list, I zoom to that location, but I would love to get the callout to popup. Is this possible? Thank you.

A: Getting the callout to pop is different from the accessory control. The latter is the (typically chevron-image) control in the callout once it is popped up, the "go to more detail" button, basically.
To get a callout to popup, check out -[RMMapView selectAnnotation:] and friends.


text:
Q: Laravel 4.2 Email::queue with assets Simple, I am trying to queue an email using services beanstalkd and supervisord like so:
Mail::queue('emails.congratulations', $user, function($message) use($user) {
    $message->to($user['email'], $user['name'])
        ->subject('Congratulations!');
});

My supervisor program config:
[program:emailservice]
command=php /path/to/laravel/artisan queue:listen
stdout_logfile=/path/to/laravel/app/storage/logs/emailservice_supervisord.log
redirect_stderr=true

In my blade file I am trying to access an asset, an image:

When the email is sent and received, the image is broken and the URL to the image looks like this:

I cannot figure out why the domain is :
If anyone else as experienced this behavior it would be good to get this out in the open because I have scoured Google and StackOverflow for answers to this issue without any mention of the issue.
A question I ask myself... when queuing, is Laravel/Supervisor/Beanstalk smart enough to remember the domain for the job?

A: You have to set application url to your domain (http://localhost by default) in config/app.php.


text:
Q: grep output to pip install How to take a subset of python dependencies in  requirements.txt and using grep send them to pip install?
Let's say I want to install redis and gunicorn only: with
cat requirements.txt | grep "redis\|gunicorn"

I get only the dependencies I want,
redis>=3.5.3
gunicorn>=20.1.0

but I would like to pass it as requirement file to pip install.
I guess I should create a temp file with the output of grep and do something like pip install -r tempfile, but I don't understand how to do it.
Could anyone help me?

A: You can use xargs to pass the outputs to pip:
grep "redis\|gunicorn" requirements.txt | xargs pip install


text:
Q: Generate project files from Publish profile I've accidentally deleted project files but have got Publish Profile folder. Is there a way to generate project files back from Publish Profile folder? Thanks

A: No. A publish profile contains information about publishing a project, not what that project looks like.
Next time, use source control and take regular backups of important files.


text:
Q: FragmentPagerAdapter crash I try to build viewPager with several fragments.
But when I launch app I get crash with text

Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference

my code is following:
    public static class MyPagerAdapter extends FragmentPagerAdapter {
        private static int NUM_ITEMS = 4;

        MainFragment main;
        CartFragment cart;

        public MyPagerAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);

            main = new MainFragment();
            cart = new CartFragment();
        }

        // Returns total number of pages
        @Override
        public int getCount() {
            return NUM_ITEMS;
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return main;
                case 1:
                    return null;
                case 2:
                    return null;
                case 3:
                    return cart;
                default:
                    return null;
            }
        }
    }

A: Use below code for calling Fragments...
  @Override
    public android.support.v4.app.Fragment getItem(int position) {
        Fragment f = new Fragment();
        switch (position) {
            case 0:
                f = new LogoFragment();
                break;
            case 1:
                f = new AboutUsFragment();
                break;
            case 2:
                f = new ServicesFragment();
                break;
        }
        return f;
    }

A: this is my way to use it :
public class ViewPagerAdapter extends FragmentPagerAdapter {

ArrayList<PagerFragments> mFragments;

public ViewPagerAdapter(FragmentManager fm) {
    super(fm);
    this.mFragments = new ArrayList<>();
}

public void addFragment(Fragment fragment,String title) {
    PagerFragments t = new PagerFragments();
    t.setTitle(title);
    t.setFragment(fragment);
    mFragments.add(t);
    notifyDataSetChanged();
}
public void addFragment(Fragment fragment) {
    PagerFragments t = new PagerFragments();
    t.setFragment(fragment);
    mFragments.add(t);
    notifyDataSetChanged();
}
//This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int position) {
    return mFragments.get(position).getFragment();
}

// This method return the titles for the Tabs in the Tab Strip

@Override
public CharSequence getPageTitle(int position) {
    return mFragments.get(position).getTitle();
}

// This method return the Number of tabs for the tabs Strip

@Override
public int getCount() {
    return mFragments.size();
}

}
PagerFragment.java :
import android.support.v4.app.Fragment;

public class PagerFragments {
Fragment fragment;
String title;

public Fragment getFragment() {
    return fragment;
}

public void setFragment(Fragment fragment) {
    this.fragment = fragment;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

}
Then in fragment or activity :
  private ViewPagerAdapter viewPagerAdapter;
viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
                    viewPagerAdapter.addFragment(new RTopGainLossFragment(oneDay), "1D");
                    viewPagerAdapter.addFragment(new RTopGainLossFragment(oneWeek), "1W");
                    viewPagerAdapter.addFragment(new RTopGainLossFragment(oneMonth), "1M");
                    viewPagerAdapter.addFragment(new RTopGainLossFragment(oneYear), "YTD");
                    viewPagerAdapter.addFragment(new RTopGainLossFragment(ytd), "1Y");
                    viewPagerAdapter.addFragment(new RTopGainLossFragment(max), "MAX");
                    viewpager.setAdapter(viewPagerAdapter);
                    tab.setupWithViewPager(viewpager);


text:
Q: Using ng-options to show object property but bind index with ng-model I'm trying to display a list of the names of the teams in a league, and select one. When selected, it should place the index of league.teams[index] into homeTeam.teamId. Here is the HTML:
<select
    ng-model="homeTeam.teamId"
    ng-options="team.name for team in league.teams">
</select>

And here the scope:
$scope.league = {
    teams: [
        { name: "Team#1" },
        { name: "Team#2" }
    ]
};

But it adds the whole object into homeTeam.teamId, like this:
homeTeam: {
    "teamId": { "name":"Team#1" }
}

How can I get it to just input the index, i.e.:
homeTeam: {
    "teamId": 0
}

A: If you want an id then the teams should have one:
ng-options="team.id as team.name for team in league.teams"
Alternative:
ng-options="league.teams.indexOf(team) as team.name for team in league.teams"
indexOf() is not supported by IE < 9


text:
Q: How to remove small objects from 3D image?
Do you see that?There are some small objects spread below the brain. and I want to remove them to get a whole clean brain.
A 3D image can be expressed as a 3D array in Numpy.
Below is an approach to remove small objects in 2D image.
from skimage import morphology
img_size = img.shape[0] * img.shape[1]
new_img = morphology.remove_small_objects(img, img_size*0.1)

A: Here is my solution:

from skimage import morphology

    def remove_small_objects(img):
        binary = copy.copy(img)
        binary[binary>0] = 1
        labels = morphology.label(binary)
        labels_num = [len(labels[labels==each]) for each in np.unique(labels)]
        rank = np.argsort(np.argsort(labels_num))
        index = list(rank).index(len(rank)-2)
        new_img = copy.copy(img)
        new_img[labels!=index] = 0
        return new_img


text:
Q: Creating a main page view with templates from Pycharm's Django IDE I am trying to get template information into my view file and I keep getting an error that my output is indented wrong.  am i doing this right?
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
def main_page(request):
   template = get_template('main_page.html')
   variables = Context({
       'head_title': u'Django Bookmarks',
       'page_title': u'Welcome to Django Bookmarks',
       'page_body': u'Where you can store and share bookmarks'
       })
         output =  template.render(variables)
         return HttpResponse(output)

I keep receiving an indentation error and i don't know what's going on.  thanks ahead of time for any help

A: The traceback should tell you which line the indentation is on.
In the code you've pasted above, the final two lines are incorrectly indented. They should be in line with variables = ....


text:
Q: Android Studio does not detect my Moto G I've connected my phone in the Camera mode, I have installed the latest motorola drivers from https://motorola-global-portal.custhelp.com/app/answers/detail/a_id/88481/action/auth. And I've also installed the avd from
http://forum.xda-developers.com/showthread.php?t=2588979
My device is just not showing up in the available devices when I try testing my app. Please help.

A: Enable USB debugging on the device (Developer options).

A: I've followed this link https://www.youtube.com/watch?v=Qb2olFyoMV4 and it worked well with my Moto G 2nd Generation.
When I try to see the logs from my device on Android Monitor, I had to unlock my device and there was a message asking if it was ok to debug from this computer.
Allow USB Debug message
Hope it works for you too.


text:
Q: Different approaches for accessing OpenSSL from Node.js I am looking for a way to integrate OpenSSL and Node.js for a while now.
My goals are:

*

*I want to be platform independent, hence a solution should work on OS X, Linux and Windows.

*I want to avoid unnecessary disk operations. E.g., a private key might not be in a file, but in a database (may be a stupid example, but let's consider this to be a valid requirement).

*I want to support creating keys, csrs, signing csrs, creating ca certs, ... all the certificate stuff, from end to end.

Now the options I have considered are:

*

*Use the OpenSSL library which is integrated within Node.js. Unfortunately, the crypto module does not provide the certificate things.

*Use the OpenSSL library using an external module. Unfortunately, I don't know how to do this, probably due to missing knowledge in C/C++.

*Use the OpenSSL binary as a child process. Given that OpenSSL is available, this should work on all platforms. It's not nice, but it works.

Question #1: As I have written I do not have the slightest idea on how access the OpenSSL library directly that comes bundled with Node.js. How would I approach this?
At the moment, I stick with using the binary as a child process. Unfortunately, this requires that all the things such as private keys and so on are either given as files (which I explicitly want to avoid), or that I hand over everything using /dev/stdin (which does not work on Windows).
Question #2: How could I deal with this? Would a solution to #1 solve this issue, too?

A: The answer to question #1 is that you cannot. Without bindings, you can only access the functions exposed by nodejs.
Unfortunately there doesn't seem to be a way work around for /dev/stdin in windows. Namedpipes would be an option but nodejs does not support them. You may be able to have nodejs launch openssl.exe in interactive mode and send commands through stdin, and read the output through stdout but this seems very inefficient.
So the answer is question #2 is that you cannot deal with the windows problem.
Writing your won binding seems to be the only option. It's actually not so difficult - something I'm sure you could get collaborators to help with.


text:
Q: How to display the Group name field in continuous pages in Crystal Report? I have created one crystal report which has one Group name field too. My Crystal report has 3 pages. But the Group Name field is displayed only in the first page. I want to display the Group Name field in the next pages also. Any one help me.
I am using Crystal Reports 2008.

A: You can put the group name field in group header section and check "Repeat group header in each page" in group options (available via group expert).


text:
Q: Fixed Navigation when Scroll down The script is working, when scrolling down it does place the navContainer at the top of the window but unfortunately there're a couple of small issue that are driving me bananas!

*

*I want this function to get fired right after the the outerHeight of the header (page title). With the code i have it does it but a few pixels a little before than it should. Take a look at the letter "g", .navContainer should stick to the top right after it passes the last pixel of the letter(which is the height of its container) but it does it a few pixels before (i would say 10 px). Fixed

*If the view port is less than 960px the issue is that the .f-nav goes 100% of the viewport but what i want it to go 100% of its parent container .container -its parent container is inheriting this attributes from its parent container .wrapper, which has a max-width:60em; margin: 0 auto;and padding:0em 0.5em;
I'm more concern about the second issue than the first one, any idea how to solve this issue? Let me know if you want more details. The snippet below is also on Codepen.

function testFunction(){/*alert("test");*/

 $(window).scroll(function () {
         var nav = $('.navContainer');
    var headerHeight = $('.headContainer').outerHeight();
  if ($(this).scrollTop() > headerHeight) {
 //  $('.f-nav').width($('.nav').width());
            nav.addClass("f-nav");
            $('.nav-wrapper').css('background','#f7f7f7');
  } else {
   nav.removeClass("f-nav");
  }
 });

    };
    testFunction();
body{margin:0;}
.wrapper{
  margin:0 auto;
  padding:0em 0.5em;
  max-width:60em
}
.container{
  background:gray;
}
.navContainer{
  border-top:2px black solid;
  border-bottom:2px black solid;

}
.navContainer ul {
  list-style:none;
  margin:0;padding:0;
}
.headContainer{
  height:100%;
  color:white;
  font-family:'tahoma';
  font-size:50px;
  padding-bottom:30px;
}
.navContainer ul{background:green;}
.navContainer li{
  display:inline;
  padding:0px 50px;
  vertical-align:middle;
  background:red;
  margin:0px;
  margin-right:10px;
}
.wrapper img{width:100%;}
.f-nav{ z-index: 9999; position: fixed; top: 0; width: 100%;max-width: 60em;
}

Page Title

 Home 1

      Home 2

      Home 3

A: *

*The problem is that the Body has margin: 10px; that's why the navigation has a fixed top earlier than you have expected it. Set the margin to 0, it will make a smoother transition.

*Are you missing some codes in your Codepen because there is no .fixed-nav, unless you meant .f-nav. But the parent of .f-nav is .container. So you need to clear this up.

A:

var header = document.querySelector('#mainMenu');

window.addEventListener("scroll", function(event) {
 this.scrollY > header.getBoundingClientRect().top ? header.classList.add('f-nav') : header.classList.remove('f-nav')
}, false);
*{box-sizing: border-box; padding: 0; margin: 0}
.rowWrap{
  margin:0 auto;
  padding:0em 0.5em;
  max-width:60em
}
.container{
  background:gray
}
menu.rowWrap{
  border-top:2px black solid;
  border-bottom:2px black solid;
  background:green
}
menu li {
  list-style:none;
  margin:0;padding:0
}
header h1{
  height:100%;
  color:white;
  font-family:'tahoma';
  font-size:50px;
  padding-bottom:30px
}

menu.rowWrap li{
  display:inline-block;
  padding:0px 50px;
  vertical-align:middle;
  background:red;
  margin:0px;
  margin-right:10px
}
article.rowWrap img{width:100%}

.f-nav{
    z-index: 9999;
    position: fixed;
    top: 0;
    right: 0;
    left: 0
}

Page Title

    <menu class=rowWrap>

 Home 1

 Home 2

 Home 3

    </menu>


text:
Q: Extract value from background-image style attribute with xpath Ii have the follow structure:

I need that output:
name_file.jpg
I try use that answer, but dont work fo me :
$img = $xpath->query(substring-before(substring-after(//div[@class='xGh']/@style, "background-image: url('"), "')"));

echo $img->item($i)->nodeValue."
";

Look the error:
Test Ideone with error
I have some error in that sintaxe i cant see how is correct...
sry my english

A: 1) You lost quotes wrapping xpath - it's string.
2) with dom xpath, query returns set of nodes while to receive string result it's better to use evaluate
$img = $xpath->evaluate('substring-before(substring-after(//div[@class=\'xGh\']/@style, "background-image: url(\'"), "\')")');

echo $img; // it contains name_file.jpg

demo


text:
Q: Maximum size of file that can be stored entirely in NTFS Master File Table (MFT) I'm using Windows 7 and NTFS. I've noticed the MFT is a huge security risk because it can store sensitive document files without user knowledge for a long time before they get overwritten.
All tests I've run tell me that files smaller than 640 bytes are resident in the MFT and cannot be securely deleted. However, any files that are 640 bytes or more can be securely deleted immediately - this is true for my 500GB HDD and my 128GB Flash Drive (both NTFS).
I've tested this by creating a bunch of text files and writing words to them to create different file sizes. Deleting them, emptying recycle bin and running Recuva and then securely deleting highlighted. It fails to securely delete any file under 640 bytes (file is resident in MFT message will come up).
Is this the same for SSDs with Trim Enabled?
Why 640 bytes? Thought it was 512 bytes maximum for MFT entries for wiped files?
Any input much appreciated.

A: Any files can be deleted securely, as long as you use the correct tool. For example Sysinternals' SDelete is capable of handling this

On NTFS drives SDelete's job isn't necessarily through after it allocates and overwrites the two files. SDelete must also fill any existing free portions of the NTFS MFT (Master File Table) with files that fit within an MFT record. An MFT record is typically 1KB in size, and every file or directory on a disk requires at least one MFT record. Small files are stored entirely within their MFT record, while files that don't fit within a record are allocated clusters outside the MFT. All SDelete has to do to take care of the free MFT space is allocate the largest file it can - when the file occupies all the available space in an MFT Record NTFS will prevent the file from getting larger, since there are no free clusters left on the disk (they are being held by the two files SDelete previously allocated). SDelete then repeats the process. When SDelete can no longer even create a new file, it knows that all the previously free records in the MFT have been completely filled with securely overwritten files.

Surely you've chosen the wrong tool because if you've read the documentation you'd see that

Recuva cannot:

*

*...

*Securely delete certain very small files that are held in the Master File Table (MFT) and files of zero-byte length.

Introducing Recuva - What it can and can't do

Why 640 bytes? Thought it was 512 bytes maximum for MFT entries for wiped files?

Size of files that can be stored in MFT (called resident files) varies depending on each file, each system and which information is stored in MFT. The more data is used for metadata in MFT, the less is left for the file, thus there's no defined limit, but according typically Files smaller than approximately 900 bytes are stored within the directory entry at the MFT

The figure MFT Entry with Resident Record shows the contents of an MFT record for a small file or folder. Small files and folders (typically, 900 bytes or smaller) are entirely contained within the file's MFT record.
How NTFS Works

As an example I created an example 1000-byte file with very minimal metadata that can be stored completely in the MFT. But as soon as I added more metadata to the file (hard links, longer names, streams, permissions...) the maximum space that can accommodate the resident file quickly reduces

A: The MFT entry is 1024 bytes long (see the MFT section at http://www.cse.scu.edu/~tschwarz/coen252_07Fall/Lectures/NTFS.html) and stores more than just the filename - it also can include the file size, read/write permission, creation/modification date, and other meta-info. These items all have allocated sizes and this is why, in earlier versions of Windows, you could encounter an error if the filename was too long. This is also why you are unable to store files larger than 640 bytes entirely inside the table - the remaining 384 bytes (1024-640=384) were for the dedicated allocations.
It is useful to know that you computer has two identical MFT's, not one. The main is on the outer edge of the HDD, and the second one is located halfway in. The second one exists as a backup in case the main one is damaged, which can happen if the computer is shut off while an entry was being written or changed. Every MFT-cleaning program should delete from both tables (and the process is handled by the BIOS or the drive's firmware), but this is one thing to keep in mind if you want to take your data security to an extreme.
Also, the MFT row size CAN be varied, based on the drive (or partition) size and its intended purpose. Datacenters and servers are more likely to use a non-standard size, as the MFT allocation can be more than 10% of the HDD so the extra space becomes valuable. However, 1024 bytes is the standard.


text:
Q: nextFeature method for FeatureIterator object in QGIS 3 seemingly not working? How do we get the next feature from a QgsFeatureIterator object in QGIS 3? I tried the following with no success:
l = QgsProject.instance().mapLayersByName('Dissolved')[0]
f = l.getFeatures()
f = f.nextFeature()

The error returned by the .nextFeature call above is as follows:
Traceback (most recent call last):
  File "C:\PROGRA~1\QGIS3~1.2\apps\Python36\lib\code.py", line 91, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
TypeError: nextFeature(self, f: QgsFeature): not enough arguments

What am I doing wrong? How come the iterator nextFeature method is asking me for arguments?

A: Take a look at the QGIS Python Cookbook documentation on using feature iterators:
l = QgsProject.instance().mapLayersByName('Dissolved')[0]
for f in l.getFeatures():
    print ("Feature ID %d: " % f.id())

A: It works actually. But first, you have to create a new QgsFeature object (or you can use existing QgsFeature object, and pass it to nextFeature method.
f = layer.getFeatures()

feat = QgsFeature() # create empty feature in memory
print(feat.isValid())  # False
print(feat.geometry()) # OUT: <QgsGeometry: null> -> geometry of empty feature

f.nextFeature(feat) # assign next feature to feat
print(feat.isValid())  # True
print(feat.geometry()) # OUT: <QgsGeometry: Point (30 30)> -> first feature of layer

But I have no idea what the point is, yet.


text:
Q: How to export summary from R to Excel Spreadsheet I am trying to export my summary output from R into an Excel Spreadsheet. I am trying to filter my data down to what I need the summary from and then am trying to export this, i.e. dataframe -> filter 1 (called x) -> filter 2 (called y). This means I essentially need the summary from y exported.
df$group
x= filter(df,Group == "Intervention")
y= filter (x, Visit == "1")
View(x)
View(y)

summary(y)

This is a variation from many that I have tried and doesn't work:
install.packages("writexl")
library("writexl")

write_xlsx(as.data.frame(summary$y),"Summary_Intervention-V1.xlsx")

Thanks in advance!
Sample using dput(head(df)):
structure(list(Pseudonym = c(1L, 2L, 4L, 5L, 6L, 7L), Group = c("Intervention",
"Intervention", "Intervention", "Intervention", "Intervention",
"Intervention"), Visit = c(1L, 1L, 1L, 1L, 1L, 1L), Sex = c("M",
"M", "M", "M", "M", "M"), Weight..kg. = c(90.2, 109.3, 78, 70.7,
89.1, 91.2), Height..cm. = c(186, 192, 173, 182, 185, 175), Pulse.Rate..bpm. = c(76L,
72L, 60L, 64L, 79L, 74L), Systolic.Blood.Pressure = c(150L, 140L,
115L, 100L, 121L, 112L), Diastolic.Blood.Pressure = c(80L, 80L,
69L, 59L, 81L, 98L), Respiration.Rate = c(20L, 16L, 13L, 16L,
13L, 18L), HS.cTnT..ng.l. = c("18", "5", "78", "6", "12", "10"
), Myoglobin..ug.l. = c(NA, "31", "173", "21", "25", "63"), NT.proBNP..ng.l. = c(88L,
55L, 60L, 14L, 282L, 256L), CK..U.l. = c(53L, 137L, 115L, 72L,
59L, 188L), CK.MB = c(12.9, 14.5, 69, 15.6, 19.2, 28.2), CK.MB.... = c(25L,
11L, 13L, 22L, 32L, 15L), CRP..mg.l. = c("5.3", "3.6", "1.2",
"4.5", "1.1", "0.8"), Hemoglobin..g.dl. = c(15.6, 15.1, 14.4,
14.1, 17.3, 16.2), Hematocrit..l.l. = c(0.437, 0.465, 0.441,
0.427, 0.53, 0.459), Erythrocytes...pl. = c(4.9, 5.5, 5, 5.6,
5.8, 4.9), Leucocytes...nl. = c(7.13, 6.75, 5.95, 8.36, 7.41,
8.83), Thromobocytes...nl. = c(298L, 240L, 319L, 148L, 286L,
184L), Mean.corpuscular.hemoglobin..pg. = c(32.2, 27.2, 29, 25.2,
30.1, 33.3), Mean.corpuscular.hemoglobin.concentration..g.dl. = c(35.7,
32.5, 32.7, 33, 32.6, 35.3), Mean.Corpuscular.Volume..fl. = c(90,
85, 89, 76, 92, 94), Mean.platelet.volume..fl. = c(10, 10.8,
12.2, 10.8, 10.9, 12.3), Red.cell.distribution.width..RDW.CV..... = c(12.5,

13, 12.3, 12.5, 13.7, 12.3), Neutrophils.absolute...nl. = c(3.85,
4.04, 3.74, 5.51, 4.65, 5.16), Neutrophils.... = c(54, 59.9,
62.9, 65.9, 62.8, 58.6), Immature...banded.granuclocytes..Neutrophils....nl. = c(0.06,
0.03, 0.02, 0.04, 0.04, 0.03), Immature...banded.granulocytes..Neutrophils..... = c(0.8,
0.4, 0.3, 0.5, 0.5, 0.3), Reticulocytes...nl. = c(NA, 127.8,
56.5, 37, 74.8, 89.9), Eosinophils.... = c(1.7, 2.8, 2.2, 0.7,
1.2, 2), Eosinophils...nl. = c(0.12, 0.19, 0.13, 0.06, 0.09,
0.18), Basophils.... = c(0.4, 0.6, 0.3, 0.4, 0.7, 1.1), Basophils...nl. = c(0.03,
0.04, 0.02, 0.03, 0.05, 0.1), Lymphocytes...nl. = c(2.5, 1.73,
1.54, 2.14, 1.91, 2.72), Lymphocytes.... = c(35.1, 25.6, 25.9,
25.6, 25.8, 30.8), Monocytes.... = c(8, 10.7, 8.4, 6.9, 9, 7.2
), Monocytes...nl. = c(0.57, 0.72, 0.5, 0.58, 0.67, 0.64), Sodium..mmol.l. = c(137L,
142L, 143L, 142L, 136L, 142L), Potassium..mmol.l. = c(3.3, 4.4,
4.2, 4.7, 4.4, 4.4), Iron..umol.L. = c(11.9, 17.6, 18.4, 8.1,
14.6, 25.2), Ferritin..ug.l. = c(54.4, 244.4, 100.5, 177.9, 137.6,
535.9), Transferrin..g.l. = c(2.72, 2.43, 2.8, 2.54, 2.88, 2.14
), Transferrin.Saturation.... = c(17.4, 28.8, 26.2, 12.7, 20.2,
46.9), Total.Calcium..mmol.l. = c(NA, 2.37, 2.39, 2.46, 2.33,
2.22), Calcium.corrected..mmol.l. = c(NA, 2.24, 2.2, 2.39, 2.23,
2.14), Chloride..mmol.l. = c(NA, 106L, 102L, 101L, 102L, 106L
), Magnesium..mmol.l. = c(NA, NA, 0.86, 0.88, 0.86, 0.78), Phosphate..mmol.l. = c(NA,

NA, 1.28, 1.27, 1.07, 0.9), Glucose..mg.dl. = c(126L, 82L, 107L,
109L, 131L, 168L), HbA1c.... = c(4.9, 5.3, 5.5, 5.3, 6.1, 5.7
), Total.protein..g.dl. = c(NA, 77L, 79L, 21L, 72L, 72L), Albumin..g.l. = c(NA,
45.4, 47.5, 42.7, 43.9, 43.1), Urea..mg.dl. = c(30L, 34L, 28L,
27L, 27L, 32L), Creatinine..mg.dl. = c(0.86, 0.97, 0.89, 0.9,
0.74, 1.22), eGFR = c(">90", ">90", ">90", ">90", ">90", "63"
), ALT...U.l. = c(14L, 47L, 33L, 27L, 20L, 35L), AST..U.l. = c(22L,
31L, 25L, 20L, 21L, 24L), gamma.GT..U.l. = c(NA, 45L, 22L, 15L,
33L, 58L), LDH..U.l. = c(200L, 205L, 153L, 160L, 246L, 264L),
    Alkaline.phosphatase..U.l. = c(52L, NA, 79L, 56L, 45L, 59L
    ), TSH.basal..mU.l. = c(3.15, 0.97, 1.43, 1.05, 0.52, 8.83
    ), Total.Bilirubin..mg.dl. = c(NA, 0.38, 1.62, 1.25, 0.45,
    0.73), Direct.Bilirubin..mg.dl. = c(NA, 0.2, 0.55, 0.43,
    0.2, 0.28), Total.Cholesterol..mg.dl. = c(146L, 221L, 166L,
    169L, 207L, 149L), HDL.Cholesterol..mg.dl. = c(57L, 48L,
    53L, 42L, 58L, 46L), Non.HDL.Cholesterol..mg.dl. = c(90L,
    173L, 113L, 127L, 149L, 103L), LDL.Cholesterol..mg.dl. = c(86L,
    143L, 106L, 115L, 139L, 83L), Triglycerides..mg.dl. = c(74L,
    219L, 67L, 77L, 63L, 159L)), row.names = c(NA, 6L), class = "data.frame")

Output of summary y (excerpt):
 Height..cm.     Pulse.Rate..bpm. Systolic.Blood.Pressure Diastolic.Blood.Pressure
 Min.   :  1.71   Min.   :60.00    Min.   :100.0           Min.   :59.00
 1st Qu.:174.00   1st Qu.:65.00    1st Qu.:113.5           1st Qu.:73.50
 Median :182.00   Median :72.00    Median :121.0           Median :80.00
 Mean   :156.39   Mean   :70.14    Mean   :124.0           Mean   :77.86
 3rd Qu.:185.50   3rd Qu.:75.00    3rd Qu.:135.0           3rd Qu.:80.50

 Max.   :192.00   Max.   :79.00    Max.   :150.0           Max.   :98.00

A: You can also create a summary statistics manually in a easier to handle format. The final product is a dataframe which can be easily exported to a csv or Excel file.
library(dplyr)
df <- structure(list(
  Pseudonym = c(1L, 2L, 4L, 5L, 6L, 7L), Group = c(
    "Intervention",
    "Intervention", "Intervention", "Intervention", "Intervention",
    "Intervention"
  ), Visit = c(1L, 1L, 1L, 1L, 1L, 1L), Sex = c(
    "M",
    "M", "M", "M", "M", "M"
  ), Weight..kg. = c(
    90.2, 109.3, 78, 70.7,
    89.1, 91.2
  ), Height..cm. = c(186, 192, 173, 182, 185, 175), Pulse.Rate..bpm. = c(
    76L,
    72L, 60L, 64L, 79L, 74L
  ), Systolic.Blood.Pressure = c(
    150L, 140L,
    115L, 100L, 121L, 112L
  ), Diastolic.Blood.Pressure = c(
    80L, 80L,
    69L, 59L, 81L, 98L
  ), Respiration.Rate = c(
    20L, 16L, 13L, 16L,
    13L, 18L
  ), HS.cTnT..ng.l. = c("18", "5", "78", "6", "12", "10"), Myoglobin..ug.l. = c(NA, "31", "173", "21", "25", "63"), NT.proBNP..ng.l. = c(
    88L,
    55L, 60L, 14L, 282L, 256L
  ), CK..U.l. = c(
    53L, 137L, 115L, 72L,
    59L, 188L
  ), CK.MB = c(12.9, 14.5, 69, 15.6, 19.2, 28.2), CK.MB.... = c(
    25L,
    11L, 13L, 22L, 32L, 15L
  ), CRP..mg.l. = c(
    "5.3", "3.6", "1.2",
    "4.5", "1.1", "0.8"
  ), Hemoglobin..g.dl. = c(
    15.6, 15.1, 14.4,
    14.1, 17.3, 16.2
  ), Hematocrit..l.l. = c(
    0.437, 0.465, 0.441,
    0.427, 0.53, 0.459
  ), Erythrocytes...pl. = c(
    4.9, 5.5, 5, 5.6,
    5.8, 4.9
  ), Leucocytes...nl. = c(
    7.13, 6.75, 5.95, 8.36, 7.41,
    8.83
  ), Thromobocytes...nl. = c(
    298L, 240L, 319L, 148L, 286L,
    184L
  ), Mean.corpuscular.hemoglobin..pg. = c(
    32.2, 27.2, 29, 25.2,
    30.1, 33.3
  ), Mean.corpuscular.hemoglobin.concentration..g.dl. = c(
    35.7,
    32.5, 32.7, 33, 32.6, 35.3
  ), Mean.Corpuscular.Volume..fl. = c(
    90,
    85, 89, 76, 92, 94
  ), Mean.platelet.volume..fl. = c(
    10, 10.8,
    12.2, 10.8, 10.9, 12.3
  ), Red.cell.distribution.width..RDW.CV..... = c(
    12.5,
    13, 12.3, 12.5, 13.7, 12.3
  ), Neutrophils.absolute...nl. = c(
    3.85,
    4.04, 3.74, 5.51, 4.65, 5.16
  ), Neutrophils.... = c(
    54, 59.9,
    62.9, 65.9, 62.8, 58.6
  ), Immature...banded.granuclocytes..Neutrophils....nl. = c(
    0.06,
    0.03, 0.02, 0.04, 0.04, 0.03
  ), Immature...banded.granulocytes..Neutrophils..... = c(
    0.8,
    0.4, 0.3, 0.5, 0.5, 0.3
  ), Reticulocytes...nl. = c(
    NA, 127.8,
    56.5, 37, 74.8, 89.9
  ), Eosinophils.... = c(
    1.7, 2.8, 2.2, 0.7,
    1.2, 2
  ), Eosinophils...nl. = c(
    0.12, 0.19, 0.13, 0.06, 0.09,
    0.18
  ), Basophils.... = c(0.4, 0.6, 0.3, 0.4, 0.7, 1.1), Basophils...nl. = c(
    0.03,
    0.04, 0.02, 0.03, 0.05, 0.1
  ), Lymphocytes...nl. = c(
    2.5, 1.73,
    1.54, 2.14, 1.91, 2.72
  ), Lymphocytes.... = c(
    35.1, 25.6, 25.9,
    25.6, 25.8, 30.8
  ), Monocytes.... = c(8, 10.7, 8.4, 6.9, 9, 7.2), Monocytes...nl. = c(0.57, 0.72, 0.5, 0.58, 0.67, 0.64), Sodium..mmol.l. = c(
    137L,
    142L, 143L, 142L, 136L, 142L
  ), Potassium..mmol.l. = c(
    3.3, 4.4,
    4.2, 4.7, 4.4, 4.4
  ), Iron..umol.L. = c(
    11.9, 17.6, 18.4, 8.1,
    14.6, 25.2
  ), Ferritin..ug.l. = c(
    54.4, 244.4, 100.5, 177.9, 137.6,
    535.9
  ), Transferrin..g.l. = c(2.72, 2.43, 2.8, 2.54, 2.88, 2.14), Transferrin.Saturation.... = c(
    17.4, 28.8, 26.2, 12.7, 20.2,
    46.9
  ), Total.Calcium..mmol.l. = c(
    NA, 2.37, 2.39, 2.46, 2.33,
    2.22
  ), Calcium.corrected..mmol.l. = c(
    NA, 2.24, 2.2, 2.39, 2.23,
    2.14
  ), Chloride..mmol.l. = c(NA, 106L, 102L, 101L, 102L, 106L), Magnesium..mmol.l. = c(NA, NA, 0.86, 0.88, 0.86, 0.78), Phosphate..mmol.l. = c(
    NA,
    NA, 1.28, 1.27, 1.07, 0.9
  ), Glucose..mg.dl. = c(
    126L, 82L, 107L,
    109L, 131L, 168L
  ), HbA1c.... = c(4.9, 5.3, 5.5, 5.3, 6.1, 5.7), Total.protein..g.dl. = c(NA, 77L, 79L, 21L, 72L, 72L), Albumin..g.l. = c(
    NA,
    45.4, 47.5, 42.7, 43.9, 43.1
  ), Urea..mg.dl. = c(
    30L, 34L, 28L,
    27L, 27L, 32L
  ), Creatinine..mg.dl. = c(
    0.86, 0.97, 0.89, 0.9,
    0.74, 1.22
  ), eGFR = c(">90", ">90", ">90", ">90", ">90", "63"), ALT...U.l. = c(14L, 47L, 33L, 27L, 20L, 35L), AST..U.l. = c(
    22L,
    31L, 25L, 20L, 21L, 24L
  ), gamma.GT..U.l. = c(
    NA, 45L, 22L, 15L,
    33L, 58L
  ), LDH..U.l. = c(200L, 205L, 153L, 160L, 246L, 264L),
  Alkaline.phosphatase..U.l. = c(52L, NA, 79L, 56L, 45L, 59L), TSH.basal..mU.l. = c(3.15, 0.97, 1.43, 1.05, 0.52, 8.83), Total.Bilirubin..mg.dl. = c(
    NA, 0.38, 1.62, 1.25, 0.45,
    0.73
  ), Direct.Bilirubin..mg.dl. = c(
    NA, 0.2, 0.55, 0.43,
    0.2, 0.28
  ), Total.Cholesterol..mg.dl. = c(
    146L, 221L, 166L,
    169L, 207L, 149L
  ), HDL.Cholesterol..mg.dl. = c(
    57L, 48L,
    53L, 42L, 58L, 46L
  ), Non.HDL.Cholesterol..mg.dl. = c(
    90L,
    173L, 113L, 127L, 149L, 103L
  ), LDL.Cholesterol..mg.dl. = c(
    86L,
    143L, 106L, 115L, 139L, 83L
  ), Triglycerides..mg.dl. = c(
    74L,
    219L, 67L, 77L, 63L, 159L
  )
), row.names = c(NA, 6L), class = "data.frame")

df %>%
  filter(Group == "Intervention") %>%
  filter(Visit == 1) %>%
  as_tibble() %>%
  # convert e_gfr to numeric
  mutate_at("eGFR", ~ as.numeric(str_extract(., "[0-9]+"))) %>%
  # delesect non-numeric variables
  select(-Pseudonym, -Group, -Visit, -Sex) %>%
  # convert character values to numeric
  mutate_if(is.character, is.numeric) %>%
  # summarise
  summarise(across(everything(),
    .f = list(
      mean = mean,
      min = min,
      median = median,
      max = max, sd = sd
    ), na.rm = TRUE
  )) %>%
  # reshaping
  tidyr::pivot_longer(
    cols = everything(),
    names_sep = "_",
    names_to = c("variable", ".value")
  ) %>%
  # write as csv (writexl::write_xlsx for Excel)
  readr::write_csv(., "filename.csv")


text:
Q: $\displaystyle\lim_{z\to 0} |zf(z)| = 0$ implies $z = 0$ is a removable singularity. Given that $f$ is analytic around $z = 0$ and that $\displaystyle\lim_{z\to 0} |zf(z)| = 0$, we can conclude that $f(z)$ has a removable singularity at $z = 0$.
I think that we should deduce that $f(z)$ is bounded around $z = 0$ and use Riemann to conclude that it has a removable singularity. However, I have no idea how to show that this must be bounded. Am I on the right track?

A: Let $g(z) = zf(z)$. By assumption $g$ is bounded near $z=0$, so $g$ has a removable singularity at $z=0$. Hence
$$f(z) = \frac{g(z)}{z},$$
on a punctured neighbourhood of $z=0$. Since $g(0) = 0$, it follows that $g(z) = zh(z)$ for some analytic function $h$, i.e.
$$f = h$$
on a punctured neighbourhood of $z=0$, which shows that $f$ is bounded near $0$.


text:
Q: For loop is not working correctly in Laravel Controller I am saving some input data into database. Using for loop I am trying to save the input data in different rows.
for ($i=0; $i < $day ; $i++) {
    $activity->event_id = $request->event_id;
    $activity->created_by = $id;
    $activity->index = $request->index[$i];
    $activity->activity_title = $request->activity_title[$i];
    $activity->activity_details = $request->activity_details[$i];

    $activity->save();
}

The problem is, it only saves the last value. Suppose if day = 2 it saves the information of the second index of my arrays. Ignores the first index value. Where am I doing wrong?

A: Instantiate your $activity within the loop, e.g.
for ($i=0; $i < $day ; $i++) {
    $activity = new Activity();

    $activity->event_id = $request->event_id;
    $activity->created_by = $id;
    $activity->index = $request->index[$i];
    $activity->activity_title = $request->activity_title[$i];
    $activity->activity_details = $request->activity_details[$i];

    $activity->save();
}

Right now, you're just overwriting the same instance every iteration, which explains why only the last value remains.


text:
Q: Adding label to contour This code:
import numpy as np
import matplotlib.pyplot as plt

plt.contourf(np.random.random((10,10)), label='my_label')
plt.legend()

produces this warning:

warnings.warn("No labeled objects found.")

Does anyone know how to label contour?
I just want to annotate automatically generated contours inside plot window the easiest possible way.

A: I used annotate() function to label my filled contour:

In above code, instead plt.legend() I used:
plt.annotate('my_label', (8, 1), backgroundcolor='w')
So only additional consideration compared to label parameter, is that user needs to know the coordinates where the text will be positioned. Or so I think.
Update: As suggested in the comments, user can choose axes fraction type for xycoords parameter and use relative reference in range [0,1] to set mandatory xy point parameter:
plt.annotate('my_label', (.9, .1), xycoords='axes fraction', backgroundcolor='w')


text:
Q: Mapping key in the tmux command prompt I would like to map <C-p> to <Up> in the context of the tmux command prompt (the one that is opened by pressing <prefix>:) so that when pressing it, previous executed commands are displayed in order.
The reason why I want to do this is because I tend to execute tmux commands in the command prompt. One scenario is when moving multiple panes from the current opened session to another session. What I would do is to toggle the command prompt and execute :join-pane -t <session-name>, then I would move to the other pane I want to move from the current session, toggle the comand prompt again and press the <Up> key in order not to type the whole command again. However, this method involves moving my right hand from the home row. Mapping <C-p> to <Up> avoids that.
The only potential feature I found helpful for accomplishing this was the bind-key command. However, mapping keys for the command prompt is not mentioned in the documentation of that command.

A: It is not possible to configure the keys at the command prompt.
However, tmux has supported C-p and C-n in the command prompt with emacs keys for a long time: set -g status-keys emacs.


text:
Q: Creating a thread from a method of an object How is it possible to make a thread running the loop function of a TCP server instance in the example shown here.
tcpserver.py
    import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The request handler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever() # <== make a thread for serve_forever()

I've tried adding the following code and running server_forever() in a thread but execution doesn't get over its invocation.
 from threading import Thread, Lock
 server_thread = Thread(target=server.serve_forever())
 server_thread.start()
 print "Execution doesn't get to this point"

How can I launch server_forever() so that I may run code after its invocation?
It's also a bit strange that even if the file containing the server is invoked from a remote python module, execution still hangs when the server is run. For example, running:
import os

os.system("python /path/to/tcpserver.py")
print "Execution doesn't get here either"

produces the same results.
The code in the answers from the suggested duplicate question do not work for the above example.


text:
Q: Adding x:Name causes compilation error "Type name *** does not exist" I am running into an issue when I try to add thex:Name attribute to a custom user control.  Here is the code of the user control which overrides the ListView item to provide sorting when the user clicks the column header:
ListViewSorter.xaml
<ListView x:Class="GenericProjectLibrary.Helpers.ListViewSorter"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <ListView.Resources>

        <Style TargetType="{x:Type GridViewColumnHeader}">
            <Setter Property="HorizontalContentAlignment"
                    Value="Left" />
        </Style>

        <Style TargetType="Grid" x:Key="HeaderGridStyle">
            <Setter Property="Height" Value="20" />
        </Style>

        <Style TargetType="TextBlock" x:Key="HeaderTextBlockStyle">
            <Setter Property="Margin" Value="5,0,0,0" />
            <Setter Property="VerticalAlignment" Value="Center" />
        </Style>

        <Style TargetType="Path" x:Key="HeaderPathStyle">
            <Setter Property="StrokeThickness" Value="1" />
            <Setter Property="Fill" Value="Gray" />
            <Setter Property="Width" Value="20" />
            <Setter Property="HorizontalAlignment" Value="Center" />
            <Setter Property="Margin" Value="5,0,5,0" />
            <Setter Property="SnapsToDevicePixels" Value="True" />
        </Style>

        <DataTemplate x:Key="HeaderTemplateDefault">
            <Grid Style="{StaticResource HeaderGridStyle}">
                <TextBlock Text="{Binding }" Style="{StaticResource HeaderTextBlockStyle}" />
            </Grid>
        </DataTemplate>

        <DataTemplate x:Key="HeaderTemplateArrowUp">
            <Grid Style="{StaticResource HeaderGridStyle}">
                <Path Data="M 7,3 L 13,3 L 10,0 L 7,3" Style="{StaticResource HeaderPathStyle}" />
                <TextBlock Text="{Binding }" Style="{StaticResource HeaderTextBlockStyle}" />
            </Grid>
        </DataTemplate>

        <DataTemplate x:Key="HeaderTemplateArrowDown">
            <Grid Style="{StaticResource HeaderGridStyle}">
                <Path Data="M 7,0 L 10,3 L 13,0 L 7,0"  Style="{StaticResource HeaderPathStyle}" />
                <TextBlock Text="{Binding }" Style="{StaticResource HeaderTextBlockStyle}" />
            </Grid>
        </DataTemplate>

    </ListView.Resources>

    <ListView.View>
        <GridView></GridView>
    </ListView.View>
</ListView>

ListViewSorter.xaml.cs
namespace GenericProjectLibrary.Helpers
{
    /// <summary>
    /// Interaction logic for ListViewSorter.xaml
    /// Original article: https://stackoverflow.com/questions/994148/best-way-to-make-wpf-listview-gridview-sort-on-column-header-clicking
    /// Auto-Generate Columns: https://social.technet.microsoft.com/wiki/contents/articles/17635.the-equivalent-to-autogeneratecolumns-for-a-listviewgridview.aspx
    /// </summary>
    public partial class ListViewSorter : ListView
    {
        #region Initialization & Cleanup

        GridViewColumnHeader _lastHeaderClicked = null;

        /// <summary>
        /// Default ctor
        /// </summary>
        public ListViewSorter()
        {
            InitializeComponent();
            this.AddHandler(GridViewColumnHeader.ClickEvent, new RoutedEventHandler(GridViewColumnHeaderClicked));
        }

        #endregion Initialization & Cleanup

       [snip]
    }
}

I am trying to implement this ListViewSorter like so:
<Window x:Class="GenericProjectLibrary.Views.PayrollDatabaseMappingWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:h="clr-namespace:GenericProjectLibrary.Helpers"
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        mc:Ignorable="d"
        SizeToContent="WidthAndHeight">

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="..\Dictionary\StylesDictionary.xaml"/>
            </ResourceDictionary.MergedDictionaries>

        </ResourceDictionary>
    </Window.Resources>

    <StackPanel Name="StackPanel_PayrollDatabaseMappingGrid">

        <h:ListViewSorter ItemsSource="{Binding Model.DatabaseInfo.PayrollDatabaseMappings, UpdateSourceTrigger=PropertyChanged}"
                          Margin="10"
                          ScrollViewer.CanContentScroll="True">
            <ListView.View>
                <GridView>

                [snip]

                </GridView>
            </ListView.View>
        </h:ListViewSorter>

        <StackPanel Name="StackPanel_AddEditDeleteButtons"
                    Orientation="Horizontal"
                    HorizontalAlignment="Right"
                    Margin="5">

            <!-- 'Add Payroll Database Mapping' button -->
            <Button Name="AddPayrollDatabaseMappingsButton"
                    Content="Add Database Mapping"
                    Width="150"
                    HorizontalAlignment="Right"
                    Margin="5">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Click">
                        <ei:CallMethodAction TargetObject="{Binding}"
                                                     MethodName="AddPayrollDatabaseMappingButtonClicked" />
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </Button>

            <!-- 'Edit Payroll Database Mapping' button -->
            <Button Name="EditPayrollDatabaseMappingsButton"
                    Content="Edit Database Mapping"
                    Width="150"
                    HorizontalAlignment="Right"
                    Margin="5"
                    IsEnabled="{Binding ElementName=ListView_PayrollDatabaseMappings, Path=SelectedItems.Count,
                                        Converter={StaticResource EqualToBooleanConverter}, ConverterParameter=1}">
                 <i:Interaction.Triggers>
                     <i:EventTrigger EventName="Click">
                         <ei:CallMethodAction TargetObject="{Binding}"
                                                     MethodName="EditPayrollDatabaseMappingButtonClicked" />
                     </i:EventTrigger>
                 </i:Interaction.Triggers>
             </Button>

             <!-- 'Delete Payroll Database Mapping' button -->
             <Button Name="DeletePayrollDatabaseMappingsButton"
                     Content="Delete Database Mapping"
                     Width="150"
                     HorizontalAlignment="Right"
                     Margin="5"
                     IsEnabled="{Binding ElementName=ListView_PayrollDatabaseMappings, Path=SelectedItems.Count,
                                        Converter={StaticResource GreaterThanEqualToBooleanConverter}, ConverterParameter=1}">
                  <i:Interaction.Triggers>
                      <i:EventTrigger EventName="Click">
                          <ei:CallMethodAction TargetObject="{Binding}"
                                                     MethodName="DeletePayrollDatabaseMappingButtonClicked" />
                      </i:EventTrigger>
                  </i:Interaction.Triggers>
             </Button>

         </StackPanel>
     </StackPanel>
</Window>

I am trying to enable/disable the Edit and Delete buttons based on the number of items selected in the ListViewSorter.  To do this I am trying to bind to the ListViewSorter by element name but when I add a Name property to the ListViewSorter I get a compilation error of Because 'ListViewSorter' is implemented in the same assembly, you must set the x:Name attribute rather than the Name attribute.  When I make this change to x:Name I get the error of The type name 'Helpers' does not exist in the type 'GenericProjectLibrary'
I have seen similar issues on StackOverflow but those all relate to a where a namespace is identical to the view/file name.  I don't believe this is the issue here.


text:
Q: Confused about commits on github I'm using github to work on a project with two other people and am getting very confused about the whole commit thing, and nothing I'm reading is helping me understand. I get that commit records changes that you've made to a local repository... but then why are my group members' commits showing up on the online repository? Can you commit to both the local repository on your computer as well as an online repository? If you can commit to an online repository, what is the difference between doing that and simply using git push to push your changes online?
Thank you kindly.

A:
but then why are my group members' commits showing up on the online repository?

answer: I would assume they've made commits to their local version of the repository then git pushed those commits to the remote repository so that everyone else can see and pull down those changes.

If you can commit to an online repository, what is the difference between doing that and simply using git push to push your changes online?

answer: They are the same. I don't know anyone who makes commits directly to an online repository though (unless you are editing a README or making some simple HTML fix). Its general practice to make commits to the repository you have locally, then to push those changes up to the remote repository when you want to add it to the code base.

A: If your group members do a git push- it will push to the "online repository". Git commit only works on local. Git push is what moves those commits to the "online repository".

A: There will be two stages of git commits.
Local repository commits: These are commits that you will doing to your local repository which is called staging the commits. These commits are not available for your friends as the name suggests these are local to your machine.
Online repository commits: These are commits that you will push from staging them to origin repository that is online. These commits will be available for all the users that are using this branch once they pull them.
Hope this clarifies and let me know if you need more information.

A: Let's say you are starting a new repository. You'd have to start local first, right? So,
git init -> Initializes a repository on your local computer. (assuming you started with an empty folder)
Now you have an empty repository. Now it's time to add lots and lots of awesome code/content. Once you have some code, you will commit.
git commit -> Git will still keep all your changes locally; but remembers all the changes you made in this commit.
Let's say you make a couple of more changes, and want to save your work. So, you'll run the commit again. Git again saves your changes, but in commit #2, still local to your computer.
Now you are ready to share your work with other people. Because Github repo's are online (typically), you will have to push (i.e. upload) your changes to a remote repository.
Difference between commit and push is, the first one keeps all your changes locally on your computer (no one else in your team has access to your changes or commits), and push will make your code available to everyone. Hope that's clear!

A: I guess you may have experience in SVN. Different from svn commit, git commit is merely a local operation. It generates data locally and doesn't send data to the remote repository. To publish your local changes, which are stored as commits, to the remote repository, you need git push.
git push sends local-only data to the remote repository and sometimes tells the remote repository to create or remove references like branches and tags. In theory, a remote repository can be any repository in the universe, as long as there is a functional path between your local repository and the remote one. Besides, the remote repository can even be the very same local repository itself. You can push from a repository to itself, although it's almost useless. You could try git push . HEAD:refs/heads/fmyself.
After you successfully push commits (Yes, the push may fail but Git hints will tell you how to solve it), other people (more specifically other repositories. You yourself may have other repositories) can get your commits from the remote repository via git fetch or git pull. git pull can be equivalent to git fetch + git merge or git fetch + git rebase. The key is git fetch. It downloads meta data and references from the remote repository to the local one. As described above, other people can directly push to or fetch from your local repository and vice versa. However considering convenience and safety, this model is seldom used. More likely, a central repository is used. In your case, it's a repository hosted in Github. It works as a transfer station.
Some hosting services may support "online commit", which seems to allow you to directly commit in the remote repository. It's like you log in and do things in a repository on a server. Oneline commit is not that convenient in most cases except amending a commit message.


text:
Q: Missing Bndtools Welcome dialog in Eclipse to setup a configuration project after creating new Bndtools project I am following along with the Bndtools tutorial with Bndtools 3.3 from the Eclipse marketplace, but I get stuck when, after creating the project, the tutorial says, "you will now see the 'Welcome' dialog. Click Next followed by Finish to allow Bndtools to setup a configuration project and import a basic repository." I don't see a Welcome dialog, or know how to open up the dialog to setup a configuration project. I am also stuck at the parallel step in the Amdatu Tutorial where it says, "After closing the dialog Bndtools will ask to create a Configuration project. Choose the 'Amdatu Configuration'."
I experienced additional problems in the Bndtools tutorial such as an error in Eclipse I had after creating the Bndtools project, "Missing Bnd Workspace.". I created a Bndtools workspace and the error went away but I wonder if the problems I'm having are part of a larger issue of the Bndtools tutorial being out of date or incomplete. I've tried the Bndtools tutorial with both Eclipse Neon and Eclipse Luna, which the Bndtools webpage says are supported, but get the same errors with either version of Eclipse.

A: Try to switch to the bndtools perspective. On the botton left you find the view Repositories.
There you should see "No workspace configuration found". Directly beside there is a link to Create New Bnd Workspace...
This will create the conf project.


text:
Q: Entity Framework Core not updating existing tables I have an IdentityServer that uses EntityFramework Core.
I use the code-first approach. Every time i want to edit the database, such as adding tables or adding more columns to any existing table, I just perform those changes in code and then in package manager console I use the commands to create the migration files.
When i run the IdentityServer, it has the following piece of code that performs the migrations.
GlobalConfig.DatabaseConnectionString = configuration.GetValue<string>("DatabaseConnectionString");

var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>().UseSqlServer(GlobalConfig.DatabaseConnectionString);

using (var context = new ApplicationDbContext(optionsBuilder.Options))
    {
        context.Database.Migrate();
    }

'ApplicationDbContext' is just the class that extends IdentityDbContext and implements IApplicationDbContext.
Back to the main point, the
 context.Database.Migrate();

applies the new migrations if I create a new database, and even with an existing database it applies the new changes.
Now is where the problem occurs. If I delete the columns or tables just added after the migration, if I run the program again, it will not perform the changes again. And why is this a problem?
I run the migration in my localmachine an it performs the migrations and updates the databases, but when someone pulls (in my particular case, my company's QA) my solution and runs the program, it does not perform that migrations on their machines.
I would like to know what am I doing wrong, or if that is something normal in EntityFramework.
I would like that the EF could check the database first and if it is not equal as specified in code, apply the changes... or something similar.
Thanks in advance!


text:
Q: Different exception handling between Task.Run and Task.Factory.StartNew I encountered an issue when I was using Task.Factory.StartNew and tried to capture an exception that is thrown. In my application I have a long running task that I want to encapsulate in a Task.Factory.StartNew(.., TaskCreationOptions.LongRunning);
However, the exception isn't caught when I'm using Task.Factory.StartNew. It is however working as I expect when I use Task.Run, which I thought was just a wrapper on Task.Factory.StartNew (according to for instance this MSDN article).
A working example is provided here, the difference being that the exception is written to console when using Task.Run, but not when using Factory.StartNew.
My question would be:
if I have a LongRunning task that has the possibility to throw exceptions, how should I handle them in the calling code?
private static void Main(string[] args)
{
    Task<bool> t = RunLongTask();
    t.Wait();
    Console.WriteLine(t.Result);
    Console.ReadKey();
}

private async static Task<bool> RunLongTask()
{
    try
    {
        await RunTaskAsync();
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        return false;
    }
    Console.WriteLine("success");
    return true;
}

private static Task RunTaskAsync()
{
    //return Task.Run(async () =>
    //    {
    //        throw new Exception("my exception");
    //    });
    return Task.Factory.StartNew(
        async () =>
    {
        throw new Exception("my exception");
    });

}

A: I'll pull some of my comments into an answer because they turned out to be helpful:
LongRunning is identical to forcing a new thread to be created in practice. And your async method is probably not on that thread for a long time (it is taken off at the first await point). You don't want LongRunning in this case.
It does not matter how long the async method runs. The thread is destroyed at the very first await (that operates on a non-completed task).
Can the compiler use this hint in any way? The compiler is generally unable to analyze your code in any major way. Also the compiler does not know anything about the TPL. The TPL is a library. And this library will just always launch a new thread. Specify LongRunning iff your task will almost always burn 100% CPU for multiple seconds or will block for multiple seconds with very high probability.
My guess is you don't want LongRunning here because if you're blocking, why are you using async in the first place? async is about not blocking but getting off the thread.

A: Your problem is that StartNew doesn't work like Task.Run with async delegates. The return type of StartNew is Task<Task> (which is convertible to Task). The "outer" Task represents the beginning of the method, and the "inner" Task represents the completion of the method (including any exceptions).
To get to the inner Task, you can use Unwrap. Or you can just use Task.Run instead of StartNew for async code. LongRunning is just an optimization hint and is really optional. Stephen Toub has a good blog post on the difference between StartNew and Run and why Run is (usually) better for async code.
Update from @usr comment below: LongRunning only applies to the beginning of the async method (up until the first incomplete operation is awaited). So it's almost certainly better all around to use Task.Run in this case.

A: It should be possible when you first Unwrap the task:
await RunTaskAsync().Unwrap();

Or alternatively:
await await RunTaskAsync();


text:
Q: Marketing Cloud Web Analytics Data in Data Extensions I've configured Web & Mobile Analytics to track webpage visitors - I can see it properly in the web analytics reports, however, I'm struggling with getting the data to the Predictive Intelligence Data Extensions PI_ and IGO_.
My goal is to capture records to the Data Extensions which present the pages visited by identified users.
I've enabled the Streaming Updates and configured the tracking code to push data to SFMC as follows:
   <script type="text/javascript" src="https://XXX.collect.igodigital.com/collect.js"></script>
   <script type="text/javascript">

    var title = document.title;
    var url = window.location.href;

    var urlParams = new URLSearchParams(window.location.search);
    let identified = urlParams.has('subid');
        if (identified === true) {
            let subid = urlParams.get('subid');
            _etmc.push(["setOrgId", "XXX"]);
            _etmc.push(["setUserInfo", {"email": subid}]);
            _etmc.push(["trackPageView"]);
            _etmc.push(["updateItem",
                {
                  "item_type": "content",
                  "item": url,
                  "url": url,
                  "title": title,
                  "available": "Y",
                }
            ]);

        } else {
            _etmc.push(["setOrgId", "XXX"]);
            _etmc.push(["trackPageView"]);
            _etmc.push(["updateItem",
                {
                  "item_type": "content",
                  "item": url,
                  "url": url,
                  "title": title,
                  "available": "Y"
                }
            ]);
        }

    </script>

I also uploaded the Content Catalog with the following format (status:
Successfully processed 5 items):
ContentID   Title   Link    Availability
1   Home    https://sfmcdemo.test.com/  Y
2   Shop    https://sfmcdemo.test.com/shop.html Y
3   About   https://sfmcdemo.test.com/about.html    Y
4   Updates https://sfmcdemo.test.com/updates   Y
5   Contact https://sfmcdemo.test.com/contact.html  Y

None of these options work for me. I'm not able to see any data being populated in IGO and PI Data Extensions.
Thanks in advance for your help.

A: So the issue I see:
1) Not passing an item in the track view call
2) Setting the item in your streaming update call to url as opposed to the contentid


text:
Q: How does this heading area work on all browsers? I just saw this browser here:
http://www.dietriffic.com/
Now, the green section at the top, no matter how I re-size my browsing window (Chrome), it manages to either fill it completely or just not show all of it.  How does it do this?  It is an image right?  They couldn't have prepared for every screen size could they?
Thanks!

A: It uses a horizontally- and vertically-repeated image across the width of the entire header:

and a centered, non-repeated, mostly-transparent PNG for that glow effect in the middle of the header:

A: Using Firebug:
The green box is
<div id="header_area" class="full_width">

It's using a repeating background image (the green) of size 50x50 that they use to fill the entire div with "tiles". The fact that the div always fits the browser viewport width is the class "full_width":
.full_width {
    clear: both;
    width: 100%;
}

It's the width: 100% that does the scaling.
Apart from that, the centered text is not an image, it's real text. They achieve the centered alignment with
margin: 0 auto;

on the container element.