text:
Q: I have written a news web scraper code the error is IndexError: list index out of range and its not resolving import requests
from bs4 import BeautifulSoup
import pandas as pd

headers = {
    'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
}

if __name__ == '__main__':
    # Access the page
    r = requests.get('https://tribune.com.pk/kse-100-index/')

    if r.status_code == 200:
        html = r.text
        soup = BeautifulSoup(html, 'lxml')

    news_date = soup.find_all("span", {"class": "excerpt"})

    news_title = soup.find_all("h2", {"class": "title"})
    # news_title = soup.find_all("div",{"class":"story  cat-0 group-0 position-14 sub-story clearfix"})

    news_description = soup.find_all("p", {"class": "excerpt"})
    date_list = []
    title_list = []
    description_list = []
    # print("Hello world")
    for date in news_date:
        date_list.append(date.text)
    for title in news_title:
        title_list.append(title.text)
    for description in news_description:
        description_list.append(description.text)
    for i in range(30):
        print("Date: ", date_list[i])
        print("Title: ", title_list[i])
        print("Description: ", description_list[i])
        print()

    s1 = pd.Series(date_list[0:30], name='News Date')
    s2 = pd.Series(title_list[0:30], name='News Heading')
    s3 = pd.Series(description_list[0:30], name='News Description')
    df = pd.concat([s2, s3], axis=1)
    df = df.fillna("None")
    # d = {'Phone name': phone_name_list, 'Price per month': price_per_month_list,'Interest List': interest_list, 'Total Price List': total_price_list,'Unlimited Offer List': unlimited_offer_list}
    # df = pd.DataFrame(data=d)
    print(df)
    df.to_csv('tribune1.csv', encoding='utf-8')

It's an Express Tribune web scraper. I want to print the date, headlines and description. When I was running the code previously, there wasn't any error. But after adding the date section, the error appeared.
I would be thankful to you if you could help me resolve the error.

A: Change this in your code.
if(len(date_list) > 0 ):
    for date in news_date:
        date_list.append(date.text)
    for title in news_title:
        title_list.append(title.text)
    for description in news_description:
        description_list.append(description.text)
    for i in range(max(len(date_list), 30)): # So as to have 30 or less items
        print("Date: ", date_list[i])
        print("Title: ", title_list[i])
        print("Description: ", description_list[i])
        print()
 else:
     print("Not found");

Make sure you have proper indentation.


text:
Q: What do you name a Java package when it isn't a part of a top level domain? I've read the syntax conventions for naming Java packages, and I know the general rule of thumb, but what if you've just started building your application, you haven't chosen a license, and it is a personal project? It doesn't make sense to throw in "com.mycompany" or "org.myorganization" if that is not the case. Does anyone have suggestions for this?

A: Many Java books and online examples just use the name of the book or project, i.e., ejb3inaction.* or tutorial.*.

A: I usually just go with something like lastname.firstname.<other packages>. The package name should just be unique, and the combination of your last name and first name is probably unique enough (if you have a common name, throw in a middle initial or a middle name or something like that).

A: Perhaps org.{myname} ?
I don't think it particularly matters for personal projects. In fact I've seen commercial (in-house) projects flout this rule and simply call their packages {servicename} or similar (which I don't particularly like). The packaging rules are designed to prevent name clahes when sharing code cross-enterprise (or organisation) and consequently for personal projects you can use most anything.

A: Java packages are just for namespacing.  Call it whatever you want!  Think of something that will be useful to you later on when you want to remember what this code was supposed to do.

A: how about org.{projectname}? Think about some open-source projects (e.g. org.hibernate, org.springframework and org.junit) ... did they start this way because it was the name of the website, or the name of the project itself?
Besides, re-factoring is so trivial these days, just name it whatever you want.

A: What about name.yourname.myproject or net.sf.myproject or com.googlecode.myproject or simply myproject.
As long as you don't make your code public, it's not that important actually (and you can easily refactor it later before releasing your code if you need to). Once people start using your code, it's another story...

A: In the case you might also think about sharing the project (making it an open-source project), to open an project entry, in that case you can use something like 'net.sf.{project-name}.*', be careful here, that the project-name, must be the unix name, of the project (at least then you follow the rules correctly :)

*

*SourceForge

*Java Net

*Google Code

*Launchpad

*JavaForge

*Tigris.org

A: I generally use nl.myname.myapp for all personal projects. There is no rule against open sourcing something that uses your personal name. If you decide to make the project bigger and create a web site for it you can always rename the packages if you really want to.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jquery can't find firebreath object I'm creating a web video player using Firebreath to compile my C/C++ codec as a browser plugin. Now the plugin is loaded OK and works (start, stop video etc.). The next step would be to implement full screen which would require to change the width and height of the plugin object (plus other stuff of course), but jQuery seems unable to find it.
This is my HTML:

    <object id="plugin0" type="application/x-webplayer" style="width: 500px; height: 300px;">
    </object>

I would like to dynamically resize the object but when I try both
jQuery("#plugin0")

and
document.getElementById("#plugin0")

I get [] (null I would guess)
If I try jQuery('object') I get [TypeError]
On the other hand if I try to handle player0 with jQuery everything works fine. What am I missing?
Thanks!

A: there are a lot of reasons why, but jquery doesn't work well when wrapped around a firebreath plugin object tag; I spent about 8 hours working on this issue once and eventually determined that it wasn't a big enough deal to keep working on.  I recommend you just don't do this. IF you need to move or position it, make it 100% x 100% and put it in a div and move that, it'll save you a lot of grief.


text:
Q: How hide .exe.config or change location? I need set hidden .exe.config that actually resides in application folder. Alternatively, it would good change folder location, example in application data (hidden folder).

A: You cannot change the location of the app.exe.config file with the default CLR host.  It initializes the primary appdomain with the values it finds in the .config file before your code starts running.  There's only one place it will look for the file, in the same directory as the startup EXE, using the name of the EXE.  Altering the location is technically possible but only if you write a custom CLR host that uses a custom AppDomainManager.  Writing a custom CLR host requires COM code written in C++.  This otherwise defeats the point of having only a single deployable file.
If you intend to do this to hide sensitive information, like the username+password for a dbase connection string, then keep in mind that security through obscurity is not true security.
If you intend to do this to achieve single-file deployment then don't forget to overlook the standard solution: a single file named setup.exe


text:
Q: SSIS Excel column name reading from file I have a source file, has columns names with length as more than 100.
Column name are same upto 80 characters and remaining 20 characters will be different, please find below example.
ABC_XXXX_MNOAP : XYZABC_PAGELOADER_CLICKS_MANOPD_YXBDBAGD : VIEWS
ABC_XXXX_MNOAP : XYZABC_PAGELOADER_CLICKS_MANOPD_YXBDBAGD : CLICKS & THROGHS

While i am loading this file in to ssis, full column name is not loading and it is trimming.
Error thrown was

There is more than one data source column with same

Please help me how to get full metadata from excel


text:
Q: rt_raster_from_two_rasters: The two rasters provided do not have the same alignment I have a set of geometries in my database which I used to create a set of rasters (each raster has a unique color). Now I would like to merge all of these rasters  into one but get an error such as :
rt_raster_from_two_rasters: The two rasters provided do not have the same alignment

I tried to resample all of these rasters using ST_Resample(geometry_set, 800, 600) methods but it does not help me.
The numbers 800 and 600 are the width and height values used to generate rasters.
How could I merge all of these rasters into one?
Here is my PostgreSQL script:
SELECT
        layer."SummaryId",
        layer."Name",
        encode(
            ST_AsPNG(
                ST_Union(layer.raster)
            ),
            'base64'
        ) AS pngBase64String
 FROM

(
  SELECT
    s."Id" AS "SummaryId",
    r."Name" AS "Name",

            ST_ColorMap(
              ST_AsRaster(
                  ST_MakeValid (
                      ST_GeomFromText("WktString", 4326)
                  ),
                  800,
                  600
                ),
                1,
                mr."ColorMap"
          --)
       ) AS raster

  FROM "TableA" AS s
  INNER JOIN "TableB" AS r ON r."Id" = s."SomeId"
  INNER JOIN "TableC" AS l ON l."TableAId" = s."Id"
  INNER JOIN "TableD" AS mr ON mr."Id" = l."RangeId"
  WHERE
    s."StartDate" >= '2018-09-10 00:00:00' AND
    s."EndDate" <= '2018-09-10 23:59:59'

  GROUP BY s."Id", r."Name", l."WktString", mr."ColorMap"

) AS layer

GROUP BY
  layer."SummaryId",
  layer."Name"


text:
Q: Coulomb potential of a periodic crystal in reciprocal space Usually the Coulomb potential (electron-electron interaction) can be Fourier transformed (aside from prefactors) like that:
$$
\frac{1}{|\vec r_1 -\vec r_2|} = \int \frac{\text d ^3 k}{(2\pi)^3} \frac{\text e^{\text i \vec k (\vec r_1 - \vec r_2)}}{\vec k^2}\;.
$$
But sometimes, when dealing with periodic crystals, I see things that:
$$
\frac{1}{|\vec r_1 -\vec r_2|} = \sum_{\vec G} \frac{\text e^{\text i \vec G (\vec r_1 - \vec r_2)}}{\vec G^2}\;,
$$
where the sum goes only over the reciprocal lattice vectors $\vec G$.
But I don't understand why? The electron-electron interaction is not periodic! Does it have something to do with the finite size of the system?

A: Much as Okarin wrote, in the crystal there is a periodic arrangement of Coulomb potentials.  The Fourier transform of this periodic arrangement of Coulomb potentials is discrete; it is zero except for the reciprocal lattice vectors.
Like the Fourier transform of a single Dirac delta function is constant, but the Fourier transform of an infinite comb of Dirac delta functions is an infinite comb of Dirac delta functions.  Using the convolution theorem you can see that the Fourier transform of the infinite comb of Coulomb potentials is the infinite comb of Dirac delta functions times the Fourier transform of the Coulomb potential.

A: I'm very late at this but I'll answer. The reason is that for a periodic crystal the Fourier transform and the Fourier series are equivalent. Instead of thinking of a point-like charge, consider a generic charge density $\rho(r_2)$. The case of a point-like electron is one where $\rho(r_2) = \delta(r_2-r_e)$, using the Dirac delta. Then the Fourier transform of it is the constant function, $\rho(k)=1$ for any $k$, and you retrieve the first formula.
However, if you have a periodic system with lattice parameters $a,b,c$, then for each electron at $r_e$ you will also have infinite more electrons at $r_e+ia+jb+lc$, with $i,j,l$ integers. Then your density isn't a Dirac delta any more, but a Dirac comb: $\rho(r_2) = \sum_{ijl}\delta(r_2-r_e-ia-jb-lc)$. And the Fourier transform of a Dirac comb is another Dirac comb! Hence, you now have a Fourier transform that is itself defined on a lattice of sort - non-zero at the various reciprocal lattice vectors $G$, and zero everywhere else. And that's why the integral above becomes, effectively a sum. It's still an integral, really: it's just that the integrand is zero everywhere other than at those discrete points.


text:
Q: Updating child entities ABP I'm trying to work with child entities in ABP but when I call repository methods nothing happens, the way i'm doing it is deleting all records and Inserting it again, when methods are called I got duplicate entries
I'm working with it in DomainService layer here is my manager
    using Abp.Domain.Repositories;
    using Abp.Domain.Services;
    using DomiSys.Prestamos.Models.Generales.ClienteFuturoNs.DireccionClienteFuturoNs;
    using Microsoft.EntityFrameworkCore;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;

    namespace DomiSys.Prestamos.Models.Generales.DireccionClienteFuturoNs
    {
        public class DireccionClienteFuturoManager : DomainService, IDireccionClienteFuturoManager
        {
            private readonly IRepository<DireccionClienteFuturo> _direccionClienteFuturoRepository;

            public DireccionClienteFuturoManager(IRepository<DireccionClienteFuturo> direccionClienteFuturoRepository)
            {
                LocalizationSourceName = PrestamosConsts.LocalizationSourceName;
                _direccionClienteFuturoRepository = direccionClienteFuturoRepository;
            }

            public async Task<DireccionClienteFuturo> Registrar(DireccionClienteFuturo entity)
            {
                return await _direccionClienteFuturoRepository.InsertAsync(entity);
            }

            public async void Eliminar(DireccionClienteFuturo entity)
            {
                await _direccionClienteFuturoRepository.DeleteAsync(entity);
            }

            public async void EliminarTodo(int clienteId)
            {
                var list = _direccionClienteFuturoRepository.GetAll().Where(x => x.ClienteFuturoId == clienteId).ToList();
                foreach (var item in list)
                {
                    await _direccionClienteFuturoRepository.DeleteAsync(item);
                }
            }

            public async void RegistrarLista(IEnumerable<DireccionClienteFuturo> lista)
            {
                foreach (var item in lista)
                {
                    item.Id = 0;
                    await _direccionClienteFuturoRepository.InsertAsync(item);
                }
            }

        }
    }

And I'm using it like this
    private void InsertarDireccion(ClienteFuturo clienteNuevo)
    {
        _direccionClienteFuturoManager.EliminarTodo(clienteNuevo.Id);
        _direccionClienteFuturoManager.RegistrarLista(clienteNuevo.ListaDirecciones);
    }

    public Task<ClienteFuturo> Actualizar(ClienteFuturo entity)
    {

        Validar(entity);
        entity.SucursalId = usuario.SucursalId ?? 0;

        InsertaActualizaConyugue(entity);

        entity.FechaNacimiento = Shared.Shared.FormateaFecha(entity.FechaNacimiento);
        var result = _clienteRepository.Update(entity);

        InsertarTelefono(entity);
        InsertarEmail(entity);
        InsertarDireccion(entity);

        return Task.FromResult(result);
    }

InsertaTelefonos(entity) method is called from Actualizar method
When methods are called I got duplicate entries in database.
What I'm doing wrong ?


text:
Q: Show that a union of triangles can be represented as a union of separated triangles. Let a simplex $\overline{ABC}$ in the plane $\mathbb{R}^2$ be defined as a triangle with vertices $A,B,C\in\mathbb{R}^2$ i.e. the subset $\overline{ABC}:=\{P\in\mathbb{R}^2 : P=\lambda_AA+\lambda_BB+\lambda_CC,\ \lambda_A,\lambda_B,\lambda_C\in[0,1], \lambda_A+\lambda_B+\lambda_C = 1\}$. Define a polygonal tile as a finite union of simplices $\mathcal{P}=\bigcup_{i=1}^n \overline{A_iB_iC_i}$ such that for $i\neq j$ the intersection of $\overline{A_iB_iC_i}$ and $\overline{A_jB_jC_j}$ is either empty, reduced to one of the vertices or a common side segment. Furthermore, we impose $\overset{\circ}{\mathcal{P}}$ to be path connected. Then show that every finite union $\mathcal{P}=\bigcup_{i=1}^n \overline{A_iB_iC_i}$ of simplices for which $\overset{\circ}{\mathcal{P}}$ is path connected is indeed a polygonal tile.
The assertion is pretty intuitive and it is very simple to show it in a concrete case. However, it seems very difficult to formally show it. I tried to use an induction on $n$, but if we remove a simplex from the union, we can no longer assume $\overset{\circ}{\mathcal{P}}$ to be path connected. Is there a somewhat simple way to show this?

A: The key is to drop the assumption that  $\overset{\circ}{\mathcal{P}}$ is path connected. Then the same proof as given in Will Jaggy's answer to this question shows that every finite union of triangles $P$ has an interior edge. Next, you argue inductively: Given $P$ with a union $E$ of interior edges (pairwise disjoint except for their endpoints; I will call such edges "essentially disjoint"), you use the same argument as given by Jaggy to find an extra interior edge essentially disjoint from the rest of the interior edges, unless $P-E$ is a disjoint union of triangles. In the latter case, you get the desired decomposition of $P$ as the union of distinct triangles which intersect only along edges or vertices or not at all.


text:
Q: Sending simple email on Azure with Sendgrid I am trying to send email using SendGrid on Azure.
I followed these instructions: https://learn.microsoft.com/tr-tr/azure/sendgrid-dotnet-how-to-send-email ; but it doesn't seem to work.
. Sending via smtp works though.
using System;
using System.Threading.Tasks;
using SendGrid;
using SendGrid.Helpers.Mail;

namespace Example
{
    internal class Example
    {
        private static void Main()
        {
            Execute().Wait();
        }

        static async Task Execute()
        {
            var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
            var client = new SendGridClient(apiKey);
            var msg = new SendGridMessage()
            {
                From = new EmailAddress("from@hotmail.com", "DX Team"),
                Subject = "Hello World from the SendGrid CSharp SDK!",
                PlainTextContent = "Hello, Email!",
                HtmlContent = "Hello, Email!"
            };
            msg.AddTo(new EmailAddress("to@gmail.com", "Test User"));
            var response = await client.SendEmailAsync(msg);
        }
    }
}

A: According to your code sample, it would run well while you do not receive any email.
So pay attention to some points as below:
1.When you create api key, make sure that you choose the Full Access.

2.You use Gmail to receive email, so set "Allow less secure apps:ON".

3.Check the response, if the StatusCode is Accepted it means it send email successfully.

Then test agian, and it may work well.
Also, you want to make an function which is send email every 15 minutes.
You could refer to the code as below, I create azure function in v1.
public static void Run([TimerTrigger("0 */15 * * * *")]TimerInfo myTimer, [SendGrid(ApiKey = "sendgridkey")] out SendGridMessage message, TraceWriter log)
        {
            log.Info($"C# Timer trigger function executed at: {DateTime.Now}");
            message = new SendGridMessage();
            message.AddTo("testto@gmail.com");
            message.AddContent("text/html", "Test body");
            message.SetFrom(new EmailAddress("testfrom@gmail.com"));
            message.SetSubject("Subject");

        }


text:
Q: How to display observable in angular 2? Just trying out a ngrx-store sample app. In my component I have:
 <div *ngFor="#todo of todos">
        {{ todo.value }}
 </div>

However the todos are not displayed after entering. This is the error I get:
Can't bind to 'ngFor' since it isn't a known native property ("

      ********
      <div [ERROR ->]*ngFor="let todo of todos">
        {{ todo.value }}
      </div>
"): App@8:11

How can I display the todos?
plunkr:http://plnkr.co/edit/yOw4qh4aZ5d9jhg235gD?p=preview

A: You forgot to import NgFor in your component. And register it in your components directives:[ ] property.
import { NgFor } from '@angular/common';

@Component({
  directives: [NgFor]
})

Also if you are returning data async from an observable you will need to use the async pipe.
https://angular.io/docs/ts/latest/guide/pipes.html


text:
Q: Questions about Docker's configuration and the selection of OS accordingly I am planning to build an environment for Web services using ECS at Docker.
However I am in trouble because I do not know what to do with the OS inside Docker.
I heard that it is common to build Docker individually for each service for general construction of Docker.
At first, there was a Docker that gathers Docker, and imagined in which Docker (server, DB, Redis ...) was created for each role.
If this is done, if you set Docker's OS for each role to general LinuxOS (such as CentOS), it seems that it will increase considerably only by OS memory capacity.
I just realized that there is a compact OS called CoreOS.
Then there are doubts.
Is it common for Docker's OS to be set to CoreOS for each role?
Is the assumption that I wrote so far is common?
It will be helpful if you can answer.

A: Not sure I understand the question, but you seem to misunderstand "layers" of a Docker image.
The base OS doesn't really matter all that much as long as you know how to install and manage services for that container OS.
For minimal base images, you can pick Alpine or CoreOS. For more substantial OS's that might match your production systems, then you can pick from Debian, CentOS, or Ubuntu.
For more reading see Elasticsearch switched to CentOS as a base.
You'll find that things are often easier to install when you can use apt or yum install

increase considerably only by OS memory capacity

Only once per machine (assuming running in a cluster/swarm), though. For example, if you share a base CentOS image between your web app and Redis Docker images, then only the extra layers to build the respective apps are created.
For a visual, let's assume I have a Python (or Ruby, Node, Golang, etc.) web app, a CLI utility written using that same language, and a database image built on one machine. You would build a general Python layer, then extend that onto the web and CLI images. All images build from the same base OS image
----------------
|  Web | CLI   |
---------------------
|    Python    | DB |
---------------------
|     Base image    |
---------------------


text:
Q: How to forced logout a user when sessions stored in cache? In certain circumstances I'd like to let the staff to kick out some users.
My django 1.8 site stores sessions in redis.
I tried this solution in my view:
#will be removed in 1.9
from django.utils.importlib import import_module

@staff_member_required
def kickout_user(request, username):

    u = User.objects.get(username = username)

    SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
    active_users = Request.objects.active_users(seconds=60)
    active_users_ids = [user.id for user in active_users]
    for session in stored_sessions:
            SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
            s = SessionStore(session_key=session.session_key)
            session_uid = session.get_decoded().get('_auth_user_id')
            print 'session', session_uid
            if session_uid == u.id:
                print 'session going to be deleted for uid:',  session_uid
                session.delete()
                print  ' session deleted'+ u.username

But it gives this error:
global name 'Request' is not defined

There also some suggestions here, but they are either flawd or based writing additional middlewares that I find overkill and try to aovid.

A: You can try django-force-logout
and also visit this_link for more assistance


text:
Q: achieve atomic operation because java volatile guarantees happens-before relation? achieve atomic operation because java volatile guarantees happens-before relation?
I have read about the happens-before for the volatile:
If Thread A writes to a volatile variable and Thread B subsequently reads the same volatilevariable, then all variables visible to Thread A before writing the volatile variable, will also be visible to Thread B after it has read the volatile variable.
Now, I have two varaibles:
         static int m_x;
volatile static int m_y;

Now I have two threads, one only writes to them, and first write to m_x, and then write to m_y; The other one, only reads from them, first read m_y, and then, m_x.
My question is: is the write operation atomic? is the read operation atomic?
In my understanding, they should be atomic:
(1) On the side of writ thread, after (Write-1), it will not flush its cache to main-memory for m_x is NOT volatile, so, read-thread is not able to see the update; and after (Write-2), it will flush its cache to main-memory, for m_y is volatile;
(2) on the side of read thread, on (Read-1), it will update its cache from main memory, for m_y is volatile; and on (Read-2), it will NOT update its cache from main memory, for m_x is not volatile.
Because of the above two reason, I think the read thread should always observe the atomic value of the two variable. Right?
public class test {
         static int m_x;
volatile static int m_y;

public static void main(String[] args) {
    // write
    new Thread() {
        public
        void run() {
            while(true) {
                int x = randInt(1, 1000000);
                int y = -x;
                m_x = x; // (Write-1)
                m_y = y; // (Write-2)
            }
        }
    }.start();

    // read
    new Thread() {
        public
        void run() {
            while(true) {
                int y = m_y; // (Read-1)
                int x = m_x; // (Read-2)

                int sum = y + x;
                if (sum != 0) {
                    System.out.println("R:sum=" + sum);
                    System.out.println("R:x=" + x);
                    System.out.println("R:y=" + y);
                    System.out.println("\n");
                }
            }
        }
    }.start();
}

public static int randInt(int Min, int Max) {
    return Min + (int)(Math.random() * ((Max - Min) + 1));
}

}

A: As stated in the comment, the two reads and writes are not atomic. You cannot achieve atomicity by using the volatile keyword.
This fact can be observed running your program.
To read/write both variables at the same time you either need proper synchronisation or create your own immutable value.
To do the later
public class ConcurrencyTestApp {

    // use volatile for visibility
    private volatile ImmutableValue immutableValue = new ImmutableValue(0, 0); // initial, non-null value

    static class ImmutableValue {
        private final int x;
        private final int y;

        ImmutableValue(final int x, final int y) {
            this.x = x;
            this.y = y;
        }

        int getX() {
            return x;
        }

        int getY() {
            return y;
        }

        @Override
        public String toString() {
            return String.format("x = %s\t| y = %s", x, y);
        }
    }

    void replaceOldWithNewValue(final ImmutableValue newValue) {
        immutableValue = newValue;
    }

    ImmutableValue getImmutableValue() {
        return immutableValue;
    }

    static class Writer extends Thread {

        private final ConcurrencyTestApp app;

        Writer(ConcurrencyTestApp app) {
            this.app = app;
        }

        volatile boolean isRunning = true;

        @Override
        public void run() {
            while (isRunning) {
                int x = randInt(1, 1000000);
                int y = -x;

                app.replaceOldWithNewValue(new ImmutableValue(x, y));
            }

        }

        int randInt(int Min, int Max) {
            return Min + (int) (Math.random() * ((Max - Min) + 1));
        }
    }

    static class Reader extends Thread {
        private final ConcurrencyTestApp app;

        Reader(ConcurrencyTestApp app) {
            this.app = app;
        }

        volatile boolean isRunning = true;

        @Override
        public void run() {
            while (isRunning) {
                ImmutableValue value = app.getImmutableValue();
                System.out.println(value);
                int x = value.getX();
                int y = value.getY();
                int sum = x + y;
                if (sum != 0) {
                    System.out.println("R:sum=" + sum);
                    System.out.println("R:x=" + x);
                    System.out.println("R:y=" + y);
                    System.out.println("\n");
                }
            }
        }
    }

    public static void main(String[] args) {

        ConcurrencyTestApp app = new ConcurrencyTestApp();
        Writer w = new Writer(app);
        Reader r = new Reader(app);

        w.start();
        r.start();

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        w.isRunning = false;
        r.isRunning = false;
    }

}

For further reference, I recommend the book Java concurrency in practice by Brian Goetz and Tim Peierls.

Addendum

...
Because of the above two reason, I think the read thread should always
  observe the atomic value of the two variable. Right?

Wrong!
...and you are missing an important part.
For reference, see JSR 133 (Java Memory Model) FAQ by Jeremy Manson and Brian Goetz section What does volatile do?
In your program, there is nothing preventing the following:
Assume int m_x = x1 and int m_y = y1

*

*Your Writer-Thread executes until Write-1

*

*int m_x is now set to value x2 (which may or may not be visible to your Reader-Thread)

*Your Writer-Thread's execution gets suspended (for whatever reason)

*Your Reader-Thread executes Read-1 and Read-2 (there is nothing stopping the Reader-Thread from doing that)

*

*int y = m_y which is still y1 because your Writer-Thread did not execute further yet

*int x = m_x which may be x2 (but it also could still be x1)

*Your Reader-Thread gets suspended and your Writer-Thread continues

*

*int m_y is now set to value y2 (only now Read-1 would get y2 and Read-2 would be guaranteed to get x2 - unless your Writer-Thread continues)

*... and so on

To see that yourself modify your writer
System.out.println("W0");
m_x = x; // non-volatile
System.out.println("W1: " + x);
m_y = y; // volatile
System.out.println("W2: " + y);

and reader thread code
System.out.println("R0");
int y = m_y; // volatile
System.out.println("R1: " + y);
int x = m_x; // non-volatile
System.out.println("R2: " + x);

So why does it not work for you?
From the reference

...volatile or not, anything that was visible to thread A when it writes to volatile field f becomes visible to thread B when it reads f.

Thus, your Reader thread is guaranteed to see the new values for m_x and m_y only when your Writer thread wrote the new value to m_y. But because no particular thread execution order is guaranteed the write operation Write-2 may not happen before Read-1 is executed.
Also see Java Volatile Keyword by Jakob Jenkov for a similar example to yours.

A: You assert that

"...after (Write-1), it will not flush its cache to main-memory for m_x is NOT volatile"

and

"... on (Read-2), it will NOT update its cache from main memory, for m_x is not volatile."

In fact, it is not possible to say whether or not the caches will be flushed (write), or whether or not values that are present in the cache (read). The JLS certainly does not make >>any<< guarantees for reads and writes to non-volatile variables.  The guarantees apply to read and write operations on volatile variables ONLY.
While it is possible that you will observe consistent behavior for your program on certain platforms, that behavior is not guaranteed by the JLS.


text:
Q: Citation brackets at the wrong place with natbib I use natbib with the following customization:
\RequirePackage{natbib}
\RequirePackage{hyperref}
\setcitestyle{square,aysep={},yysep={;}}
\hypersetup{
  colorlinks=true,  % false: boxed links; true: colored links
  linkcolor=blue,   % color of internal links (change box color with linkbordercolor)
  citecolor=blue,   % color of links to bibliography
  filecolor=blue,   % color of file links
  urlcolor=blue
}

When I use \cite I get:

but what I want is:

How can I do this?

A: Use \citep instead of \cite. See the documentation of natbib for details.


text:
Q: How to set pthread max stack size The API pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize)
is to set the minimum stack size (in bytes) allocated for the created thread stack.
But how to set the maximum stack size?
Thanks

A: If you manage the allocation of memory for the stack yourself using pthread_attr_setstack you can set the stack size exactly.  So in that case the min is the same as the max.  For example the code below illustrate a cases where the program tries to access more memory than is allocated for the stack and as a result the program segfaults.
#include <pthread.h>

#define PAGE_SIZE 4096
#define STK_SIZE (10 * PAGE_SIZE)

void *stack;
pthread_t thread;
pthread_attr_t attr;

void *dowork(void *arg)
{
 int data[2*STK_SIZE];
 int i = 0;
 for(i = 0; i < 2*STK_SIZE; i++) {
   data[i] = i;
 }
}

int main(int argc, char **argv)
{
  //pthread_attr_t *attr_ptr = &attr;
  posix_memalign(&stack,PAGE_SIZE,STK_SIZE);
  pthread_attr_init(&attr);
  pthread_attr_setstack(&attr,&stack,STK_SIZE);
  pthread_create(&thread,&attr,dowork,NULL);
  pthread_exit(0);
}

If you rely on memory that is automatically allocated then you can specify a minimum amount but not a maximum.  However, if the stack use of your thread exceeds the amount you specified then your program may segfault.
Note that the man page for pthread_attr_setstacksize says:
A thread's stack size is fixed at the time of thread creation.  Only the main thread can dynamically grow its stack.
To see an example of this program try taking a look at this link
You can experiment with the code segment that they provide and see that if you do not allocate enough stack space that it is possible to have your program segfault.

A: The default stack size per thread is usually very large on most implementations of pthreads().  If you are running into issues where you need it larger than default though, you can try to increase it using pthread_attr_stacksize(), checking the return value as you do, and trying to find a larger value.  The actual limit will probably be based upon per process address space limits on your specific system.
If you just want to find out what the default stack size is, you can use pthread_attr_getstacksize().  It is not going to grow larger than that, unless you tell it to by adjusting it yourself before you create the thread(s).
Some code for adjusting stack sizes with pthreads is shown here
https://stackoverflow.com/a/15356607/2159730
Note: the example in the link is for trying to minimize stack usage, and finding a minimum (which is dangerous, without a lot of testing).  Sort of the opposite of what you seem to want to do, but the example may still be helpful to you.  Just approach it differently.
In general, you should probably not need to raise the pthread stack size above the default.  If you find you do, you probably should try understand why that is happening. It's fairly unusual.
If you could explain what's actually happening in your own code, instead of a general question, other solutions might present themselves.  I'm wondering if you are actually trying to reduce the per thread stack size, and just not explaining yourself clearly.  If that's the case, the link might be helpful for that reason as well.

A: I don't think there is an option to do that.
If you refer to <pthread.h>, look for the constant PTHREAD_STACK_MIN constant. That is the pre-determined stack size for all newly created threads by default.
The behavior of pthread_attr_setstacksize can be found here:
The pthread_attr_setstacksize() function will fail if:
[EINVAL]
    The value of stacksize is less than PTHREAD_STACK_MIN
    or exceeds a system-imposed limit.

So, to answer your question precisely, no you cannot set the max stack size of a thread using POSIX library.


text:
Q: Filling HStack swiftUI I want to create a button stack like having a play and record button using SwiftUI, after creating it just does not look anything like what I wanted.
var body: some View {

        HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/, spacing: 8) {
            Spacer()
            Button(action: {
                print("Recordinggg")
            }, label: {
                Text("Record")
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(40.0)
            })
            Spacer()
            Button(action: {
                print("Recordinggg")
            }, label: {
                Text("Play")
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(40.0)
            })
            Spacer()
        }

    }

What I actually want is something like this

A: Use proper frame, padding you can achieve this. Here is an example code.
Create ButtonStyle.
struct ThemeButtonStyle: ButtonStyle {
    func makeBody(configuration: Self.Configuration) -> some View {
        configuration.label
            .padding([.top, .bottom], 10)
            .foregroundColor(.white)
            .frame(minWidth: 0, maxWidth: .infinity, alignment: .center)
            .background(Color.blue)
            .cornerRadius(40.0)
    }
}

Your view
struct ContentView: View {
  @State private var phase: CGFloat = 0
    var body: some View {

        HStack(alignment: .center, spacing: 0) {
            Button(action: {
                print("Recordinggg")
            }, label: {
                Text("Record")
            })
            .buttonStyle(ThemeButtonStyle())

            Spacer()
            Button(action: {
                print("Recordinggg")
            }, label: {
                Text("Play")
            })
            .buttonStyle(ThemeButtonStyle())
        }
        .padding()
    }
}


text:
Q: pythonw.exe do not work with canopy I installed Enthought Canopy express 64-bit on Windows 7 professional 64-bit.
Then I got some .py and .pyw files. At first they are linked to Canopy so I cannot run .pyw files without console.
So I changed to open .pyw with pythonw.exe, but no results came out. I checked with IDLE.exe and if I open the file in IDLE and run it, it works. How can I set .pyw files to run without console?

A: Which pythonw.exe did you associate with your .pyw files?
They should be associated with the pythonw in your Canopy User Python, as described here:
https://support.enthought.com/entries/23646538-Make-Canopy-s-User-Python-be-your-default-Python-i-e-on-the-PATH-
This would normally be here:
 C:\Users\YOUR-USER-ID\AppData\Local\Enthought\Canopy\User\Scripts\pythonw.exe


text:
Q: Text disappears but the container is still there when resizing page Every time I'm resizing my screen size, text disappears. I checked live element selection and still see the div container where it should be. It's only the text which is disappearing. I have tried everything but to no avail. When I try moving it to left or right or resize it, it works. But it's just the text which is not visible. Please help me out.
Update: I checked and the problem is with anchor tag. I am still not able to fix it.


text:
Q: What is the topology on the Grassmannian $G_n(\mathbb{R}^{n+k})$? If the real projective space $\mathbb{P}^n=\mathbb{R}^{n+1}/(x\sim \lambda x, \lambda\in\mathbb{R})$, then how does one define a real Grassmanian $G_n(\mathbb{R}^{n+k})=\{V\subset\mathbb{R}^{n+k}\mid \dim V=n\}$ as a quotient of $\mathbb{R}^{n+k}$? I saw on Wikipedia that its topology is given by the quotient topology, without specifically referring to what quotient.
I am asking because in the definition of a tautological bundle over a Grassmannian, Wikipedia says that $G_n(\mathbb{R}^{n+k})$ is given a topology such that the map $G_n(\mathbb{R}^{n+k})\to \mathrm{End}(\mathbb{R}^{n+k})$, sending an $n$-plane $V$ to the orthogonal projection map $P_V$ onto that plane, is a homeomorphism onto its image.
https://en.wikipedia.org/wiki/Tautological_bundle#cite_note-3
As a consequence, then the set $U_V$ containing all $n$-planes $X$ such that $P_V(X)\cong X$ by a linear isomorphism is open. Is this because it is a map onto the set of automorphisms which is open from the determinant function?

A: Let $Y\subset\mathbb{R}^{n(n+k)}$ be the set of linearly independent $n$-tuples of elements of $\mathbb{R}^{n+k}$.  Then there is a surjection $p:Y\to G_n(\mathbb{R}^{n+k})$ sending an element of $Y$ to its span.  The topology on $G_n(\mathbb{R}^{n+k})$ is the quotient topology for this map $p$ (considering $Y$ as a subspace of $\mathbb{R}^{n(n+k)}$).
In particular, $p^{-1}(U_V)$ is the set of $n$-tuples which remain linearly independent after applying $P_V$ to each of them.  As you say, this is just the set on which a certain determinant does not vanish, and so is open in $Y$.

A: Consider the collection $M$ of matrices of $n\times (n+k)$ of rank $n$ inside matrices of this size. There is a map $M \to G(n,n+k)$ that sends a matrix $x$ to its column span. This onto and induces a topology on $G(n,n+k)$. The reduced row echelon form gives you canonical representatives for the class of a matrix.

A: Taking a basis of row vectors, each element of the Grassmannian, that is a subspace of $\Bbb R^{n+k}$, can be represented as an $n\times(n+k)$
matrix of rank $n$. Of course many different matrices represent
the same plane, but if $A$ is the space of full-rank $n\times(n+k)$
real matrices, it has a topology as a subspace of a vector space,
and the map to the Grassmannian is a quotient map as a map of
topological spaces.

A: (Just realized that the original question was asking specifically for a construction as a quotient topology.  I'll still post this answer as another way to construct a topology in case this view would be useful.)
There is a canonical way to cover the Grassmannian $G_n(\mathbb{R}^{n+k})$ by $\binom{n+k}{n}$ copies of $\mathbb{R}^{kn}$, as follows: for each subset $S$ of $n$ elements of $\{ 1, \ldots, n+k \}$, we have the subspaces given by the row spaces of $n \times (n+k)$ matrices where the columns corresponding to $S$ are $e_1, \ldots, e_n$ in order.  So for example, for $k=2$ and $n=3$, one possible form of matrices would be:
$$ \begin{bmatrix} * & 1 & 0 & * & 0 \\
                   * & 0 & 1 & * & 0 \\
                   * & 0 & 0 & * & 1
  \end{bmatrix}.$$
Each such map is injective.  To see the images cover the Grassmannian, take some basis of the subspace, and then the reduced row echelon form of the matrix with these vectors as rows has the required form, and has row space equal to the original subspace.
Now, what remains is to show that on overlaps between these copies, the transition maps $(U \subseteq \mathbb{R}^{kn}) \to (V \subseteq \mathbb{R}^{kn})$ are continuous.  In fact, it shouldn't be too hard to see that these transition maps are defined by rational functions.
Therefore, we can define a topology on the Grassmannian as the strong topology generated by these maps $\mathbb{R}^{kn} \to G_n(\mathbb{R}^{n+k})$, i.e. $U \subseteq G_n(\mathbb{R}^{n+k})$ is open if and only if the corresponding subsets of $\mathbb{R}^{kn}$ are each open.  The condition on transition maps then implies that each copy of $\mathbb{R}^{kn}$ is homeomorphic to $\mathbb{R}^{kn}$ with its subspace topology.

In fact, since the transition maps are also $C^\infty$, this also gives a canonical way to give the Grassmannian $G_n(\mathbb{R}^{n+k})$ a structure of $kn$-dimensional $C^\infty$ manifold.


text:
Q: How to execute a few task after from few hour to dozens of days in iOS? Even if I slide the application to kill the process, I want to run the task after a few hours to several tens of days.
Task is to get location information every few seconds.

A: In this case, you can just store the last task Date to the SharedPreference, every time the app launches, you can compare the current date with it, if the difference is greater than you expected interval (e.g. 30 days), you can run the task again and update the stored Date with the current date.


text:
Q: Receiving a reference error for Index Match, what am I doing wrong? What is wrong with my index match statement? I am getting:
#REF! error

when I use:
=INDEX(VendorSub[@[Unique ID]],MATCH([@VendorName]],VendorSub[VendorName],0),2)

I have two sheets in same workbook. I need to lookup the UniqueID from VedorSub where the VendorName matches the VendorName in GCMainForm and then return the value in GCMainForm. The formula is being called from GCMainForm.
VendorSub

GCMainForm

What am I missing?  If I am looking for the UniqueID for "AAA Fencing", it should return "18327".

A: I changed to a vlookup and was able to get the correct results.  Thanks for your input.

=VLOOKUP(Table1[@[7293_Vendor(s) currently working for]],VendorSub!A:B,2,0)


text:
Q: Android DownloadManager: Download fails, but COLUMN_REASON only returns "placeholder" DownloadManager appears to be the right choice for an app with lots of background downloads on a flaky mobile internet connection.
Using tutorial code found on the web, the app is able to request a download from the system's DM like so:
// in onCreate()
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

// in requestData()
Uri u = Uri.parse("http://server:8000/feed/data");
Request dreq = new Request(u);
dreq.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
downloadID = dm.enqueue(dreq);

The URL in that code is a test server on a local computer. The URL works, the browser in Android emulator can retrieve the page and the server returns HTTP code 200 when my app requests that page via DownloadManager and the code quoted above.
This is the relevant code in the ACTION_DOWNLOAD_COMPLETE BroadcastReceiver which gets called when DM has retrieved the file.
Query q = new Query();
q.setFilterById(downloadID);
Log.i("handleData()", "Handling data");
Cursor c = dm.query(q);
if (c.moveToFirst()) {
  Log.i("handleData()", "Download ID: " + downloadID + " / " + c.getInt(c.getColumnIndex(DownloadManager.COLUMN_ID)));
  Log.i("handleData()", "Download Status: " + c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)));
  if (c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
    String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
    Log.i("handleData()", "Download URI: " + uriString);
  } else if (c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_FAILED) {
    Log.i("handleData()", "Reason: " + c.getString(c.getColumnIndex(DownloadManager.COLUMN_REASON)));
  }
}

The strange result is this:
The DOWNLOAD_STATUS is 16 (or STATUS_FAILED), but the reason is "placeholder".
Why is that? Why does it fail when the server returned a 200 status code? And why is there no reason given by DownloadManager?

A: Answering myself here.
Here's the problem: COLUMN_REASON is not a string, but a number value.
Log.i("handleData()", "Reason: " + c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON)));

will return an actual error code that one can work with.


text:
Q: Test fails with ShimNotSupportedException I have a very simple test that uses a shim but when I run the test I get a "ShimNotSupportedException".  I am using VS2013 Ultimate and I am not debugging.
[TestMethod]
public void GetDateTimeString_ReturnDTString_SetDateTime_CurrentYear()
{
    using (ShimsContext.Create())
    {
        // Set 'UtcNow' to 1 March 2014
        ShimDateTime.UtcNowGet = () => new DateTime(2014, 3, 1, 5, 30, 28);

        var inputDate = new DateTime(2014, 06, 20, 18, 33, 50);

        // Act
        var actual = CustomTimeHelper.GetDateTimeString(inputDate);

        // Assert
        Assert.IsNotNull(actual);
    }
}

I have tried the following with no success

*

*Running VS as a Adminstrator

*Deleting System.4.0.0.0.Fakes from reference, System.fakes from the Fakes directory, and all System.4.0.0.0.Fakes files from the FakeAssemblies and recreating the fake from the right-click "Add-fakes assembly" menu in  references

*I'm not using a Test Settings File

*I have disabled IntelliTrace from the options menu

*I have done a Clean Solution and Rebuild

*I have performed the "Run All Tests"  via the Test menu item and via Test Explorer

*I have run just the single test that is broken

*I DO have a warning saying that "Some Fakes could not be generated" when when investigated (by setting Diagnostic="True" in the System.Fakes file, System.DateTime seems to be fine as it is not listed in the list of classes that could not be generated from

*I have Tried both Release and Debug and on other computers

If anyone has any ideas as to what might be happening or how to resolve the issue, it would be greatly appreciated.

A: The issue was coming from referencing version 11.0.0.0 of Microsoft.QualityTools.Testing.Fakes.
The following steps fixed the issue for me.

*

*remove all *.fakes references from the project

*Delete all files in your Fakes folder

*re-add Microsoft.QualityTools.Testing.Fakes version 12.0.0.0

*Regenerate the fake assemblies you deleted in step 1


text:
Q: How to get raw text of a Handlebars.js block template? I want to make this work:
{{#definePartial "myPartial"}}
  Value: {{value}}
{{/definePartial}}

{{>myPartial this}}

But I can't figure out how to get the text from the definePartial block helper. All I have is options.fn(), that would replace {{value}} with a value from the current context.
Is there a way to do this, without using <script> or other tag to store the partial?

A: This will work:
{{{{definePartial "myPartial"}}}}
  Value: {{value}}
{{{{/definePartial}}}}

{{>myPartial this}}


text:
Q: Could not locate the assembly "System.Fabric" Seeing the following build warning in command prompt,

D:\CxCache\MsBuild.Corext.14.0.23107.9\v14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3245: Coul d not resolve this reference. Could not locate
  the assembly "System.Fabric". Check to make sure the assembly exists
  on disk. If this reference is required by your code, you may get
  compilation errors.

followed by the error,

D:\CxCache\MsBuild.Corext.14.0.23107.9\v14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3245: Could not resolve this reference. Could not locate
  the assembly "System.Fabric". Check to make sure the assembly exists
  on disk. If this reference is required by your code, you may get
  compilation errors.        For SearchPath
  "{TargetFrameworkDirectory}".
                   Considered "D:\CxCache\DotNetFxRefAssemblies.Corext.4.6.0\System.Fabric.dll", but
  it didn't exist.
                   Considered "D:\CxCache\DotNetFxRefAssemblies.Corext.4.6.0\System.Fabric.exe", but
  it didn't exist.

My change,
From:
package id="Microsoft.ServiceFabric" version="5.2.207"
To:
package id="Microsoft.ServiceFabric" version="6.3.187"
I am new to Nuget and msbuild. Looking for starting pointers...Please help.

A: Okay, I did some research and nuget has Microsoft.ServiceFabric there are 2 ways to do this. Open the Package Manager (nuget) console, or open nuget package manager.
The Package Manager is located in visual studio (Tools > Nuget Package Manager > Package Manager) and/or around that area, that one is easy to look up. For installing you want to enter this into your package manager.
[Install-Package Microsoft.ServiceFabric -Version 7.0.466] or any version that follow in your visual studio project. Looking on nuget (dot) org you can find it easily and all the accepted versions, I already said this and I'll say it again. Be sure to be in your project when you do this and the reference will be added.


text:
Q: Returning row if value exists, inserting otherwises I have a table that is created like so:
CREATE TABLE IF NOT EXISTS my_table
     p_id uuid DEFAULT uuid_generate_v4() NOT NULL,
     my_column varchar(250) NOT NULL,
     PRIMARY KEY (p_id),
     CONSTRAINT unique_mycolumn UNIQUE (mycolumn);

What I would like to do is return p_id if a particular value matches whatever is in my_column, but if not, insert that particular value and return the newly generated value. I can "sort" of get around this by trying to from within my code calling the respective queries to query the value, and if that returns null, insert it, but that's a fairly big race condition and I'd like to do it within sql. I've seen a lot of similiar questions, but this is different given the unique constraint on that column.
EDIT: This is what I'm looking to accomplish: Say I have the following data:
1 | foo
2 | bar

If I query for "bar", I'd like to get 2 back. However, If I query for "baz", I'd like to have the table look like the following:
1 | foo
2 | bar
3 | baz

So I guess it would be better described as "return ID if the value exists, and insert it the value otherwise to create a new row".

A: You could try something like this:

with ins as (insert into my_table (my_column)
select 'baz' where not exists
   (select 1 from my_table where my_column = 'baz')
returning p_id)
select p_id from ins
union all
select p_id from my_table where my_column = 'baz';

Note however that this can fail if two transactions try to insert the value 'baz' at the same time.


text:
Q: How can I get "for loop" to work properly? I want to impute missing values with (upper value + lower value)/2.
If column "A" has NaN, I want to calculate like above and then put the value to the next column "B".
In my original dataset, I don't know how many NaNs. So I should check how many NaNs are there in a row.
I think my problem is the 'for loop'.
I tried to solve this whole day, but I couldn't.
Please check my code and give me some advice.
Thank you so much for your work and time.
Here is the sample dataset and my code.
df = pd.DataFrame([[np.NaN,np.NaN],
              [2,np.NaN],
              [8,np.NaN],
              [11,np.NaN],
              [8,np.NaN],
              [np.NaN,np.NaN],
              [np.NaN,np.NaN],
              [8,np.NaN],
              [8,np.NaN],
              [8,np.NaN],
              [8,np.NaN],
              [np.NaN,np.NaN],
              [np.NaN,np.NaN],
              [np.NaN,np.NaN],
              [8,np.NaN]],columns=list('AB'))

for r in range(df.shape[0]):
    if math.isnan(df.A[r]) == True:
        nan_find = True
        have_nan = False
        start_row = r
        while nan_find == True:
            r = r + 1
            if math.isnan(df.A[r]) == True:
                nan_find = True
                have_nan = True
            else:
                end_row = r-1
                nan_find = False
                r = r - 1
        for start_row in range(start_row, end_row):
            if start_row == 0:
                df.B[start_row] = (df.A[end_row+1])/2
            elif (start_row == df.shape[0]) | (end_row == df.shape[0]):
                df.B[start_row] = (df.A[start_row-1])/2
            else:
                df.B[start_row] = (df.A[start_row-1] + df.A[end_row+1])/2
    else:
        pass


text:
Q: How do I set map zoom based on nearest pin to current location Right now I am setting my region based on users current location.  I would like to now set the zoom level so I can see the users current location and the nearest pin that is being pulled in via json.
Not until run time will the app know the number of pins or the locations of said pins.
Here is what I have so far.
@implementation LocationsViewController

@synthesize mapView;
@synthesize locationManager;
@synthesize phone;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = NSLocalizedString(@"Locations", @"Locations");
        self.tabBarItem.image = [UIImage imageNamed:@"locations"];
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

 #pragma mark - View lifecycle

 //Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad
{
    [super viewDidLoad];
    self.locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"New latitude: %f", newLocation.coordinate.latitude);
    NSLog(@"New longitude: %f", newLocation.coordinate.longitude);

    MKCoordinateRegion region;
    region.center.latitude =newLocation.coordinate.latitude;
    region.center.longitude=  newLocation.coordinate.longitude;
    region.span.longitudeDelta=0.2;
    region.span.latitudeDelta =0.2;
    [mapView setRegion:region animated:YES];
    [mapView setDelegate:self];
    //[locationManager stopUpdatingLocation];

}

-(void)viewDidDisappear:(BOOL)animated
{
    [locationManager stopUpdatingLocation];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [locationManager startUpdatingLocation];

    if([self connectedToNetwork] != YES)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"OH NO!" message:@"To get the latest information you need a data or wi-fi connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
    else
    {
        [mapView removeAnnotations:mapView.annotations];

        NSString *urlString = [NSString stringWithFormat:@"http://www.mywebsite.com/json.json"];

        NSURL *url = [NSURL URLWithString:urlString];

        NSData *data = [NSData dataWithContentsOfURL:url];

        NSError *error;

        NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        for(id key in json) {
            id value = [json objectForKey:key];
            NSString *titlePin = [value valueForKey:@"address"];
            NSString *address = [value valueForKey:@"title"];
            NSString *latitude = [value valueForKey:@"latitude"];
            NSString *longitude = [value valueForKey:@"longitude"];

            NSArray* foo = [address componentsSeparatedByString: @":"];
            NSString* address2 = [foo objectAtIndex: 0];
            phone = [foo objectAtIndex: 1];

            double myLatitude = [latitude doubleValue];
            double myLongitude = [longitude doubleValue];

            MKCoordinateRegion location1;
            location1.center.latitude =myLatitude;
            location1.center.longitude= myLongitude;
            location1.span.longitudeDelta=0.1;
            location1.span.latitudeDelta =0.1;

            MapAnnotation *ann1 =[[[MapAnnotation alloc] init] autorelease];
            ann1.title=[NSString stringWithFormat:@"%@",titlePin];
            ann1.subtitle=[NSString stringWithFormat:@"%@",address2];
            ann1.phone=[NSString stringWithFormat:@"%@",phone];
            ann1.coordinate= location1.center;
            [mapView addAnnotation:ann1];
            [phone retain];

        }
     }
}

-(MKAnnotationView *) mapView:(MKMapView *)mapView2 viewForAnnotation:(id<MKAnnotation>)annotation {
    if (annotation == mapView2.userLocation) {
        return nil;
    }else{
         MKPinAnnotationView *MyPin=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"current"];
        MyPin.pinColor = MKPinAnnotationColorPurple;

        UIButton *advertButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
         [advertButton setImage:[UIImage imageNamed:@"mapphone"] forState:UIControlStateNormal];
         [advertButton addTarget:self action:@selector(button:) forControlEvents:UIControlEventTouchUpInside];
         MyPin.rightCalloutAccessoryView = advertButton;

        MyPin.draggable = NO;
        MyPin.highlighted = YES;
        MyPin.animatesDrop=TRUE;
        MyPin.canShowCallout = YES;

        return MyPin;
     }
 }

 -(void)button:(id)sender {

     UIButton *button = (UIButton *)sender;

     MKPinAnnotationView *annotationView = (MKPinAnnotationView*)button.superview.superview;

     MapAnnotation *mapAnnotation = annotationView.annotation;

     UIDevice *device = [UIDevice currentDevice];
     if ([[device model] isEqualToString:@"iPhone"] ) {
         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",mapAnnotation.phone]]];
     } else {
         UIAlertView *Notpermitted=[[UIAlertView alloc] initWithTitle:mapAnnotation.phone message:@"Your device doesn't support this feature." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
         [Notpermitted show];
         [Notpermitted release];
    }

}

 - (BOOL) connectedToNetwork
 {
    Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];
    BOOL internet;
    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
        internet = NO;
    } else {
        internet = YES;
    }
    return internet;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}

@end

A: I did something similar, but based on two annotations, not the user's location. You should be able to replace mapView.centerCoordinate with mapView.userLocation.coordinate.
in viewForAnnotation:
   CLLocation *centerLoc = [[CLLocation alloc] initWithLatitude:mapView.centerCoordinate.latitude longitude:mapView.centerCoordinate.longitude];
   CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:[annotation coordinate].latitude longitude:[annotation coordinate].longitude];
   CLLocationDistance distance = [loc2 distanceFromLocation:centerLoc];

   MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(mapView.centerCoordinate, distance*2, distance*2);
   MKCoordinateRegion adjustedRegion = [mapView regionThatFits:viewRegion];
   [mapView setRegion:adjustedRegion animated:YES];

Note, this code will re-calc the zoom level each time you add an annotation. You may need to save the distance and only change the map if the new distance is greater than the prior distance.


text:
Q: Best way to check if value is integer ? Coldfusion 9 I have fields to test and make sure they only accept integers. There is few functions but I wasn't sure which one is the best. First I tried isValid("integer",value) but I have discovered that "1,5" will be accepted as an integer. So then I tried isNumeric(value) but this will accept values like 1.5. I'm wondering what should be the best way to check for integers? Maybe two combine these two functions like:
<cfif isValid("integer",value) AND isNumeric(value)>

Or there is better way to do this?

A: cfscript
// Returns if the provided value is a signed integer up to 32 Bit.
function isINT(any value) {

    return (
        isSimpleValue(ARGUMENTS.value) &&
        (reFind("^\-?[0-9]{1,10}$", ARGUMENTS.value) > 0) &&
        (ARGUMENTS.value <= 2147483647) &&
        (ARGUMENTS.value >= -2147483648)
    );
}

cftag
<cffunction name="isINT" access="public" output="false" returnType="boolean"
    hint="Returns if the provided value is a signed integer up to 32 Bit.">

    <cfargument name="value" type="any" required="true">

    <cfreturn (
        isSimpleValue(ARGUMENTS.value) and
        (reFind("^\-?[0-9]{1,10}$", ARGUMENTS.value) gt 0) and
        (ARGUMENTS.value lte 2147483647) and
        (ARGUMENTS.value gte -2147483648)
    )>
</cffunction>

*

*isSimpleValue making sure the input is a primitive type (by CF means), because all numbers are considered simple values in CF (string conversion)

*reFind regular expression checking digits-only (with or without sign), minimum of one digit, maximum of ten digits (implicit call of toString here)

*check the range, all numeric types fit into 4 Bytes, thus no need to "upgrade" the type (as you would need to with BigInteger, BigDecimal etc.)

If you don't need the range check for 4 Byte integers, @DanBracuk posted an answer with a function that performs around 5-6 times faster than this one.

A: Here's the isInteger UDF that I prefer using:
function isInteger(num){
    return YesNoFormat(refind("^-?\d+$", num) AND VAL(num) LTE 2147483647 AND VAL(num) GTE -2147483648);
}

Here are some tests to determine how it functions and compares against the various built-in functions.
https://gist.github.com/JamoCA/fab1104a3a9074434ff336630dd5ffd1
View the results using TryCF.com
https://trycf.com/gist/fab1104a3a9074434ff336630dd5ffd1

A: You could try this:
value = replace(value, ',', '', 'all');
numberIsInteger = isNumeric(value) && round(value) == value ? true : false;

Note
People often include commas in large numbers such as 1,000,000.  isNumeric will return false for that string, as will the refind function in the other answers.


text:
Q: tkinter PIL image is not shown up in class I can't show up the Image in tkinter PIL class.
Image is packed or placed successfully but it is not showing up.
windowxp wall paper and a man's face are not shown.
I made message box when click his face.
So if I click the location, message box is showing up. But picture is not showing up. Just location :(
I use windows 64bit and Python 3.6
I am Korean. I'm not goot at English.... Please understand me.
Please help me
This is right display: screenshot
from tkinter import *
import tkinter as tk
from tkinter import messagebox
from PIL import Image, ImageTk

    ##함수
class Mainwindow(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)
        self.title("김상곤이 좋아하는 꿈꾸는 학과 과목 문제 맞추기♡")
        self.geometry("1600x900")
        self.resizable(width=FALSE, height=FALSE)

        wall = tk.PhotoImage(file="gif/bg.gif")
        labelwall = tk.Label(self, image = wall)
        labelwall.place(x=0, y=0)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        def func_make():
            messagebox.showinfo("제작자", "김재온, 정성윤, 안예진, 이소유, 우연서")

        def func_exit():
            window.quit()
            window.destroy()

        mainMenu=Menu(self)
        fileMenu=Menu(mainMenu)
        self.config(menu=mainMenu)
        mainMenu.add_cascade(label="파일", menu=fileMenu)
        fileMenu.add_command(label="제작자", command=func_make)
        fileMenu.add_separator()
        fileMenu.add_command(label="종료", command=func_exit)

        self.frames={}
        for F in (MainPage, QuizPage):
            page_name=F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name]=frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("MainPage")

    def show_frame(self, page_name):

        frame = self.frames[page_name]
        frame.tkraise()

    def 국어():

        page == 1

    subject=['국어', '과학', '역사', '사회', '기술']

#색이나 위치 숫자 설정

mint="#99FFFF"
subjectsize=30
subjectbutton=60

##위젯

class MainPage(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)
        self.controller=controller
        def clickksk(event):
                messagebox.showinfo("김상곤", "아주 좋아요^^")

        labeltitle=tk.Label(self, text=
                            """김상곤이 좋아하는 꿈꾸는
학과 과목 문제 맞추기♡""", font=("궁서체", 35), bg="#8DFD73")

        ksk=tk.PhotoImage(file="gif/ksk.gif")
        labelksk=tk.Label(self, image=ksk)

        labelksk.place(x=400-subjectbutton, y=200)
        labelksk.bind("<Button>", clickksk)
        labelhow=tk.Label(self, text="게임방법!                   ", font=("맑은 고딕", 30), bg="#FFE400")
        labelexplain=tk.Label(self, text=
        """원하는 과목을 택해 클릭한후,
        OX퀴즈를 풀면 됩니다^^
        난이도=중3""", font=("고딕체", 25), bg="#FFE400")

        btKorean=tk.Button(self, text="국어", font=("양재블럭체", subjectsize), bg=mint,
                        command=lambda: controller.show_frame("QuizPage"))

        btScience=tk.Button(self, text="과학", font=("양재블럭체", subjectsize), bg=mint)
        btHistory=tk.Button(self, text="역사", font=("양재블럭체", subjectsize), bg=mint)
        btSocial=tk.Button(self, text="사회", font=("양재블럭체", subjectsize), bg=mint)
        bttech=tk.Button(self, text="기술", font=("양재블럭체", subjectsize), bg=mint)

        ##pack하는 장소(코드 순차대로)

        labeltitle.place(relx= 0.25, rely=0.02, relwidth=0.5)
        labelhow.place(x=610-subjectbutton, y=200, relwidth=0.3)
        labelexplain.place(x=610-subjectbutton, y=260, relwidth=0.3)

        btKorean.place(x=400-subjectbutton, y=600)
        btScience.place(x=600-subjectbutton, y=600)
        btHistory.place(x=800-subjectbutton, y=600)
        btSocial.place(x=1000-subjectbutton, y=600)
        bttech.place(x=1200-subjectbutton, y=600)

        btKorean.bind("<Button-1>")
        btScience.bind("<Button-1>")
        btHistory.bind("<Button-1>")
        btSocial.bind("<Button-1>")
        bttech.bind("<Button-1>")

class QuizPage(tk.Frame):
    def __init__(self, parent, controller):

        OB=PhotoImage(file="gif/OB.gif")
        XR=PhotoImage(file="gif/XR.gif")

        tk.Frame.__init__(self, parent)
        self.controller = controller
        buttonOB=Button(self, image=OB)
        buttonXR=Button(self, image=XR)

        buttonOB.place()
        buttonXR.place()

if __name__ == "__main__":
    app = Mainwindow()
    app.mainloop()

A: I think your main problem is you are using two subclassed frames and using grid to manage them but the main application window is not expanding the grid area. You need to add the following to MainWindow.__init__:
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)

so that the (0,0) cell is expanded to fill all the available space. Then your currently selected frame will expand into that region as it has sticky='NSWE' set in the grid method call.
Where you define container you are both packing and gridding. You have to only use one. However, this looks like dead code. Maybe you intended to put the subclassed frames into this container at one time.
Also, you cannot just call buttonXR.place(), you need to give it a position. For instance: buttonXR.place(x=1, y=1).


text:
Q: Loading image in Flutter | Path from content root doesn't work, but absolute path works Very simple app, the image is in project/images folder.

*

*When I try to load it from the relative path:
'images/diamond.png'
the image doesn't load.

*When I do it from the absolute path: '/Users/MacBookAir/StudioProjects/secondtry_iamrich/images/diamond.png'
it does.
Why is this? Can anyone please help?
import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.blueGrey,
        appBar: AppBar(
          title: const Text('I am Rich'),
          backgroundColor: Colors.blueGrey[900],
        ),
        body: const Center(
          child: Image(
            image: AssetImage('images/diamond.png'),
          ),
        ),
      ),
    ),
  );
}

This is the error it is providing:
======= Exception caught by image resource service ================================================
The following assertion was thrown resolving an image codec:
Unable to load asset: images/diamond.png

When the exception was thrown, this was the stack:
#0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:237:7)
<asynchronous suspension>
#1      AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:658:14)
<asynchronous suspension>
Image provider: AssetImage(bundle: null, name: "images/diamond.png")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#99cb5(), name: "images/diamond.png", scale: 1.0)
====================================================================================================

A: Do not forgot to add image folder path to your pubspec.ymal folder like
  assets:
    - assets/images/
    - assets/images/icons/
    - assets/loader.json

Use this plugin in your android studio it will auto generate your all assets no need to write path.
Use it like this
Image.asset(Assets.imagesNoDataFound, scale: 3.5)

A: Uncomment and change the asset section in your pubspect.yaml file can fix it.
  assets:
    - images/


text:
Q: File is a Method which is not valid in the given context Trying to check whether a file exists inside a path but getting a build error on File.

File is a method and cannot be used in this context.

 if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
        if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile);

Full Class code
 static void CovertExcelToCsv(string excelFilePath, string csvOutputFile, int worksheetNumber = 1)
    {
        if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
        if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile);

        // connection string
        var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;IMEX=1;HDR=NO\"", excelFilePath);
        var cnn = new System.Data.OleDb.OleDbConnection(cnnStr);

        // get schema, then data
        var dt = new DataTable();
        try
        {
            cnn.Open();
            var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            if (schemaTable.Rows.Count < worksheetNumber) throw new ArgumentException("The worksheet number provided cannot be found in the spreadsheet");
            string worksheet = schemaTable.Rows[worksheetNumber - 1]["table_name"].ToString().Replace("'", "");
            string sql = String.Format("select * from [{0}]", worksheet);
            var da = new OleDbDataAdapter(sql, cnn);
            da.Fill(dt);
        }
        catch (Exception e)
        {
            // ???
            throw e;
        }
        finally
        {
            // free resources
            cnn.Close();
        }

        // write out CSV data
        using (var wtr = new StreamWriter(csvOutputFile))
        {
            foreach (DataRow row in dt.Rows)
            {
                bool firstLine = true;
                foreach (DataColumn col in dt.Columns)
                {
                    if (!firstLine) { wtr.Write(","); } else { firstLine = false; }
                    var data = row[col.ColumnName].ToString().Replace("\"", "\"\"");
                    wtr.Write(String.Format("\"{0}\"", data));
                }
                wtr.WriteLine();
            }
        }
    }

How can  fix this?

A: You probably have this method inside MVC controller in which File method exists. Add in your code System.IO.File instead of File


text:
Q: R markdown asis breaks valid html code I have a function that outputs html code that renders properly, but encasing it in a markdown document R code chunk with ´results = "asis"` fails. I trace problem back to spaces in my HTML code.  I like the spaces because they make it easier to read the raw HTML file.  If you would please consider installing my R package "rockchalk", you could run this and see the same.
I show the problem is caused by spaces in HTML (which markdown treats as markup for code) in the following MRE. The output I get without any additional style sheet magic is available: http://pj.freefaculty.org/scraps/mre.html
You scroll down you see the table is broken, but after sifting out the extra spaces, then the table shows as intended.
In your opinion, is this simply my user error for relying on spaces in HTML code, or is it a bug in "asis" in R markdown.
---
title: "Guide Documents"
author:
 - name: Paul Johnson
   affiliation: Center for Research Methods and Data Analysis, University of Kansas

abstract:
    Author, please REMEMBER TO INCLUDE AN ABSTRACT BEFORE FINALIZING THIS DOCUMENT!
date: "`r format(Sys.time(), '%Y %B %d')`"
output:
  html_document:
    highlight: haddock
---

```{r setup, include = FALSE}
##This Invisible Chunk is required in all CRMDA documents
outdir <- paste0("tmpout")
if (!file.exists(outdir)) dir.create(outdir, recursive = TRUE)
knitr::opts_chunk$set(echo = TRUE, comment = NA, fig.path = paste0(outdir, "/p-"))
options(width = 70)
```

```{r myregs}
library(rockchalk)
set.seed(2134234)
dat <- data.frame(x1 = rnorm(100), x2 = rnorm(100))
dat$y1 <- 30 + 5 * rnorm(100) + 3 * dat$x1 + 4 * dat$x2
dat$y2 <- rnorm(100) + 5 * dat$x2
m1 <- lm(y1 ~ x1, data = dat)
m2 <- lm(y1 ~ x2, data = dat)
m3 <- lm(y1 ~ x1 + x2, data = dat)
gm1 <- glm(y1 ~ x1, family = Gamma, data = dat)
or1 <- outreg(list("Amod" = m1, "Bmod" = m2, "Gmod" = m3),
              title = "My Three Linear Regressions", float = FALSE, type = "html")
```

```{r browseme}
or1 <- outreg(list("Amod" = m1, "Bmod" = m2, "Gmod" = m3),
              title = "My Three Linear Regressions", float = FALSE, type = "html")
```

```{r flawed, results = "asis"}
cat(or1)
```

```{r cleaned, results = "asis"}
or1 <- gsub(" "," ", or1)
or1 <- gsub("^\\ *", "", or1)
or1 <- paste(or1, collapse = "")
or1 <- gsub("\\ \\ \\ \\ \\ \\ ", " ", or1)
or1 <- gsub("\\ \\ \\ ", " ", or1)
cat(or1)
```

```{r sessionInfo, echo = FALSE}
sessionInfo()
```

Available under
[Created Commons license 3.0 ](http://creativecommons.org/licenses/by/3.0/)

A: The knitr chunk option results='asis' has done its job correctly. The problem is Pandoc's Markdown treats indented lines (by four spaces) as literal code blocks (

).
The solution is either remove the leading spaces, or protect them. It seems you do not want to do the former. You can pass your HTML code to htmltools::HTML() so that the output is protected during Pandoc's conversion.


text:
Q: Sorting nodes in VirtualTreeView - OnCompareNodes does not fire for all nodes to be compared I'm having a (strange) sorting problem with VirtualTreView (v 6.1.0 / Delphi 10 Seattle). I've looked into more recent versions of VTV and there's no mention of a similar behavior.
I'll post full source code, but let me first explain what I'm trying to accomplish:

*

*There are nodes I'd like to sort

*Each node has a kind of stage - where the node stage determines the sort order of the node (in that stage)

*I'd like to have nodes sorted when a particular stage is selected by their stage sort value. Those nodes that are not included in the stage are to be set invisible.

Here's the record I'm using:
PRecord = ^TRecord;
TRecord = record
  SortOrder : array [0..4] of integer;
  PositionAdded : integer;
end;

Here's how nodes are added:
procedure TVTVSortForm.FormCreate(Sender: TObject);
var
  vn : PVirtualNode;
  pr : PRecord;
begin
  tree.NodeDataSize := SizeOf(TRecord);

  vn := tree.AddChild(nil);
  pr := PRecord(tree.GetNodeData(vn));
  pr.PositionAdded := vn.Index;
  pr.SortOrder[0] := 0; //first in 0 - removed in later
  pr.SortOrder[1] := -1;
  pr.SortOrder[2] := -1;
  pr.SortOrder[3] := -1;
  pr.SortOrder[4] := 2; //third in 4

  vn := tree.AddChild(nil);
  pr := PRecord(tree.GetNodeData(vn));
  pr.PositionAdded := vn.Index;
  pr.SortOrder[0] := 1; //second in 0
  pr.SortOrder[1] := 0; //first in 1
  pr.SortOrder[2] := 1; //second in 2
  pr.SortOrder[3] := 1; //second in 3
  pr.SortOrder[4] := 0; //first in 4

  vn := tree.AddChild(nil);
  pr := PRecord(tree.GetNodeData(vn));
  pr.PositionAdded := vn.Index;
  pr.SortOrder[0] := 2; // third in 0
  pr.SortOrder[1] := 2; //third in 1
  pr.SortOrder[2] := 0; //first in 2
  pr.SortOrder[3] := -1; //removed in 3
  pr.SortOrder[4] := 1; //second in 4

  vn := tree.AddChild(nil);
  pr := PRecord(tree.GetNodeData(vn));
  pr.PositionAdded := vn.Index;
  pr.SortOrder[0] := -1; //not in 0
  pr.SortOrder[1] := 1;  //second in 1
  pr.SortOrder[2] := 2; //third in 2
  pr.SortOrder[3] := 0; // first in 3
  pr.SortOrder[4] := -1; // not in 4

  tree.ValidateNode(nil, true);
end;

"Stages" are SortOrder indices.
SortOrder[x] := y means that the order of the node in stage X should be y.
For example, SortOrder[2] = 0 means that in stage 2 the node should be first node. SortOrder[3] = -1 means that the node "does not exist" in stage 3.
There's a radiogroup having 5 elements (0...4) presenting the stage. When the stage is selected the nodes should be sorted according their SortOrder value for the stage selected (I'm also hiding nodes that are not existing in a stage:
procedure TVTVSortForm.rgFilterAndSortClick(Sender: TObject);
begin
  tree.Sort(tree.RootNode, 0, sdAscending);

  tree.IterateSubtree(
  nil,
  procedure (Sender: TBaseVirtualTree; Node: PVirtualNode; Data: Pointer; var Abort: Boolean)
  var
    d : PRecord;
  begin
    d := PRecord(tree.GetNodeData(Node));
    //tree.IsVisible[Node] := -1 <> d.SortOrder[rgFilterAndSort.ItemIndex];
  end,
  nil);
end;

The OnCompare looks like:
procedure TVTVSortForm.treeCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
var
  d1, d2 : PRecord;
begin
  d1 := PRecord(Sender.GetNodeData(Node1));
  d2 := PRecord(Sender.GetNodeData(Node2));

  if (-1 <> d1.SortOrder[rgFilterAndSort.ItemIndex]) AND (-1 <> d2.SortOrder[rgFilterAndSort.ItemIndex]) then
    result := d1.SortOrder[rgFilterAndSort.ItemIndex] - d2.SortOrder[rgFilterAndSort.ItemIndex];
end;

Therefore I'm only comparing those nodes that exist in the selected stage (i.e. SortOrder[stage] <> -1).
The GetText displays the sort order for the selected stage + the original position of the node at the time of adding to the tree.
procedure TVTVSortForm.treeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string);
var
  Data: PRecord;
begin
  Data := Sender.GetNodeData(Node);
  CellText := Format('s:%d, p:%d', [Data.SortOrder[rgFilterAndSort.ItemIndex], Data.PositionAdded]);
end;

Now, what happens when you start the program and go (select radio button/click) to stage (3), the order is 1,0 instead of 0,1 (I'm omitting "-1" nodes).
If after selecting stage (3) you select (1) then (3) -> stage 3 is sorted ok. But then go to stage (0),(2),(4) and the order is 1,2,0 instead of 0,1,2.
Any ideas why this is not working (as expected)?
I've noted that when two nodes go into OnCompare: if one of the nodes has -1 for the selected stage, the other node will not any more be compared to the remaining nodes that exist in the selected stage. How to force the other node to still be matched with other same-stage nodes?

A: Omg, I've been trying to figure out what's wrong here for the last few days and, of course, once I posted my problem here I've figured it out.
The OnCompare needs to compare "all" nodes - so skipping some nodes (when a node is "not in stage") is what was wrong with my code.
I need to make sure that the stage node gets still compared to other same-stage nodes when it does not get compared to the matched different-stage node.
Finally, I rewrote the OnCompare method like this, and for the moment (I have a larger real world application for testing) all seems to be ok:
procedure TVTVSortForm.treeCompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer);
var
  d1, d2 : PRecord;
begin
  d1 := PRecord(Sender.GetNodeData(Node1));
  d2 := PRecord(Sender.GetNodeData(Node2));

  if (-1 = d1.SortOrder[rgFilterAndSort.ItemIndex]) then result := -1
  else if (-1 = d2.SortOrder[rgFilterAndSort.ItemIndex]) then result := 1
  else
    if (-1 <> d1.SortOrder[rgFilterAndSort.ItemIndex]) AND (-1 <> d2.SortOrder[rgFilterAndSort.ItemIndex]) then
      result := d1.SortOrder[rgFilterAndSort.ItemIndex] - d2.SortOrder[rgFilterAndSort.ItemIndex]
  else
  begin
    //just testing if this ever happens
    if (-1 = d1.SortOrder[rgFilterAndSort.ItemIndex]) then Inc(d1.PositionAdded);
    if (-1 = d2.SortOrder[rgFilterAndSort.ItemIndex]) then Inc(d2.PositionAdded);
  end;
end;

Still, frankly, this is not what I would expect from how comparing nodes works.


text:
Q: Discord bot 'connect' command with discordjs v13, @discordjs/voice & SlashCommandBuilder I am currently stuck with following problem: my test 'connect' command doesn't work if I try to execute it in Discord. Normal reply commands are working fine with the current build, but I can't figure out how to do voice channel shenanigans.
Here is the code of my 2 files:
(can post the deploy-commands.js too if needed, bit its the same code like in the discord.js guide)
EDIT #1: With GentleAutumnRain help I could resolve the first error, I changed all code snippets accordingly.
EDIT #2: fixed, bot is now joining the VC
connect.js v3 //the test command
const { SlashCommandBuilder } = require('@discordjs/builders');
const voiceDiscord = require('@discordjs/voice'); //3.change[GentleAutumnRain]

module.exports = {
    data: new SlashCommandBuilder()
        .setName('connect')
        .setDescription('The bot will connect to your voice channel!'),
        execute: async (interaction, client) => { //1.change[GentleAutumnRain]
            const channel = interaction.member.voice.channel;
            //Error case handling
            if(!channel) return interaction.channel.send('Please join a Voice Channel first!');

            const player = voiceDiscord.createAudioPlayer();
            const resource = voiceDiscord.createAudioResource('');

            const connection = voiceDiscord.joinVoiceChannel({
                channelId: channel.id,
                guildId: interaction.guild.id,
                adapterCreator: interaction.guild.voiceAdapterCreator,
            });

            player.play(resource);
            connection.subscribe(player);

            // checking for ending, leaving VC if true
            /*player.on(voiceDiscord.AudioPlayerStatus.Idle, () => {
                connection.destroy();
            });*/
        },
};

index.js v2 //main
// Require the necessary discord.js classes
const fs = require('fs');

const { Client, Collection, Intents } = require('discord.js');
const { token } = require('./config.json');

// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_VOICE_STATES] }); //2.change[GentleAutumnRain]
client.commands = new Collection();

const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    // Set a new item in the Collection
    // With the key as the command name and the value as the exported module
    client.commands.set(command.data.name, command);
}

// When the client is ready, run this code (only once)
client.once('ready', () => {
    console.log('Ready!');
    client.user.setActivity(" YOU!", {type: "WATCHING"});
});
// Main - waiting for interaction
client.on('interactionCreate', async interaction => {
    if (!interaction.isCommand()) return;

    const command = client.commands.get(interaction.commandName);

    // Return error if a false command was typed
    if (!command) return;
    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
    }
});

// Login to Discord with your client's token - MUST be always at the end of this script!
client.login(token);

TERMINAL OUTPUT if 'connect' is executed:
Already tried to sub 'user' with 'member' but the result is the same.
NEW:
PS C:\Users\User\Documents\GitHub\DiscordBot_REPO> node .\index.js
Ready!
TypeError: Cannot read properties of undefined (reading 'createAudioPlayer')
    at Object.execute (C:\Users\User\Documents\GitHub\DiscordBot_REPO\commands\connect.js:13:41)
    at Client.<anonymous> (C:\Users\User\Documents\GitHub\DiscordBot_REPO\index.js:34:17)
    at Client.emit (node:events:390:28)
    at InteractionCreateAction.handle (C:\Users\User\Documents\GitHub\DiscordBot_REPO\node_modules\discord.js\src\client\actions\InteractionCreate.js:66:12)
    at Object.module.exports [as INTERACTION_CREATE] (C:\Users\User\Documents\GitHub\DiscordBot_REPO\node_modules\discord.js\src\client\websocket\handlers\INTERACTION_CREATE.js:4:36)
    at WebSocketManager.handlePacket (C:\Users\User\Documents\GitHub\DiscordBot_REPO\node_modules\discord.js\src\client\websocket\WebSocketManager.js:350:31)    at WebSocketShard.onPacket (C:\Users\User\Documents\GitHub\DiscordBot_REPO\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22)
    at WebSocketShard.onMessage (C:\Users\User\Documents\GitHub\DiscordBot_REPO\node_modules\discord.js\src\client\websocket\WebSocketShard.js:300:10)
    at WebSocket.onMessage (C:\Users\User\Documents\GitHub\DiscordBot_REPO\node_modules\ws\lib\event-target.js:199:18)
    at WebSocket.emit (node:events:390:28)

This is my first question on this site, so if someone has critique how the question was written please let me know.
Anyways I would be grateful if someone could give me a helping hand in that case.

A: You were right in changing it to interaction.member.voice.channel, that is how it will work, but you have to supply interaction properly to your connect command.
Right now, as you can see on this line execute: async (client, interaction) => { in your connect.js you are asking for two parameters, but when you attempt to execute this function on this line await command.execute(interaction); you only supply one. In javascript this is fine and the code will still work, but it is a first come first serve kind of deal. The interaction parameter you supply will be given to the first parameter you require in the execute command or in simpler words: The interaction you give as a parameter is being stored in the client variable in your execute function.
You can solve this simply switching the client and interaction parameter around in your execute command thereby allowing your interaction to slip into the right variable.
Additionally, in order to connect to a voice channel and do a lot of the related work you will need to supply you client with the GUILD_VOICE_STATES intent. Simply add Intents.FLAGS.GUILD_VOICE_STATES in the array of intents of your client in the index.js file and you're golden.


text:
Q: Jquery select item from popup and post back to parent In one of my projects, I have many different sections where I need to filter some data and select the required, for example - On newsletter page where I need to click a link to "add users" which opens up a popup window where I can search users by name, ID etc then check the checkboxes and click "Select". This adds their IDs (or maybe emails) in the hidden form on the Newsletter page.
Similarly, I need to attach a file to newsletter then I click on an another link which opens up a popup with list of files which I can search and then finally select one. I have similar other requirements in other sections of the website which means I have to write similar type of code again and again.
I won't mind duplicating code if it were to be used at one or two places. But I have more than 8-9 different sections where I have to select users, files, some other items etc so I was thinking if there was a generic plugin sort of tool which takes a url of the search page and returns the data back in a specific format to the parent opener window then I just include that code on each of these pages and just have to maintain one/two files only.
How would you handle this sort of requirement? Is there any JQuery plugin available which does similar thing?

A: I'm not aware of a plugin for this, but this Q&A looks relevant:
Open popup and refresh parent page on close popup
Perhaps you can be the hero who implements such a plugin, Mr user1421214!


text:
Q: How to fix an element after scroll in an AngularJS webpage I recently made a website in AngularJs. I am still in the learning phase.
I wish to fix an element on a page after it reaches the top. I have tried all sorts of Javascript and Jquery functions. However, they don't seem to be working.
I also tried using Angular UI's ui-scrollfix but it is also not working.
I am sharing my code. It is a partial page. Please advise me a method to achieve the above mentioned effect.

About Us

What are    we?

Brands Associations

Know Us

Our Motto

What are we?

Some content goes here.

Brands Associations

Some content goes here.

Know Us

Some content goes here.

Our Motto

Some content goes here.

I need to fix the ul class .nav .nav-justified after it hits the top of the page.
I am using bootstrap.
here are the javascript dependencies.

Please help...

A: To fix your ul to the top when it hits the top of the page on scroll, you can put a directive on it that checks for the window's scrollTop() exceeding the ul element's offset top. When that occurs, the directive can just add a class to the element that fixes it to the top.
So your ul markup would look like this, with new directive set-class-when-at-top on it:

That directive would add the CSS class fix-to-top to the element when the element hits the top of the page. The directive definition would look like this:
app.directive('setClassWhenAtTop', function ($window) {
  var $win = angular.element($window); // wrap window object as jQuery object

  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var topClass = attrs.setClassWhenAtTop, // get CSS class from directive's attribute value
          offsetTop = element.offset().top; // get element's offset top relative to document

      $win.on('scroll', function (e) {
        if ($win.scrollTop() >= offsetTop) {
          element.addClass(topClass);
        } else {
          element.removeClass(topClass);
        }
      });
    }
  };
});

If you wanted to get a bit cheeky, you could even reduce your scroll handler to just one line:
$win.on('scroll', function (e) {
  element[($win.scrollTop() >= offsetTop) ? 'addClass' : 'removeClass'](topClass);
});

And the fix-to-top CSS class would just be something like this:
.fix-to-top {
  position: fixed;
  top: 0;
}

Here's a fiddle.

A: I started using MikeJ's great answer to get started, but quickly realized a few shortcomings:

*

*Didn't account for when content above the element changes dynamically after the directive is first parsed

*Content below the fixed element moved up the height of the element when it became fixed and was removed from the normal document flow

*If this element is being fixed below something else (like a top menu) you may have some trouble calculating the right spot; you need to fix it before the offset top is past where the $win.scrollTop() is, so that it doesn't disappear behind that menu and then get fixed after.

To fix these, I came up with a modified version:
function setClassWhenAtTop($window) {
    var $win = angular.element($window);

    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            var topClass = attrs.setClassWhenAtTop,
                topPadding = parseInt(attrs.paddingWhenAtTop, 10),
                parent = element.parent(),
                offsetTop;

            $win.on("scroll", function () {
                // dynamic page layout so have to recalculate every time;
                // take offset of parent because after the element gets fixed
                // it now has a different offset from the top
                offsetTop = parent.offset().top - topPadding;
                if ($win.scrollTop() >= offsetTop) {
                    element.addClass(topClass);
                    parent.height(element.height());
                } else {
                    element.removeClass(topClass);
                    parent.css("height", null);
                }
            });
        }
    };
}

This requires the element you are fixing to be wrapped in an empty parent that only contains the element to fix. This is to handle both knowing where the original offset of the element was (for putting it back into the document flow) and to have the height of the original element to keep the document flow as it was. In addition, pass in an attribute for paddingWhenAtTop to fix it sooner (or later if desired).
Usage in the HTML changes like so:

A: Here is my attempt to make it full angularjs :
JS
.directive('setClassWhenAtTop', ['$window', function($window) {
    var $win = angular.element($window); // wrap window object as jQuery object

    return {
        restrict: 'A',
        link: function (scope, element, attrs)
        {
            var topClass = attrs.setClassWhenAtTop, // get CSS class from directive's attribute value
                topPadding = parseInt(attrs.paddingWhenAtTop, 10),
                offsetTop = element.prop('offsetTop'); // get element's offset top relative to document

            $win.on('scroll', function (e) {
                if ($window.pageYOffset + topPadding >= offsetTop) {
                    element.addClass(topClass);
                } else {
                    element.removeClass(topClass);
                }
            });
        }
    };
}])

CSS
.fix-to-top {
    position: fixed;
    top: 55px;
    height: 50px;
    z-index: 999;
    width: 100%;
}

HTML

...

Main changes to skip jquery :
parent.offset().top => element.prop('offsetTop')
$win.scrollTop() => $window.pageYOffset

Tip of the day :
Would you please stop always giving angularjs title questions jquery answers ! Or at least indicate it clearly in your title or in your answer requirements ;-)