text:
Q: SolrCloud - How to resolve "Could not find collection configName" I am trying to start Solr in SolrCloud mode. I have created a new collection from collection1 and changed its name in file core.properties by setting the property name=logmail.
But when I start Solr, I am getting the following error
$ java -Dcollection.configName=logmail -DzkRun -Dnumshards=2 -DBootstrap_confdir=./solr/logmail/conf -jar start.jar

2165 [main] INFO  org.apache.solr.common.cloud.ZkStateReader  –
  Updating cluster state from ZooKeeper...  2179
  [OverseerStateUpdate-94955713964081152-127.0.1.1:8983_solr-n_0000000001]
  INFO  org.apache.solr.cloud.Overseer  – Starting to work on the main
  queue 2197 [main] INFO  org.apache.solr.core.CoresLocator  – Looking
  for core definitions underneath /home/rahul/Desktop/dev/solrcloud/solr
  2203 [main] INFO  org.apache.solr.core.CoresLocator  – Found core
  logmail in /home/rahul/Desktop/dev/solrcloud/solr/logmail/ 2204 [main]
  INFO  org.apache.solr.core.CoresLocator  – Found core collection1 in
  /home/rahul/Desktop/dev/solrcloud/solr/collection1/ 2204 [main] INFO
  org.apache.solr.core.CoresLocator  – Found 2 core definitions 2207
  [coreLoadExecutor-6-thread-1] INFO  org.apache.solr.cloud.ZkController
  – publishing core=logmail state=down collection=logmail 2207
  [coreLoadExecutor-6-thread-2] INFO  org.apache.solr.cloud.ZkController
  – publishing core=collection1 state=down collection=collection1 2208
  [coreLoadExecutor-6-thread-1] INFO  org.apache.solr.cloud.ZkController
  – numShards not found on descriptor - reading it from system property
  2208 [coreLoadExecutor-6-thread-2] INFO
  org.apache.solr.cloud.ZkController  – numShards not found on
  descriptor - reading it from system property 2214
  [coreLoadExecutor-6-thread-1] INFO  org.apache.solr.cloud.ZkController
  – look for our core node name 2214 [coreLoadExecutor-6-thread-1] INFO
  org.apache.solr.cloud.ZkController  – waiting to find shard id in
  clusterstate for logmail 2214 [zkCallback-2-thread-1] INFO
  org.apache.solr.cloud.DistributedQueue  – NodeChildrenChanged fired on
  path /overseer/queue state SyncConnected 2215
  [coreLoadExecutor-6-thread-1] INFO  org.apache.solr.cloud.ZkController
  – Check for collection zkNode:logmail 2222
  [coreLoadExecutor-6-thread-2] INFO  org.apache.solr.cloud.ZkController
  – look for our core node name 2222 [coreLoadExecutor-6-thread-1] INFO
  org.apache.solr.cloud.ZkController  – Creating collection in
  ZooKeeper:logmail 2222 [coreLoadExecutor-6-thread-2] INFO
  org.apache.solr.cloud.ZkController  – waiting to find shard id in
  clusterstate for collection1 2223 [coreLoadExecutor-6-thread-1] INFO
  org.apache.solr.cloud.ZkController  – Looking for collection
  configName 2223 [coreLoadExecutor-6-thread-2] INFO
  org.apache.solr.cloud.ZkController  – Check for collection
  zkNode:collection1 2224 [coreLoadExecutor-6-thread-2] INFO
  org.apache.solr.cloud.ZkController  – Creating collection in
  ZooKeeper:collection1 2224 [coreLoadExecutor-6-thread-2] INFO
  org.apache.solr.cloud.ZkController  – Looking for collection
  configName 2225 [coreLoadExecutor-6-thread-1] INFO
  org.apache.solr.cloud.ZkController  – Could not find collection
  configName - pausing for 3 seconds and trying again - try: 1 2226
  [coreLoadExecutor-6-thread-2] INFO  org.apache.solr.cloud.ZkController
  – Could not find collection configName - pausing for 3 seconds and
  trying again - try: 1 2226
  [OverseerStateUpdate-94955713964081152-127.0.1.1:8983_solr-n_0000000001]
  INFO  org.apache.solr.cloud.Overseer  – Update state numShards=null
  message={   "core":"logmail",   "roles":null,
  "base_url":"http://127.0.1.1:8983/solr",
  "node_name":"127.0.1.1:8983_solr",   "state":"down",   "shard":null,
  "collection":"logmail",   "operation":"state"} 2226
  [OverseerStateUpdate-94955713964081152-127.0.1.1:8983_solr-n_0000000001]
  INFO  org.apache.solr.cloud.Overseer  – node=core_node1 is already
  registered 2227
  [OverseerStateUpdate-94955713964081152-127.0.1.1:8983_solr-n_0000000001]
  INFO  org.apache.solr.cloud.Overseer  – shard=shard1 is already
  registered 2255 [zkCallback-2-thread-1] INFO
  org.apache.solr.common.cloud.ZkStateReader  – A cluster state change:
  WatchedEvent state:SyncConnected type:NodeDataChanged
  path:/clusterstate.json, has occurred - updating... (live nodes size:
  1) 2268
  [OverseerStateUpdate-94955713964081152-127.0.1.1:8983_solr-n_0000000001]
  INFO  org.apache.solr.cloud.Overseer  – Update state numShards=null
  message={   "core":"collection1",   "roles":null,
  "base_url":"http://127.0.1.1:8983/solr",
  "node_name":"127.0.1.1:8983_solr",   "state":"down",   "shard":null,
  "collection":"collection1",   "operation":"state"} 2268
  [OverseerStateUpdate-94955713964081152-127.0.1.1:8983_solr-n_0000000001]
  INFO  org.apache.solr.cloud.Overseer  – node=core_node1 is already
  registered 2269
  [OverseerStateUpdate-94955713964081152-127.0.1.1:8983_solr-n_0000000001]
  INFO  org.apache.solr.cloud.Overseer  – shard=shard1 is already
  registered 2288 [zkCallback-2-thread-1] INFO
  org.apache.solr.cloud.DistributedQueue  – NodeChildrenChanged fired on
  path /overseer/queue state SyncConnected 2318 [zkCallback-2-thread-1]
  INFO  org.apache.solr.common.cloud.ZkStateReader  – A cluster state
  change: WatchedEvent state:SyncConnected type:NodeDataChanged
  path:/clusterstate.json, has occurred - updating... (live nodes size:
  1) 5227 [coreLoadExecutor-6-thread-1] INFO
  org.apache.solr.cloud.ZkController  – Could not find collection
  configName - pausing for 3 seconds and trying again - try: 2 5228
  [coreLoadExecutor-6-thread-2] INFO  org.apache.solr.cloud.ZkController
  – Could not find collection configName - pausing for 3 seconds and
  trying again - try: 2 8229 [coreLoadExecutor-6-thread-1] INFO
  org.apache.solr.cloud.ZkController  – Could not find collection
  configName - pausing for 3 seconds and trying again - try: 3 8229
  [coreLoadExecutor-6-thread-2] INFO  org.apache.solr.cloud.ZkController
  – Could not find collection configName - pausing for 3 seconds and
  trying again - try: 3 11232 [coreLoadExecutor-6-thread-1] INFO
  org.apache.solr.cloud.ZkController  – Could not find collection
  configName - pausing for 3 seconds and trying again - try: 4 11232
  [coreLoadExecutor-6-thread-2] INFO  org.apache.solr.cloud.ZkController
  – Could not find collection configName - pausing for 3 seconds and
  trying again - try: 4 14237 [coreLoadExecutor-6-thread-1] INFO
  org.apache.solr.cloud.ZkController  – Could not find collection
  configName - pausing for 3 seconds and trying again - try: 5 14237
  [coreLoadExecutor-6-thread-2] INFO  org.apache.solr.cloud.ZkController
  – Could not find collection configName - pausing for 3 seconds and
  trying again - try: 5 17237 [coreLoadExecutor-6-thread-1] ERROR
  org.apache.solr.cloud.ZkController  – Could not find configName for
  collection logmail 17238 [coreLoadExecutor-6-thread-2] ERROR
  org.apache.solr.cloud.ZkController  – Could not find configName for
  collection collection1 17240 [coreLoadExecutor-6-thread-1] ERROR
  org.apache.solr.core.CoreContainer  – Error creating core [logmail]:
  Could not find configName for collection logmail found:null
  org.apache.solr.common.cloud.ZooKeeperException: Could not find
  configName for collection logmail found:null

A: It looks like there may be a discrepancy between what Solr has on the filesystem for collections based on your commands and what is in zookeeper.
These are hard to fix; if possible I would recommend to delete your configuration files out of zookeeper and reload them.

A: You have a typo in your command. This should do the trick:
$ java -Dcollection.configName=logmail -DzkRun -Dnumshards=2 -Dbootstrap_confdir=./solr/logmail/conf -jar start.jar


text:
Q: CancellationToken doesn't propagate I am trying to create a function that would trigger on certain event after N seconds. If same event would appear again previously scheduled execution should be canceled and new one is supposed to be scheduled.
I tried to model this behavior through following code:
class Trend<T>
{
    private CancellationTokenSource cancellationToken =
        new CancellationTokenSource();

    public void AddObservation(T observation)
    {
        // I don't really care about T.
        //
        Func<CancellationToken, T, Task> action =
            async (CancellationToken token, T obs) =>
        {
            try
            {
                await Task.Delay(TimeSpan.FromSeconds(5), token);
                if (!token.IsCancellationRequested)
                {
                    Console.WriteLine($"{DateTime.UtcNow} Task executed {obs}");
                }
            }
            catch (TaskCanceledException)
            {
            }
        };

        // cancel previos execution, if any.
        cancellationToken.Cancel();

        // create new token
        cancellationToken = new CancellationTokenSource();

        Task.Run(async () => await action(cancellationToken.Token, observation));
    }
}

Simple test:
static void Main(string[] args)
{
    Trend<int> trend = new Trend<int>();

    // Schedule 10K tasks
    for (int i = 0; i < 10; i++)
    {
        trend.AddObservation(i);
    }

    // Only the last one should execute.
    Thread.Sleep(TimeSpan.FromSeconds(10000));
}

My expectation would be to have only the last observation executed upon and all the others canceled. In reality not a single task got canceled.
Now, what worked was to create a list of cancellationtokens and keep a reference to each one of them:
private List<CancellationTokenSource> cancellationTokens =
    new List<CancellationTokenSource>();
...
    foreach (var ct in cancellationTokens)
    {
        ct.Cancel();
    }

    CancellationTokenSource c = new CancellationTokenSource();
    cancellationTokens.Add(c);

    Task.Run(async () => await action(c.Token, observation));

Rough assumption is that garbage collector is cleaning CancellationTokenSource and thus nullifying the effect of Cancel call.
I don't know much about async internals so help would be appriciated.

A: Because all tasks are using same CancellationToken.
You can check by changing your code to this:
(This code is just for testing. Answer is below of this Code)
class Trend<T>
    {
        private CancellationTokenSource cancellationToken = new CancellationTokenSource();
        public void AddObservation(T observation)
        {
            // I don't really care about T.
            //
            Func<CancellationToken, T, Task> action = async (CancellationToken token, T obs) =>
            {
                try
                {
                    await Task.Delay(TimeSpan.FromSeconds(5), token);
                    if (!token.IsCancellationRequested)
                    {
                        Console.WriteLine($"{DateTime.UtcNow} Task executed {obs} TOKEN IS {token.GetHashCode()}" );
                    }
                }
                catch (TaskCanceledException)
                {
                }
            };

            // cancel previos execution, if any.
            cancellationToken.Cancel();

            // create new token
            cancellationToken = new CancellationTokenSource();
            Console.WriteLine($"TOKEN CREATED {cancellationToken.Token.GetHashCode()}");

            Task.Run(async () => await action(cancellationToken.Token, observation));
        }

    }

But why?
when you run Task.Run(async () => await action(cancellationToken.Token, observation)); you are scheduling a Task that will start another task which is action here.
so before all task get start and call action, cancellationToken refrence to the last created one so all Tasks will call action by last created CancellationToken.
Solution
Just simply call action(cancellationToken.Token, observation); instead of Task.Run(...); so your action will call with current created CancellationToken.
Solution Complete Code
class Trend<T>
    {
        private CancellationTokenSource cancellationToken = new CancellationTokenSource();
    public void AddObservation(T observation)
    {
        // I don't really care about T.
        //
        Func<CancellationToken, T, Task> action = async (CancellationToken token, T obs) =>
        {
            try
            {
                await Task.Delay(TimeSpan.FromSeconds(5), token);
                if (!token.IsCancellationRequested)
                {
                    Console.WriteLine($"{DateTime.UtcNow} Task executed {obs}");
                }
            }
            catch (TaskCanceledException)
            {
            }
        };

        // cancel previos execution, if any.
        cancellationToken.Cancel();

        // create new token
        cancellationToken = new CancellationTokenSource();

        action(cancellationToken.Token, observation);
    }
}

A: Here is my suggestion. This Trend implementation accepts a synchronous or asynchronous action, and can be rescheduled multiple times. It exploits the
existing functionality of the CancellationTokenSource class (the CancelAfter method).
class Trend : IDisposable
{
    private readonly CancellationTokenSource _cts = new();
    private readonly Task _task;

    public Task Completion => _task;

    public Trend(Action action) // Synchronous delegate
    {
        _task = Task.Delay(Timeout.Infinite, _cts.Token).ContinueWith(
            _ => action(), TaskScheduler.Default);
    }

    public Trend(Func<Task> action) // Asynchronous delegate
    {
        _task = Task.Delay(Timeout.Infinite, _cts.Token).ContinueWith(
            _ => action(), TaskScheduler.Default).Unwrap();
    }

    /// <summary>
    /// Returns true if the action is scheduled successfully for future execution.
    /// Returns false if the action is already running or it has completed.
    /// </summary>
    public bool StartAfter(TimeSpan delay)
    {
        if (_cts.IsCancellationRequested) return false;
        _cts.CancelAfter(delay);
        return true;
    }

    public void Dispose() => _cts.Dispose();
}

Usage example:
var trend = new Trend(() =>
{
    Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff} Action!");
});
for (int i = 0; i < 10; i++)
{
    Thread.Sleep(100);
    Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff} Scheduling trend...");
    trend.StartAfter(TimeSpan.FromMilliseconds(500));
}
await trend.Completion;
Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff} Finished");

Output:
04:39:06.541 Scheduling trend...
04:39:06.669 Scheduling trend...
04:39:06.771 Scheduling trend...
04:39:06.872 Scheduling trend...
04:39:06.990 Scheduling trend...
04:39:07.104 Scheduling trend...
04:39:07.205 Scheduling trend...
04:39:07.306 Scheduling trend...
04:39:07.408 Scheduling trend...
04:39:07.512 Scheduling trend...
04:39:08.027 Action!
04:39:08.027 Finished

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why Cygwin ssh service return (rs = 1) when running executable in Windows i have installed cygwin ssh service on windows server and configured user details and i am trying to run executables that i compiled using sshpass from Linux server and i am always getting return status = 1 .
i have made sure that my executable return 0 , but for some reason its not working .
here is the example i am trying to run
sshpass -p 'herod11' ssh herod@pcie191 'cmd /c \\\\10.128.0.102\\fwshared_gwork\\ibrahims\\git\\svx\\pci_verification\\win_64\\build\\\pcie_call_crspace_function --mst_dev mt4117_pciconf0 --tags  --function_name GetPciPort '

echo $? , return 1 .


text:
Q: Django on docker; Staticfiles disappearing I am trying to deploy my django project using docker nginx and gunicorn.
My Issue is that the staticfiles I use for my project are missing from the container.
when in the project:
ls staticfiles/
css  disconnected.html  images  lib  nothing.css

after going into the container with docker exec -it foo_web_1 /bin/sh
ls staticfiles/
admin

my docker-compose file:
version: '3.7'

services:
  web:
    build:
      context: ./foo-app
      dockerfile: Dockerfile.prod
    command: gunicorn foo-app.wsgi:application --bind 0.0.0.0:8000
    volumes:
      - static_volume:/home/foo-app/web/staticfiles
      - media_volume:/home/foo-app/web/mediafiles
    expose:
      - 8000
    env_file:
      - ./.env.prod
  nginx:
    build: ./nginx
    volumes:
      - static_volume:/home/foo-app/web/staticfiles
      - media_volume:/home/foo-app/web/mediafiles
    ports:
      - 2375:80
    depends_on:
      - web
volumes:
  postgres_data:
  static_volume:
  media_volume:

the nginx.conf file:
upstream foo-app {
    server web:8000;
}

server {

    listen 80;

    location / {
        proxy_pass http://foo-app;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }

    location /staticfiles/ {
        alias /home/foo-app/web/staticfiles/;
    }

    location /mediafiles/ {
        alias /home/foo-app/web/mediafiles/;
    }

}

the part of the settings.py that relates to staticfiles:
STATIC_URL = "/staticfiles/"
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "staticfiles")
]

Inside my dockerfile I define the following:
ENV HOME=/home/foo-app
ENV APP_HOME=/home/foo-app/web
RUN mkdir $APP_HOME
WORKDIR $APP_HOME

and later I simply copy the entire project in using
COPY . $APP_HOME

All other file show up perfectly fine, and I have tried remove and rebuild the entire project to avoid artifacts to no avail.

A: The Problem got resolved by separating STATIC_ROOT from the location of my staticfiles and then adding python manage.py collectstatic --no-input --clear to my startupscript.


text:
Q: Nested nginx reverse proxies using Docker I have linux VPS, with domain e.g. "example.com". There is multiple services served on the domain, so there should be some API gateway.
My configuration is:

*

*native nginx reverse proxy running on VPS, routing "example.com" domain inside example-nginx API gateway (container #1)

*example-nginx API gateway, e.g
/ => Vue.js project (container #2)
/api => PHP service (container #3)
/another => PHP service (container #4)

*and each container (containers #2, #3, #4) is running it's own nginx web server to serve it's contents (bcs. this is how the docker image is built so it is able to run independently on other services)

But this is 3 nested nginx servers so I am wondering, if this can be considered best practice. But also I have no idea if there is some better way, because as described, I need all the layers.
I can probably merge native nginx with api gateway, but if I do this, I will have to manually configure api gateway on each host where the app will be deployed. So this is probably not an option.


text:
Q: How to move the text marker inside a input field. (Javascript) Text marker might be the wrong word, I mean the stick/pipe (|) that follows the text you writes and let the user know where the characters will be placed inside a text box
Basically I want to know how to get the text marker and how to move it.
I'm looking for a call like this document.getPipe;
To make it more clear I show a picture on a "text marker".
Image below is on the thing I want to get/call and move inside a input field

A: I found the correct word which is insertion point.
And to move the insertion point you can use this
var input = document.getElementById("inpuName");
var pointYouWantToMoveTo = 1;
input.setSelectionRange(pointYouWantToMoveTo, pointYouWantToMoveTo);

This code will move the insertion point to the second character in the input field.
if the text inside the input field is: hello world| it will move here
h|ello world.


text:
Q: Vim as the default editor I'm on Windows XP and I just installed GVim 7.3. How do I make the default editor? How can I make it run using the command prompt
e.g.
c:\Windows>gvim boot.ini

open this file in gvim.
Thanks a lot

A: Add Gvim to your PATH variable
To be able to call Gvim from the command line, you have to add the installation directory of Vim to your PATH variable. To do that, right click on My Computer on the desktop (or in Explorer) → Properties → Advanced Tab → Click on Button Environment Variables.
In the Dialog, go to the User Variables field and search if there is already a PATH variable. If there is a PATH Variable, select it, click Edit and change it as follows:
%PATH%;C:/Program Files/Vim/Vim73

(or whatever the installation directory of Gvim is).
If there is no PATH variable set, create a new one with the content written above.
Confirm everything with OK, then open a new command window (important!), navigate to the desired directory and type
gvim somefile.txt

This should bring up your favourite editor.

Set Gvim as default editor for a certain file type
Adding Gvim to your PATH doesn't make Gvim the default editor for a certain file type. This can be achieved the following way:

*

*In Explorer, right click on any file and select Open With → Choose Program

*in the upcoming window, select Vi improved - A Text Editor or browse for gvim.exe if the entry is not already there

*select the Always use the selected program ... checkbox and click OK

*from now on, every time you double-click the file, it will be opened with Gvim

The easiest way
If you install Gvim, be sure to check the Add to context menu option. If you did that, you can right click on any file in the Windows Explorer and select Edit with Vim.

A: Right click the any file you want to open -> select Open or Open With ->check always open with the following editor.

A: *

*After installing vim the "Edit with vim..." menu item appears in the context menu (RMB click on any file to check). Thus you can edit any file (not only text file) with just selecting this menu item

*Add gvim to the PATH variable and you can run it right as you want:
c:\Windows>gvim boot.ini


text:
Q: Can memcached make full use of multi-core? Is memcached capable of making full use of multi-core? Or is there any way tuning this?

A: memcached is multi-threaded by default and has no problem saturating many cores.  It's a bit harder to saturate all cores on more massively parallel boxes (e.g. a 256-core CMT box) just because it gets harder to get the data in and out of the network.
If you find areas where some sort of contention is preventing you from saturating cores, file a bug or start a discussion.

A: Based on a this research by Intel, Memcached v.1.6 beta cannot scale well on a multicore system. Their experiments show that as core counts increase from 1 to 8, maximum throughput (with a median RTT < 1ms SLA) only doubles.

A: memcached has "-t" option:
       -t <threads>
          Number of threads to use to process incoming requests. This option is only meaningful
          if memcached was compiled with thread support enabled. It is typically not useful  to
          set  this higher than the number of CPU cores on the memcached server. The default is
          4.

so, I believe it can use all your CPU cores, of course if it was compiled with corresponding option.

A: CAREFUL.  This terminology is quite confusing.  Memcached man page says -t option is only good up to the number of cores.  However, this is odd because threads and processes are VERY different.  Threads have NOTHING to do with the number of cores.  Processes can definitely run on more than one cor, while threads cannot (unless they call to an OS routine, then they can thread switch and pack in more than 100% cpu usage).  Threads share memory and just depend on an instruction pointer to differentiate who is who.  Processes share nothing unless it is explicitly declared as shared ahead of time, and sharing occurs via the OS.
Overall, I want MORE CLARITY from the Memcached people about whether their app is multiprocessing or multithreaded and thus if it can use more than 100% of cpu.


text:
Q: Nodejs: How to get Dotenv configuration done first I'm getting an error when initialising Postmark 'Invalid api token'. I'm getting this error because my own environment variables aren't loaded yet.
In index.js I've got a start function. The first thing is configuring dotenv with the correct environment file (development/production/test).
The sendEmail file is loaded before the configuration. I can move the creation of the client inside the sendEmailConfirmationMail function but than I will have the initialize the client for every mail function.
Any other solution?
index.js
const __dirname = path.resolve();

// Load env vars
dotenv.config({
   path: path.join(__dirname, `./config/.env.${process.env.NODE_ENV}`)
});

const start = async () => {
    try {
        // Connect to database
        await connectDB(process.env.DATABASE_URL);

        // Create app
        const app = express();

        // Body parser
        app.use(express.json())
        app.use(express.urlencoded({ extended: true }));

        // Cookie parser
        app.use(cookieParser());

        // Mount routes
        app.use(`/${process.env.API_VERSION}`, authRoutes);

        // Error handler
        app.use(errorHandler);

        // Not found handler
        app.use(notFoundHandler);

        // Start server
        const server = app.listen(process.env.PORT, () => {
            console.log(`Server running in ${process.env.NODE_ENV} mode on http://${process.env.HOST}:${process.env.PORT}/${process.env.API_VERSION}`)
        });

        // Handle unhandled promise rejections
        process.on('unhandledRejection', (reason, promise) => {
            console.log('UNHANDLED REJECTION!  Shutting down...');
            console.log('Unhandled rejection at:', promise, 'reason:', reason);

            // Close server and exit process
            server.close(() => process.exit(1));
        });

        process.on('uncaughtException', err => {
            console.log('UNCAUGHT EXCEPTION!  Shutting down...');
            console.log(err.name, err.message);

            // Close server and exit process
            server.close(() => process.exit(1));
        });
    } catch(error) {
        console.log('Server crashed');
        console.log(error);
    }
}

start();

package.json
"scripts": {
    "dev": "set NODE_ENV=production && nodemon --experimental-specifier-resolution=node index.js"
}

utils/sendEmail.js
import postmark from 'postmark';

const client = new postmark.ServerClient(process.env.POSTMARK_API_TOKEN);

export const sendEmailConfirmationMail = async (email, first_name, language, confirmation_token) => {
    return client.sendEmailWithTemplate({
        To: email,
        From: process.env.MAIL_FROM,
        TemplateId: language === 'fr' ? 19699565 : 19699566,
        TemplateModel: {
            "first_name": first_name,
            "url": `${process.env.FRONTEND_URL}/confirm-email?confirmation_token=${confirmation_token}&email=${email}&lang=${language}`
        }
    });
}


text:
Q: WinRT binding, UI does not Update I have a view model that loads some data. While loading a DependencyProperty is set to true, later false again. I've often done this in WPF, but with modern Apps it don't work. :(
The view that is bound to the model should shows if the model is still loading. It just shows the value when the Page is loaded, but doesn't updates the view after the value changes.
I've written a little example that uses SharedProjects for Phone, Modern App and WPF. (BindingExample)
For test purpose it just switches between true and false.
XAML
<Page
    x:Class="App2.BlankPage1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App2"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid >
        <TextBlock Text="{Binding Loading, Mode=OneWay}" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="30" Width="100" Height="100"/>
    </Grid>
</Page>

The Constructor of the Page
    public BlankPage1()
    {
        var v = new Viewmodle();
        this.InitializeComponent();
        this.DataContext = v;

        v.Test();
    }

The Viewmodle:
public class Viewmodle : DependencyObject
{

    public bool Loading
    {
        get { return (bool)GetValue(LoadingProperty); }
        set { SetValue(LoadingProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Loading.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty LoadingProperty =
        DependencyProperty.Register("Loading", typeof(bool), typeof(Viewmodle), new PropertyMetadata(false));

    public async void Test()
    {
        while (true)
        {
            await System.Threading.Tasks.Task.Delay(1000);
            this.Loading = true;
            await System.Threading.Tasks.Task.Delay(1000);
            this.Loading = false;
        }
    }

}

A: You probably want INotifyPropertyChanged instead of DependencyObject. The way you're binding right now is actually just a plain property binding, its not really using the DependencyProperty. This can be evidenced by removing the CLR property and only having the DependencyProperty registration. You will see the binding has failed at runtime. DependencyProperty binding is seemingly only useful when the source has originated in xaml. So instead of setting your view model in code the way you have you could have done something like this
<Grid.Resources>
   <local:Viewmodle x:Name="viewModel"/>
</Grid.Resources>
<TextBlock Text="{Binding ElementName=viewModel, Path=Loading}"/>

then you could call viewModel.Test() in your constructor to start your test using the xaml made view model


text:
Q: Gradle incremental build for my task: what's wrong? I'm struggling with Gradle 3.3 in Android Studio 2.3. I have assets generating task for which I specify inputs.dir and outputs.dir in cfg section:
task compileAssets{

inputs.dir 'src/main/assets_src'
outputs.dir 'src/main/assets'

def proj_src = 'src/main/'
def abs_proj_src = project.projectDir.getAbsolutePath() + '/' + 'src/main/'
abs_proj_src = abs_proj_src.replace('\\','/')

doLast {
    delete(proj_src + 'assets')
    mkdir(proj_src + 'assets')

    copy
        {
            from proj_src + 'assets_src'
            include 'xml/**'
            include 'fonts/**'
            include 'shaders/**'
            into proj_src + 'assets'
        }

    javaexec{
        main = '-jar'
        args = [
            "../../utils/encoder.jar",
            abs_proj_src + 'assets_src/bin/levels',
            abs_proj_src + 'assets/bin/levels',
            '-rewrite'
        ]
    }
}

I expect Gradle will check contents of input folder changes and if some files were added, removed or changed it will allow to execute task, else it will print 'UP-TO-DATE'. But it is so only when only delete(...) and mkdir(...). Otherwise it is executed every time. Maybe I understand the term 'incremental build' in a wrong way? Or maybe there is task size limit, or javaexec or copy are forbidden in incremental build?
PS. I tried to launch task with make command and directly from AS Gradle projects pane.

A: It was my own error. Below is defined cleanAssets task, where I forgot to add << or doLast:
task cleanAssets{
        delete(proj_src + 'assets')
        mkdir(proj_src + 'assets')
}

So every build in configure phase assets folder was deleted. Funny!


text:
Q: Access is denied creating text file in cmd & weird "if exist" problem For a batch file project of mine, I had to create two text files if they didn't already exist. For some reason the 'if exist "example.txt"' didn't work. What I mean by that is:
if not exist "example.txt" goto :label

wouldn't go to 'label' when the file did not exist. So, i presumed the file must be existing already (from my previous tests). The thing is that
if exist "example.txt" goto :label2

always went to 'label2', even though later in the script cmd could not find the file, and the folder is empty except the batch script (the file didn't exist). I decided I'd test the label for if the file didn't exist anyway. when I used the break> command to create the text file, it came back as access is denied. It did the same thing with the following code which i used to enter information:
>> "example.txt"  echo 0

and with
del/f "example.txt"

I am a full administrator on my computer, the code I use works in other batch files I have created. I have tried running cmd in administrator (same outcome). Specifying the directory works no better in this case than using current directory. I'm wondering what is the cause of this is.
Anyway, here is the full batch script.
@echo off
title Folder Safe
color e8
if exist "infocj.txt" goto start
goto MAKESOURCE

:MAKESOURCE
rem notes: access is denied. this means that createproc doesn't work (createproc relies on makesource).
break>"infocj.txt"
attrib +s +h +r  "infocj.txt"
break>"setupcj.txt"
>> "setupcj.txt"  echo 0
attrib +s +h +r  "setupcj.txt"
goto START

:START
echo what safe do you want to unlock (number only)
set/p "loc=>"
if exist %loc% goto LOCK
if exist Locked%loc% goto UNLOCK
echo there is no safe hashing to %loc%. do you wish to create a new safe? (y/n)
set/p "cho=>"
if %cho%==y goto createpass
exit

:LOCK
cls
For /f "tokens=%loc% delims=;" %%i in (infocj.txt ) do set pass=%%i
echo enter password to lock Safe %loc%
set/p "qaz=>"
if not %qaz%==%pass% goto END
ren %loc% Locked%loc%
attrib/d  +h +s +r Locked%loc%
exit

:UNLOCK
cls
For /f "tokens=%loc% delims=;" %%i in (infocj.txt ) do set pass=%%i
echo enter password to unlock Safe %loc%:
set/p "qaz=>"
if not %qaz%==%pass% goto END
ren Locked%loc% %loc%
attrib/d  -s -h -r %loc%
exit

:createpass
echo enter password:
set/p "pass=>"
cls
echo confirm password:
set/p "npass=>"
cls
if not %pass%==%npass% (
 echo the passwords you entered are not matching
 timeout /t 2 /nobreak > NUL
 goto createpass
 )
goto createproc

:createproc
rem this stuff is screwed because the stuff under makesource is not working properly, but even if I do all that manually, a lot of this still returns access is denied
for /f "tokens=* usebackq" %%a in ("infocj.txt") do set inf=%%a
set inf=%inf%%pass%;
attrib -s -h -r  "infocj.txt"
del/f "infocj.txt"
break>"infocj.txt"
>> "infocj.txt"  echo %inf%
attrib +s +h +r  "infocj.txt"
for /f "delims=" %%b in ("setupcj.txt") do set stp=%%b+1
md %stp%
attrib -s -h -r  "setupcj.txt"
del/f "setupcj.txt"
break>"setupcj.txt"
>> "setupcj.txt"  echo %stp%
attrib +s +h +r  "setupcj.txt"
echo your locker hashes to the number %stp%
pause
exit

Thanks in advance for your answers. This one's got me truly stumped.


text:
Q: why is my query returning the right max value but not the corresponding name that goes with that average value? I have a query that is averaging the ratings of a restaurant (from a separate review table) and I'm trying to get the max value out of that. Here is what a query getting the average rating based on joining a restaurant to its reviews gets:
1   Panera  4.0000
2   BurgerKing  4.5000
3   ChuckECheese    2.6667
4   Cafe Gratitude  2.0000

However, I'm trying to get just the restaurant with the highest review and its rating and I'm using this query:
select BusinessName, MAX(AvgReview) as Rating from
(select BusinessName, avg(ReviewRating) as AvgReview
from Business
join Review
on Review.BusinessID = Business.BusinessID
group by Business.BusinessID) AvgRatingsTable;

But that is resulting in:
Panera  4.5000

Where it gets the maximum rating correctly but not the restaurant name. I've tried doing adding "where AvgRating = Max(AvgRating)" but it says invalid use of group function.
Additionally, when I try to find the restaurant with the minimum review using:
select AvgRatingsTable.BusinessName, MIN(AvgRatingsTable.AvgReview) as Rating from
(select BusinessName, avg(ReviewRating) as AvgReview
from Business
join Review
on Review.BusinessID = Business.BusinessID
group by Business.BusinessName) AvgRatingsTable;

I receive
BurgerKing  2.0000

So doing groupby BusinessName or BusinessID doesn't really help; it just grabs the first name.
What am I doing wrong here? How do I tell it I want the name that corresponds to that maximum/minimum average?
EDIT EDIT EDIT EDIT EDIT
If I do this, with a groupby on the outer query
select AvgRatingsTable.BusinessName, MIN(AvgRatingsTable.AvgReview) as Rating from
(select BusinessName, avg(ReviewRating) as AvgReview
from Business
join Review
on Review.BusinessID = Business.BusinessID
group by Business.BusinessName) AvgRatingsTable
group by BusinessName;

It just returns all of the tables instead of at least giving me the minimum rating. Same if I do groupby BusinessName, AvgReview.


text:
Q: Shortest common SuperSequence The problem is that given 2 strings X and Y , we need to find length of the shortest sequence Z such that both the strings occur as sub sequence in Z. Now, I get the intuition that length = |X| + |Y| -|LCS(X,Y)|. But how do we prove it ?
Ex: X = AGGTAB , Y = GXTXAYB , then Z = AGXGTXAYB and |Z| = 9 . LCS(X,Y) = GTAB
Reference : Link 1 Link 2

A: First, looking at the second link you send, it is possible to create a super sequence which is of size |X| + |Y| - |LCS(X,Y)|:

For two input sequences, an scs can be formed from a longest common subsequence (lcs) easily...

So now all that remains is to prove that it is actually the shortest common supersequence. Assuming the contrary, suppose that there is a shortest common supersequence such that its length is |X| + |Y| - |LCS(X,Y)| - 1 == |X| + |Y| - (|LCS(X,Y)| + 1). But in this string, you have X as a subsequence, and Y as a subsequence.  That means that they intersect in |LCS(X,Y)| + 1 places judging by the size of the string. That is there is a LCS of size |LCS(X,Y)| + 1, a contradiction to the definition of the LCS!
Hence, the size is exactly |X| + |Y| - |LCS(X,Y)|. q.e.d

A: Since you only care about the counts of the letters, you can sort all the sequences (X, Y, Z and LCS(X,Y) ).  This is because sorting sequences (after figuring out minimal contaning one and the LCS) will keep the counts of the letters the same.
If you are considering sorted sequences, you only need to consider sequences formed from 1 letter.  This is because the count of each letter in each sequence is independent of the count of all other letters in each sequence.
Now if you consider sequences consisting of only one letter, then it should be obvious that the minimal sequence which contains both X and Y as a subsequence, will be either X or Y while LCS(X,Y) will be the other one.  So (adapting notation "MCS" for minimal containing sequence), |MCS(X,Y)| + |LCS(X,Y)| = |X| + |Y|.

A: Let  be string 1 and  be string 2.
Let S be any shortest super sequence which consist of both X and Y as sequences. Let's try to create such a sequence.
Clearly , X exists as a sequence in S. Hence, initially S can be shown as :

Note:  '...' means that place can be empty or can be used to place characters of Y into this to make it shortest super sequence consisting of both X and Y.
Now, this |S| has to be minimum. We need to inject only minimum characters from Y into this S to make it shortest super sequence consisting of both X and Y. Also, note the condition is that Y needs to appear as a sub sequence and not substring. Hence, if I find any sequence of characters of Y which also occur in X, then those characters of Y need not be injected.
Hence, for |S| to be minimum , we shown that minimum characters of Y need to be injected so that Y occurs as a sequence. For this, we find such longest sequence of X which also occur in Y which in other words = LCS(X,Y).
|S| = |X| + ( |Y| - |LCS(X,Y)| ) = |X| +|Y| - |LCS(X,Y)|
Now, multiple LCS(X,Y) exists. Take any and construct the sequence.


text:
Q: How to use is_active_widget? This is the manual page and this is the code.
But I'm still struggling to understand how to use this function. Perhaps I am using it right, but something I can't think of is wrong. But more surely, I need to know what this means:

*

*callback - I assumed this was the name of the Widget class. Am I right?

*widget id, what is this?

*id base, what is it?

*Whether to check in wp_inactive_widgets. What is wp_inactive_widgets?
I really feel like the manual isn't explaining these things.
Here's something that I put together which does not work:
function cbs_register_widgets() {
    register_widget( 'cbs_map_widget' );
}

add_action( 'widgets_init', 'cbs_register_widgets' );

function cbs_enqueue_resources() {

    if ( is_active_widget( 'cbs_map_widget' ) ) {
        wp_enqueue_script( 'fancybox-js', plugins_url( '/fancybox/jquery.fancybox-1.3.4.pack.js', __FILE__), array( 'jquery' ), '1.3.4' );
        wp_enqueue_style( 'fancybox-css', plugins_url( '/fancybox/jquery.fancybox-1.3.4.js', __FILE__ ), '', '1.3.4' );
    }

    wp_enqueue_script( 'cbs-widgets-js', plugins_url( '/js/cbs-widgets.js', __FILE__ ), array( 'jquery' ) );
    wp_enqueue_style( 'cbs-widgets-css', plugins_url( '/css/style.css', __FILE__ ) );

}

add_action( 'template_redirect', 'cbs_enqueue_resources' );

The enqueueing in itself works, it is the is_active_widget that doesn't work. The widget itself works too, and displays correctly. Just the fancybox js that's missing.
Here's my implementation of one of the answers I got below, it does not work either:
class cbs_map_widget extends WP_Widget
{
    function cbs_map_widget()
    {
        $ops = array('classname' => 'cbs-map-widget', 'description' => 'Visar en karta över Chalmers område där lokaler som används av Sällskapet har markerats.');

        $this->WP_Widget('cbs-map-widget', 'CBS kartwidget', $ops);
    }

    function widget($args, $instance)
    {
        extract($args);

        echo $before_widget;

        echo '
text
';
        echo '';

        echo $after_widget;

        add_action('wp_enqueue_scripts', array(&$this, 'js'));
    }

    function js()
    {
        if ( is_active_widget(false, false, $this->id_base, true) ) {
            wp_enqueue_script( 'fancybox-js', plugins_url( '/fancybox/jquery.fancybox-1.3.4.pack.js', __FILE__), array( 'jquery' ), '1.3.4' );
            wp_enqueue_style( 'fancybox-css', plugins_url( '/fancybox/jquery.fancybox-1.3.4.js', __FILE__ ), '', '1.3.4' );
        }
    }

}

A: You should make the check inside the widget class, unless you don't have a choice. The example in the codex is pretty much what you're looking for:
class cbs_map_widget extends WP_Widget{

  function cbs_map_widget(){
    $this->WP_Widget('cbsmaps', __('Widget Name'), array('classname' => 'cbsmaps', 'description' => __('whatever')));
    ...
    add_action('wp_enqueue_scripts', array(&$this, 'js'));
  }

  function js(){

    if ( is_active_widget(false, false, $this->id_base, true) ) {
       // enqueue your scripts;
    }

  }

  ...

}

The $widget_id parameter is useful when you need to include your scripts only for a specific widget instance. For example when you have two cbs_map_widget widgets and want to include custom javascript for each of them.
The $callback argument is useful when you need to do the check outside the widget class (like you did above), but try to avoid it if you can do your check inside the class.
The other arguments are pretty much self explanatory (id_base is basically a "widget class indentifier", and the $skip_inactive is whether to check inactive widgets as well - should be true because I don't think you want to do that)...

Edit: How to find the $widget_id (A widget instance ID)
Again, you don't need this unless you specifically want to check if a certain widget instance is active. Personally I use this method because I can access the instance options too:
 ...
 function js(){

    // we need to process all instances because this function gets to run only once
    $widget_settings = get_option($this->option_name);

    foreach((array)$widget_settings as $instance => $options){

      // identify instance
      $id = "{$this->id_base}-{$instance}";

      // check if it's our instance
      if(!is_active_widget(false, $id, $this->id_base)) continue; // not active

      // instance is active
      // access the widget instance options here, you may need them to do your checks
      if($options['yourwidgetoption']) {
         // do stuff
      }
    }

 }
 ...

A: I was having the same problem, and I didn't find a good explanation about how the function works, because it seemed not to be working (always returns false in my case).
Looking at the source code, the function checks for two things basically, it checks if the $callbak matches, and it checks if the $id_base matches, if one of those matches, then it checks if the $widget_id matches. So the param $id_base must be filled to get it works with the $widget_id.
Here is my example code:
$id_base = _get_widget_id_base($widget_id);
if(is_active_widget(false, $widget_id, $id_base)){
    // Your code here ...
} else {
    // Else code here ...
}


text:
Q: Change value of each item of string inside the list inside the list Let's say I have a class Dad which has list of kids:
public class Dad
{
    public List<Kid> kids = new List<Kid>();;
}

Each of those kids has a toy:
public class Kid
{
    public List<string> Toys = new List<string>();
}

and as a sample I have collection of dads:
Dad d1 = new Dad();
Kid k1 = new Kid();
k1.Toys.Add("toy1");
k1.Toys.Add("toy2");
d1.Kids.Add(k1);
List<Dad> dads = new List<Dad> { d1 };

I am trying to understand how to perform LINQ of List of Dads to change each kid's toy name to upper case.
Something like:
var dadsWithKidsWithChangeToysName = dads.Select(dad => dad.Kids.Select(kid => kid.Toys.ForEach(toy => toy.ToUpper())));

A: LINQ is for query, It is not for modification. You shouldn't use it for modification. Instead use a simple iteration (foreach/for) etc.
You can use LINQ to create a new List of Dad based on your existing list like:
var modifiedDads = dads.Select(d => new Dad()
{
    Kids = d.Kids.Select
        (
            k => new Kid()
            {
                Toys = k.Toys.Select(t => t != null ? t.ToUpper() : t).ToList()
            }
        ).ToList()
}).ToList();

A: If your classes have a constructor accepting an IEnumerable, you could get it like so :
    public class Dad
    {
        public List<Kid> kids = new List<Kid>();

        public Dad(IEnumerable<Kid> kids)
        {
            this.kids = kids.ToList();
        }
    }
    public class Kid
    {
        public List<string> Toys = new List<string>();

        public Kid(IEnumerable<string> toys)
        {
            Toys = toys.ToList();
        }
    }

    var dads = new List<Dad> {
        new Dad(new [] { new Kid(new [] { "a", "b" }) }),
        new Dad(new [] { new Kid(new [] { "c", "d" }) }),
    };

    var dadsWithKidsWithChangeToysName = dads.Select(d => new Dad(d.kids.Select(k => new Kid(k.Toys.Select(t => t.ToUpper())))));


text:
Q: Can't convert _InternalLinkedHashMap to Map I'm trying to get data from cloud_firestore.
void _getData(){
    final getData = await FirebaseFirestore.instance
        .collection('users')
        .doc(id)
        .get();
    Map<String, dynamic> d = getData.data()!;

    for (dynamic i in d["tags"]) {
       .......
    }
}

But when _getData() is called, an error occurs at for (dynamic i in d["tags"]) .
 _TypeError (type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>')

I found this answer and changed my code.
Map<String, dynamic> d = getData.data()!;
to
Map<String, dynamic> d = Map<String, dynamic>.from(getData.data()!);
But the error never be fixed.
I don't want waste time with useless _InternalLinkedHashMap.
RunTimeType print
print("type: " + d["tags"].runtimeType.toString());

output
I/flutter (18762): type: _InternalLinkedHashMap<String, dynamic>

A: I found the error origin. when the specific document was broken, this error occurs.
In my case, I thought database was like this:
tags (array)
 |- tag1 (map)
     |- user (String)
     |- date (Timestamp)
 |- tag2 (map)
     |- user (String)
     |- date (Timestamp)
 ...

However the database was actually this:
tags (array)
 |- user (String)
 |- date (Timestamp)


text:
Q: Trying to webscrape odds from site I am trying to webscrape 'https://www.oddschecker.com/football/germany/bundesliga/wolfsburg-v-eintracht-frankfurt/winner' this page (or any other like it on the website) for the 'both teams to score' odds.
This is what I have so far
url = 'https://www.oddschecker.com/football/spain/la-liga-primera/levante-v-rayo-vallecano/winner'

req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

webpage = urlopen(req).read()

page_soup = soup(webpage, 'html.parser')

btts = page_soup.find_all('div', class_='full-bleed-wrapper MarketWrapper_mgnb13w')[13]
print(btts)

But this is where I get stuck as I can't seem to dive down to 'button' where the odds are.
Any help would be great, thanks

A: The numbers you see on the page is loaded dynamically with JavaScript (so beautifulsoup doesn't see them). You can use next example how to simulate the dynamic request:
import json
import requests
import pandas as pd
from bs4 import BeautifulSoup

url = "https://www.oddschecker.com/football/spain/la-liga-primera/levante-v-rayo-vallecano/winner"
req = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
page_soup = BeautifulSoup(req.content, "html.parser")

market_id = page_soup.select_one('h2:-soup-contains("Both Teams To Score")')
market_id = market_id["aria-controls"]

api_url = (
    "https://www.oddschecker.com/api/markets/v2/all-odds?market-ids={}&repub=OC"
)

data = requests.get(api_url.format(market_id)).json()

# uncomment this to print all data:
# print(json.dumps(data, indent=4))

# df_bets = pd.json_normalize(data[0]["bets"])
# print(df_bets)

df_odds = pd.json_normalize(data[0]["odds"])
print(df_odds)

Prints:
          betId bookmakerCode  oddsDecimal oddsFractional oddsUs                                                            bookmakerSelectionId  status movement  eachWay  eachWayDenominator  eachWayPlaces             betFeedTimestamp inOut inOutChange
0   26800267296            SK     3.500000            5/2    250                                                       905375896*59*28150512*5/2  ACTIVE    -0.25    False                   0              0     2021-09-07T12:44:47.029Z   out       -0.25
1   26800267296            EE     3.450000          49/20    245                                                                      6306209648  ACTIVE    +0.05    False                   0              0     2021-09-07T12:38:08.776Z    in       +0.05
2   26800267204            WH     4.400000           17/5    340         3314095633*992686788*Levante*Match+Result+and+Both+Teams+To+Score*false  ACTIVE    +0.07    False                   0              0     2021-09-07T12:27:49.609Z    in       +0.07
3   26800267204            FB     4.333334           10/3    333                                                            214865*924.274512130  ACTIVE    +0.13    False                   0              0     2021-09-03T09:49:05.545Z    in       +0.13
4   26800267204            PP     4.333334           10/3    333                                                            214865*927.146755960  ACTIVE    +0.13    False                   0              0     2021-09-03T09:49:23.595Z    in       +0.13
5   26800267204            SK     4.333334         100/30    333                                                    905375886*59*28150512*100/30  ACTIVE             False                   0              0     2021-09-06T09:52:03.916Z
6   26800267204            B3     4.330000           10/3    333  2092734890*106731205*Soccer*106731205*B3F90A267EC31D8BF4F7FF30A5C3D02C2917F802  ACTIVE             False                   0              0     2021-09-07T04:04:41.927Z
7   26800267204            FR     4.330000           10/3    333                                                 10*3*159105085.20*1091224276.20  ACTIVE             False                   0              0     2021-09-03T06:20:06.525Z
8   26800267204            EE     4.250000           13/4    325                                                                      6306209647  ACTIVE    +0.05    False                   0              0     2021-09-07T12:38:08.776Z    in       +0.05
9   26800267204            BY     4.200000           16/5    320                                             21512675.1*189770761.1*1357637677.1  ACTIVE    +0.20    False                   0              0     2021-09-07T14:14:03.361Z    in       +0.20
10  26800267204            SI     4.200000           16/5    320                                football*spain-primera-division*775212*367102865  ACTIVE    -0.05    False                   0              0     2021-09-02T06:41:51.322Z   out       -0.05
11  26800267204            VC     4.200000           16/5    320                                               6320610.105286032500.530000911886  ACTIVE    -0.13    False                   0              0     2021-09-07T13:19:30.309Z   out       -0.13
12  26800267141            VC     4.750000           15/4    375                                               6320610.105286032800.529952778757  ACTIVE             False                   0              0     2021-09-03T11:07:16.837Z
13  26800267141            SI     4.700000          37/10    370                                football*spain-primera-division*775212*367102869  ACTIVE    +0.05    False                   0              0     2021-09-02T06:41:51.395Z    in       +0.05
14  26800267141            WH     4.600000           18/5    360            3314095639*992686788*Draw*Match+Result+and+Both+Teams+To+Score*false  ACTIVE    +0.10    False                   0              0     2021-09-07T12:27:50.506Z    in       +0.10
15  26800267141            B3     4.500000            7/2    350  2092734892*106731205*Soccer*106731205*B786A6C56C8B974A78D9BAD863B067DF54F276E7  ACTIVE             False                   0              0     2021-09-07T04:04:41.934Z
16  26800267141            EE     4.500000            7/2    350                                                                      6306209649  ACTIVE             False                   0              0     2021-09-07T12:38:08.776Z
17  26800267141            FR     4.500000            7/2    350                                                  7*2*159105085.20*1091224274.20  ACTIVE             False                   0              0     2021-09-03T06:20:06.525Z
18  26800267141            SK     4.500000            7/2    350                                                       905375889*59*28150512*7/2  ACTIVE    +0.17    False                   0              0      2021-09-07T12:44:47.03Z    in       +0.17
19  26800267141            WA     4.500000            7/2    350                                                     781872749*202013791*8178269  ACTIVE             False                   0              0     2021-09-07T12:25:16.163Z
20  26800267141            FB     4.333334           10/3    333                                                            151478*924.274512130  ACTIVE    +0.13    False                   0              0     2021-09-03T09:49:05.544Z    in       +0.13
21  26800267141            PP     4.333334           10/3    333                                                            151478*927.146755960  ACTIVE    -0.17    False                   0              0     2021-09-03T00:02:28.432Z   out       -0.17
22  26800267141            BY     4.330000           10/3    333                                             21512675.1*189770761.1*1357637678.1  ACTIVE    +0.13    False                   0              0     2021-09-07T14:14:03.377Z    in       +0.13
23  26800267141            VT     4.150000          41/13    315                                                             18495007*2336849385  ACTIVE    +0.10    False                   0              0     2021-09-07T14:41:47.833Z    in       +0.10
24  26800267187            EE     6.300000          53/10    530                                                                      6306209644  ACTIVE    +0.10    False                   0              0     2021-09-07T12:38:08.776Z    in       +0.10
25  26800267187            SK     6.000000            5/1    500                                                       905375902*59*28150512*5/1  ACTIVE             False                   0              0     2021-09-06T09:52:03.916Z
26  26800267318            WH     7.500000           13/2    650       3314095643*992686788*Vallecano*Match+Result+and+Both+Teams+To+Score*false  ACTIVE    +0.50    False                   0              0     2021-09-07T12:27:52.616Z    in       +0.50
27  26800267318            B3     7.000000            6/1    600  2092734894*106731205*Soccer*106731205*AE9F693032CEF0361A3B091EBB0A63AE217343C2  ACTIVE             False                   0              0     2021-09-07T04:04:41.932Z
28  26800267318            FR     7.000000            6/1    600                                                  6*1*159105085.20*1091224278.20  ACTIVE    +0.50    False                   0              0      2021-09-05T20:28:01.22Z    in       +0.50
29  26800267318            SK     7.000000            6/1    600                                                       905375892*59*28150512*6/1  ACTIVE    +0.50    False                   0              0      2021-09-07T12:44:47.03Z    in       +0.50
30  26800267318            VC     7.000000            6/1    600                                               6320610.105286033200.529956789555  ACTIVE             False                   0              0     2021-09-03T10:53:08.351Z
31  26800267318            EE     6.800000           29/5    580                                                                      6306209646  ACTIVE    +0.05    False                   0              0     2021-09-07T12:38:08.776Z    in       +0.05
32  26800267318            BY     6.500000           11/2    550                                             21512675.1*189770761.1*1357637679.1  ACTIVE             False                   0              0     2021-09-07T14:14:03.377Z
33  26800267318            FB     6.500000           11/2    550                                                             10779*924.274512130  ACTIVE             False                   0              0  2021-09-01T08:57:57.259568Z
34  26800267318            PP     6.500000           11/2    550                                                             10779*927.146755960  ACTIVE    -0.50    False                   0              0     2021-09-03T09:49:23.595Z   out       -0.50
35  26800267318            SI     6.200000           26/5    520                                football*spain-primera-division*775212*367102867  ACTIVE    +0.20    False                   0              0     2021-09-02T06:41:51.479Z    in       +0.20
36  26800267159            VT    10.100000          91/10    910                                                             18495007*2336849380  ACTIVE    +1.20    False                   0              0     2021-09-07T14:41:47.833Z    in       +1.20
37  26800267159            SK    10.000000            9/1    900                                                       905375899*59*28150512*9/1  ACTIVE             False                   0              0     2021-09-06T09:52:02.815Z
38  26800267159            EE     9.500000           17/2    850                                                                      6306209645  ACTIVE    -0.75    False                   0              0     2021-09-07T12:38:08.776Z   out       -0.75


text:
Q: Retrieving leaves from differently branched parent nodes with C# in an XML document <Root>
  <P1 Text ="A" >
    <P2 Text = "AA">
      <P3 Text = "AAA">
        <L Text = "l_A"/>
        <L Text = "l_B"/>
        <L Text = "l_C"/>
      </P3>
      <P3 Text = "BBB">
        <L Text = "l_D"/>
        <L Text = "l_E"/>
        <L Text = "l_F"/>
      </P3>
    </P2>
    <P2 Text = "BB">
       <L Text = "l_G"/>
       <L Text = "l_H"/>
       <L Text = "l_I"/>
    </P2>
  </P1>
</Root>

From an XML document containing thousands of variably nested nodes up to 10 levels deep, I
would like to retrieve programmatically only the leaves belonging to any of the "P" parents
as follows: for instance, in the example above, selecting P2 "AA" would yield l_A to l_F and P3 "BBB" would give l_D to l_F.

A: Something like this (returns a list of strings):
    XDocument doc = XDocument.Load(@"test.xml");

    string level = "P3";
    string levelAttr = "AAA";

    var list = (from d in doc.Descendants(level)
                let xAttribute = d.Attribute("Text")
                where xAttribute != null && xAttribute.Value == levelAttr
                from l in d.Descendants("L")
                let lAttribute = l.Attribute("Text")
                where lAttribute != null
                select lAttribute.Value);

You may remove the attribute null checks if the Text attribute is always there...

A: one way is using XPath by XmlDocument(if you not using LINQ)
your XPath may be like this:
//P2[@Text='AA']//L/@Text

and your code like this:
XmlDocument document; //init and load it

static List<String> GetLeavesText(int pLevel /* 2 */, string pText /* AA */)
{
    var result = new List<String>();

    //loaded document

    var nodeList = document.SelectNodes(String.Format(@"//P{0}[@Text='{1}']//L/@Text", pLevel, pText));
    if (nodeList != null)
        foreach (XmlNode xmlNode in nodeList)
        {
            result.Add(xmlNode.InnerText);
        }

    return result;
}


text:
Q: Why dividing by zero still works Today, I was at a class. There was a question:

If $x = 2 +i$, find the value of $x^3 - 3x^2 + 2x - 1$.

What my teacher did was this:
$x = 2 + i \;\Rightarrow \; x - 2 = i \; \Rightarrow \; (x - 2)^2 = -1 \; \Rightarrow \; x^2 - 4x + 4  = -1 \; \Rightarrow \; x^2 - 4x + 5 = 0 $. Now he divided $x^3 - 3x^2 + 2x - 1$ by $x^2 - 4x + 5$.
The quotient was $x + 1$ and the remainder $x - 6$. Now since $\rm dividend = quotient\cdot divisor + remainder$, he concluded that $x^3 - 3x^2 + 2x - 1 = x-6$ since the divisor is $0$.
Plugging $2 + i$ into $x - 6$, we get $-4 + i$.
But my question is, how was he able to divide by zero in the first place? Why did dividing by zero work in this case?

A: The division was a division in the polynomial ring $\mathbb{C}[x]$
by a non-zero polynomial
For example: by dividing $$x^{2}+2x+1$$ by $$x+1$$ which is a non-zero
polynomial we get $$(x+1)(x+1)=x^{2}+2x+1$$ since the quotient is
$x+1$ and the reminder is $0$. The result is an equality
of polynomials, and it is valid if you set any element in the field
in those polynomials, even $x=-1$.

A: $\begin{eqnarray}{\bf Hint}\quad&& f(x) = r(x) + q(x)\, \color{#c00}{g(x)}\quad \text{[divide } f\ \text{ by }\ g\ \text{ with quotient }\, q, \text{ remainder }\, r\,]\\
\stackrel{\large \color{#c00}{g(a)\,=\,0}}\Rightarrow && f(a) = r(a)\quad \text{by evaluation at } x = a,\text{ using }\ \color{#c00}{g(a) = 0}. \end{eqnarray}$
Because we wrote the "division" as $\ f = q\,\color{#c00}g + r,\,$ not as $\smash[b]{\, \dfrac{f}{\color{#c00}g} = q + \dfrac{r}{\color{#c00}g},\,}$ there is no division by $\,0\,$  when we evaluate at a root of $\,\color{#c00}g.$
Your question has $\,g\,$ quadratic, with root $\,a = 2+i.\,$  The simpler linear case is well-known.
For linear  $\,g = x\! -\!a\,$ we have $\, r = f(a),\,$ i.e. $\,f(x)\equiv f(r)\pmod{\!x\!-\!a}\ \ $ [Remainder Theorem]. $\ $
Said equivalently $\ x\!-\!a\mid f(x)\!-\!f(a)\ \ $ [Factor Theorem]
For further insight, and a nontrivial application, see the Heaviside cover-up method for evaluating partial fraction decompositions. This does explicitly involve fractions, and, as such, the circumvention of division by zero is more explicit.
More explicitly, we can use division to calculate polynomial derivatives purely algebraically
$$\begin{eqnarray} f'(a) &=\,& \dfrac{f(x)-f(a)}{x-a}\Bigg|_{\large\, x\,=\,a}\\ \\ {\rm i.e.}\ \ \ f'(a) &=\,& q(a)\ \ {\rm where}\ \ f(x)-f(a) = q(x)(x-a)\end{eqnarray}$$
There is no division by zero because the prior linear equation defines a unique polynomial $\,q(x),\,$ and polynomials have no sinularities, i.e. they can be evaluated at any point. This leads to purely algebraic proofs of familiar analytic results, e.g. the double-root test for polynomials.
For a more extreme example of circumvention of division by $\,0,\,$ see this discussion of a proof of Sylvester's determinant identity. Even some professors have mistakenly thought that this proof involves division by zero (a strong testament to the gaps in the exposition of the universal properties of polynomials in many algebra courses).  But here,  as in the prior examples, there is, in fact, no division by zero, because, before evaluation, one performs valid polynomial operations that eliminate (apparent) singularities. Thus to gain the full universal algebraic power of formal polynomials, one has to (temporarily) forget their anayltic view (as functions). This is easier said than done, since the analytic (functional) bias is so strongly ingrained in our intution.

A: The division your teacher did is polynomial division. He did not divide by zero; he divided by $x^2 - 4x + 5$.
The long division he did is just an algorithm that allows you to get the following identity:
$$x^3 - 3x^2 + 2x - 1 = (x^2 - 4x + 5)(x+1) + x-6$$
This is an identity involving multiplication, not division. Now, when you plug in $x = 2 + i$, you're not dividing by zero; you're multiplying by zero, which you should agree is allowed.

A: because he's only dividing by zero when $x$ takes that value (or its conjugate) otherwise he's really just figuring out what the next thing he'll need to multiply is. Yes, it may look a little dodgy, think of this as a sort of back-of-the-envelope calculation. It's only a means to find out the next step and since in the final expression we no longer have this factor in the denominator, everything works out fine.
Think for example of Factorizing $x^2+7x+12$. We can similarly divide by $x+4$ and get a result of $x+3$ to conclude that $x^2+7x+12=(x+4)(x+3)$. While we can only technically divide by $x+4$ if $x\not=-4$, the process still works out fine.


text:
Q: Pandas Dataframe reorganizing columns and rows I'm attempting to consolidate channel lists from providers to show all channels as the row indices and values as the provider name.  Currently organized as:
         DIRECTV           FUBO     YOUTUBE TV
0            A&E            A&E            ABC
1            ABC     ADULT SWIM            AMC
2    ACCUWEATHER            AMC  ANIMAL PLANET
3            AMC  ANIMAL PLANET            BBC
4  ANIMAL PLANET            BBC      BBC WORLD

I would like the result to be (header row can be anything):
A&E            DIRECTV  FUBO
ABC            DIRECTV        YOUTUBE TV
ACCUWEATHER    DIRECTV
ADULT SWIM              FUBO
AMC            DIRECTV  FUBO  YOUTUBE TV
ANIMAL PLANET  DIRECTV  FUBO  YOUTUBE TV
BBC                     FUBO  YOUTUBE TV
BBC WORLD                     YOUTUBE TV

I believe this should be accomplished very simply through a join, merge, or other, but I can't get it working.  Any help would be appreciated.
Note: the above images are obviously just a small sample of the list, the index column should be every unique channel from all providers.  Something along the lines of "df.values.unique()".  Yes, I know that doesn't work.

A: IIUC, this is a melt + crosstab problem

u = df.melt(
    var_name='provider',
    value_name='channel'
)

pd.crosstab(
  index=u['channel'],
  columns=u['provider'],
  values=u['provider'],
  aggfunc='first'
)

provider       DIRECTV  FUBO  YOUTUBE TV
channel
A&E            DIRECTV  FUBO         NaN
ABC            DIRECTV   NaN  YOUTUBE TV
ACCUWEATHER    DIRECTV   NaN         NaN
ADULT SWIM         NaN  FUBO         NaN
AMC            DIRECTV  FUBO  YOUTUBE TV
ANIMAL PLANET  DIRECTV  FUBO  YOUTUBE TV
BBC                NaN  FUBO  YOUTUBE TV
BBC WORLD          NaN   NaN  YOUTUBE TV

If you would rather a simple 1 or 0 if a value exists, just omit the aggfunc and values argument from crosstab:
pd.crosstab(u['channel'], u['provider'])

provider       DIRECTV  FUBO  YOUTUBE TV
channel
A&E                  1     1           0
ABC                  1     0           1
ACCUWEATHER          1     0           0
ADULT SWIM           0     1           0
AMC                  1     1           1
ANIMAL PLANET        1     1           1
BBC                  0     1           1
BBC WORLD            0     0           1


text:
Q: Glitchy grid in QGraphicsView::drawBackground I'm trying to properly display a grid pattern on QGraphicsView::drawBackground. Everything seems to work fine until I try to move an item added to a scene.
I add the line in MainWindow like this:
   QPen _Pen;
   _Pen.setColor(Qt::red);
   _Pen.setWidth(3);

   QGraphicsLineItem* _Line=new QGraphicsLineItem(0,0,100,100);
   _Line->setPen(_Pen);
   _Line->setVisible(true);
   _Line->setFlags(QGraphicsLineItem::ItemIsSelectable | QGraphicsLineItem::ItemIsMovable);

   m_scene->addItem(_Line);

Methods of GraphicsView:
GraphicsView::GraphicsView() : cellSize(20)
{
   setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
}

void GraphicsView::drawBackground(QPainter *p, const QRectF &crect)
{
   p->save();
   p->setPen(QPen(Qt::black,1));

   for (int x = crect.topLeft().x(); x < crect.bottomRight().x(); x += cellSize)
      for (int y = crect.topLeft().y(); y < crect.bottomRight().y(); y += cellSize)
         p->drawPoint(x, y);

   p->restore();
}

The problem can be seen here:

When I move the item, it leaves a trail of grid dots behind it, which are not aligned to the original grid.
I don't understand where this error comes from. Have I done something wrong?

A: I can think of 2 possible issues:

*

*Change the view update mode. The options are described here.
setViewportUpdateMode(SmartViewportUpdate); or setViewportUpdateMode(FullViewportUpdate);

*The smear may be caused by the item bounding rectangle of the item being half a pixel too small.
(I realize this question is old, but maybe it will help someone else)

A: The region you're given in drawBackground is not always the full view. When something on the scene changes, you're given only the relevant region to redraw. And you're starting in the top left corner of different "moving" regions.
One way to fix this would be to make the initial x and y multiples of cellSize:
for (int x = (int)crect.left()/cellSize*cellSize; x < crect.right(); x += cellSize)
    for (int y = (int)crect.top()/cellSize*cellSize; y < crect.bottom(); y += cellSize)


text:
Q: Different Definition of Differentiability Question from Calculus 3:

*

*Let $f(x,y)$ be a function that's defined in a neighborhood of $(x_0,y_0)$. Show that exist $a(x,y), b(x,y) $ that are continuous at $(x_0, y_0)$, such that:

$f(x,y)=f(x_0, y_0)+a(x,y)(x-x_0)+b(x,y)(y-y_0)$.
I was able to solve this, but am writing this to explain the next part of the question which I couldn't solve.

*Do there exist any points $(x_1, y_1)\neq (x_0 ,y_0)$, such that $b(x_1,y_1)=f_y(x_1,y_1)$. This I wasn't able to solve, though I found that $b(x,y)=f_y (x_0,y_0)$.

For more background, the way I calculated $b$, was through the definition of differentiability, when $f(x,y)=f(x_0,y_0)+f_x(x_0,y_0)(x-x_0)+f_y(x_0,y_0)(y-y_0)+r(x,y)$, when $r(x,y)=o(d((x,y), (x_0,y_0))$, and using a theorem, I wrote:
$r(x,y)=u(x,y)(x-x_0)+v(x,y)(y-y_0)$, when $lim_{(x,y)\rightarrow(x_0,y_0)}v(x,y)=0$, and I defined $b(x,y)=f_y(x_0,y_0)+v(x,y)$.
So to say that $b(x_1,y_1)=f_y(x_1,y_1)$ is to say that $f_y(x_1,y_1)=f_y(x_0,y_0)+v(x_1,y_1)$. Now does there exist $(x_1,y_1)\neq (x_0,y_0)$, such that this is true?

A: Consider e.g. $f(x,y) = y^2$ with $x_0 = 0$, $y_0 = 0$.  Then you can take $a(x,y) = 0$ and $b(x,y) = y$.  You never have $y_1 = f_y(x_1,y_21) = 2 y_1$ unless $y_1 = 0$.
EDIT: OK, here's a counterexample.  Take $$\eqalign{f(x,y) &= x^2 y +  {y}^{3}\cr
a(x,y) &= x y\cr
b(x,y) &=  y^2 \cr
x_0 = y_0 = 0\cr}
$$
Then $f_y(x_1,y_1) = x^2  + 3 y^2 \ne b(x,y) = y^2$ unless $x=y=0$.


text:
Q: git/svn Hooks for PHP/Zend Projects just because i think we are not using the full potential of all possibilites here yet:
What Pre/Post Commit Hooks (i.e. PHPUnit, PHPDoc) do you people use on your Team Git/SVN Servers?
By now we do use a minification script (sadly only removes unneccessary space and comments and merges files), PHPDoc, PHPUnit and that's it already.
Any good ideas that might be usefull as well?

A: We use a Jenkins setup that runs Sebastiann Bergman's default template, including pdepend, phploc, phpmd, to analyse style quality, architecture quality and the likes.
http://jenkins-php.org/
We've already greatly improved the quality of our codebase since we started using it a few weeks ago :)

A: I use a pre-commit hook that checks for proper indentation and styling.


text:
Q: Importing css-element-queries to an angular 6 application I'm trying to install and use the css-element-queries library.
For installing, I used the following command:
npm i css-element-queries

After that, I tried to import the class ResizeSensor from the library like this:
import { ResizeSensor } from 'css-element-queries';

But the compiler retrieves the following error:

Could not find a declaration file for module 'css-element-queries'.
  'c:/PrjNET/Elevation3/FW/4.00/Mainline/Framework/Development/Client/ElevationJS/ngcore/node_modules/css-element-queries/index.js'
  implicitly has an 'any' type.   Try npm install
  @types/css-element-queries if it exists or add a new declaration
  (.d.ts) file containing `declare module 'css-element-queries';

Based on the error message, I tried to run the following npm command:
npm install @types/css-element-queries

But the compiler retrieved the following error:

npm ERR! code E404 npm ERR! 404 Not Found:
  @types/css-element-queries@latest

How can I import the css-element-queries library?

A: I don't use Angular, but I just ran into importing ResizeSensor into a typescript based application. I don't know when css-element-queries added ResizeSensor.d.ts, but it is part of the package now.
However, that file is incorrect. I have filed an issue on gitHub for it. Yesterday I did some investigation on how to get it imported and ended up reading about the different module types and how to create a typings file in the typescript documentation.
This led me to the proper way to define the typings file for ResizeSensor. Basically take the one from the github repository and change the export line from:
export default ResizeSensor;

to
export = ResizeSensor;

then you can use this as your import:
import ResizeSensor = require('Libs/css-element-queries/ResizeSensor');

Your path to css-element-queries will be different because you wont be able to pull it from npm until the package maintainer fixes the .d.ts file.
Here is a link to the github issue.

A: While there isn't typings package yet, I'm able to use the css-element-queries package using these imports:
import * as ElementQueries from 'css-element-queries/src/ElementQueries';
import * as ResizeSensor from 'css-element-queries/src/ResizeSensor';

Atom still gives info warnings about not being able to find a declaration file, but it still works. Hope this helps!


text:
Q: no matching function for call to 'Book::Book()' I am doing something for a MIT OCW course and it asks to write a 'library' class . Right now I have this:
#include <iostream>

using namespace std;

class Book{
    string title;
    bool rented;
public:
    Book(string bookTitle){
        title = bookTitle;
    }
    void borrowed(){
        rented = true;
    }
    void returned(){
        rented = false;
    }
    bool isBorrowed(){
        return rented;
    }
    string getTitle(){
        return title;
    }
};

class Library{
    string Lname;
    Book bookList[100000000];
    int numOfBooks = 0;
public:
    Library(string name){
        Lname = name;
    }
    void addBook(string bookName){
        bookList[numOfBooks] = Book(bookName);
        numOfBooks += 1;
    }
    void returnInfo(){
    cout << "Library hours:" << "\n" << "Libraries are open daily from 9am to 5pm." << "\n" << "Library addresses:" << "\n" << "10 Main St." << "\n" << "228 Liberty St.";
    }

};
int main()
{
    Library l = Library("Hi");
    return 0;
}

And when I compile it gives me the error no matching function for call to 'Book::Book()' for line 35.

A: Compiler complains that you haven't defined default constructor for Book, you could try this:
 explicit Book(const string& bookTitle = std::string(""))
 : title(bookTitle)
 {
 }

Define 100000000 on stack my cause overflow,
Book bookList[100000000];

try to use vector instead
std::vector<Book> bookList;

In addBook, you could simply use std::vector::push_back to add a new book. To get total book number, use std::vector::size()
void addBook(const string& bookName){
    bookList.push_back(Book(bookName));
}

Suggestion:

*

*To pass parameter to function like std::string, pass by const

*reference is a better way. use member initialization list if possible

 Library(const string& name) : Lname(name) {  }
 void addBook(const string& bookName){ }

A: Book bookList[100000000];

Will try to create 100000000 object with default constructor..

A: the  bookList is created as an array of objects not as an array of string and then you are assigning strings(bookName) to bookList so i think the problem lies here.


text:
Q: How dns resolve root-servers.net As I know there is 13 root dns server in the world which named from A to M.
and when no dns server answered in dns server chain,we access root dns servers.
I also suppose root server should be ip address something like 4.4.2.2 or 8.8.8.8 but using dig show me they're really domains
;; ANSWER SECTION:
.           78559   IN  NS  d.root-servers.net.
.           78559   IN  NS  f.root-servers.net.
.           78559   IN  NS  e.root-servers.net.
.           78559   IN  NS  i.root-servers.net.
.           78559   IN  NS  a.root-servers.net.
.           78559   IN  NS  l.root-servers.net.
.           78559   IN  NS  g.root-servers.net.
.           78559   IN  NS  c.root-servers.net.
.           78559   IN  NS  h.root-servers.net.
.           78559   IN  NS  b.root-servers.net.
.           78559   IN  NS  j.root-servers.net.
.           78559   IN  NS  m.root-servers.net.
.           78559   IN  NS  k.root-servers.net.

Now how DNS resolve root-servers.net address?

A: Those root servers are defined in the config file of the DNS server, most run BIND and it's in the config file root.servers
Internic constantly provides the most up-to-date one, which is currently (both ipv4 and ipv6 addresses):
a.root-servers.net. IN  A   198.41.0.4
a.root-servers.net. IN  AAAA    2001:503:BA3E::2:30

b.root-servers.net. IN  A   192.228.79.201

c.root-servers.net. IN  A   192.33.4.12

d.root-servers.net. IN  A   199.7.91.13
d.root-servers.net. IN  AAAA    2001:500:2d::d

e.root-servers.net. IN  A   192.203.230.10

f.root-servers.net. IN  A   192.5.5.241
f.root-servers.net. IN  AAAA    2001:500:2f::f

g.root-servers.net. IN  A   192.112.36.4

h.root-servers.net. IN  A   128.63.2.53
h.root-servers.net. IN  AAAA    2001:500:1::803f:235

i.root-servers.net. IN  A   192.36.148.17
i.root-servers.net. IN  AAAA    2001:7fe::53

j.root-servers.net. IN  A   192.58.128.30
j.root-servers.net. IN  AAAA    2001:503:C27::2:30

k.root-servers.net. IN  A   193.0.14.129
k.root-servers.net. IN  AAAA    2001:7fd::1

l.root-servers.net. IN  A   199.7.83.42
l.root-servers.net. IN  AAAA    2001:500:3::42

m.root-servers.net. IN  A   202.12.27.33
m.root-servers.net. IN  AAAA    2001:dc3::35

A: DNS resolvers come with a root hints file (see http://www.internic.net/domain/named.root) built-in -- as part of their configuration -- which lists the names and IPs of the root DNS servers.
By the way, that's the same principle with SSL/TLS certificate validation in your browser - the browser traverses the certificate chain up to validate a website's SSL/TLS certificate -- potentially downloading multiple intermediate certificate authority (CA) certificates -- but the root CA certificates come pre-installed with the browser.
In general and in other terms, when there's a recursive process involved you must define a base case. Otherwise you have an endless loop.


text:
Q: Error importing anydbm python 2.7.6 I get the following error when trying to import anydbm in python 2.7.6. Does anyone know whats going wrong? Appreciate your help.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/anydbm.py", line 50, in <module>
_errors.append(_mod.error)
AttributeError: 'module' object has no attribute 'error'

A: Try dbm it should work. I know in Python3 anydbm to dbm has been renamed.
import dbm

A: Reloading the information about available software in Ubuntus Software & Updates GUI fixed the problem.


text:
Q: Open angular material Snackbar in service I want to show the user Errors through a Snackbar. Which is totally fine when I open a Snackbar through a component:
export class AppComponent implements OnInit {

    constructor(private snackBar: MatSnackBar) {
    }

    ngOnInit() {
        this.snackBar.open('message');
    }
}

But when I want to open a Snackbar in my DataService it throws this error:
ERROR TypeError: Cannot read property 'open' of undefined

My DataService looks like this:
export class DataService {

  private api = 'https://localhost:5001/api/';

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };

  constructor(private http: HttpClient,
              private snackBar: MatSnackBar) {
  }

  getData() {
    return this.http.get(this.api, this.httpOptions)
      .pipe(
        retry(3), // retry a failed request up to 3 times
        catchError(this.handleError) // then handle the error
      );
  }

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }

    this.snackBar.open('Something bad happened, please try again later.');

    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  }
}

So, after the third attempt of getting Data it goes into the handleError() and should open a SnackBar with "Something bad happened, please try again later."

A: This happens because the current scope inside catchError is not the class itself and thus
this.snackbar

is not defined. To fix this, there are 2 methods
Method 1:
You can return your callback function from inside another function to preserve the scope as
private handleError() {
    return (error: HttpErrorResponse) => {
        //your logic
    }
}

and change your catchError method as
catchError(this.handleError())  //note the parenthesis on handleError

Method 2:
Simply bind the callback method in catchError to this as
this.ErrorHandler.bind(this)


text:
Q: Can a planemo turn into a star? I read this question
Why is planet CFBDSIR2149-0403 hot?
and wonder what will happen to this "planemo". Will it attract more mass as it flows around in the gas clouds in space and eventually light up and become a star?

A: It is very unlikely that a planetary mass object will accrete enough mass to take it above the mass limit (about $0.075 M_{\odot}$) to become a bona fide star supported by pp H-burning reactions.
An order of magnitude calculation might suffice.
An average sort of velocity that such objects might be moving at relative to the interstellar medium (ISM) is of order 10 km/s.
The ISM density is the biggest variable here - it could be anywhere between about $10^{-23}$ to $10^{-15}$ kg/m$^{3}$ in the densest molecular clouds. An average value might be around $10^{-21}$ kg/m$^3$.
The sound speed in the ISM is around 1 km/s in molecular clouds, but much higher elsewhere.
The relevant physics here is the Bondi-Hoyle accretion rate - an approximate formula that says a compact object moving through a medium will accrete at
$$\dot{M} \simeq  \frac{2\pi G^2M^2 \rho}{(v^2 + c_s^2)^{3/2}}, $$
where $M$ is the object's mass, $v$ its velocity with respect to a medium with density $\rho$ and $c_s$ the sound speed.
So, in the optimal case of say a $0.05M_{\odot}$ planetary mass object (well, actually a brown dwarf) moving at 10 km/s through a molecular cloud, then $\dot{M}$ is of order a few $10^{-12} M_{\odot}$/year. Thus it could be that over the course of billions of years an object could accumulate the hundredths of a solar mass required to form a star. However, the case considered above is very optimal. An object travelling at 10 km/s will spend only a small fraction of its life passing through molecular clouds and instead will encounter a medium with a density that is orders of magnitude lower and a sound speed that is order of magnitudes higher.


text:
Q: write always returns EAGAIN for connected nonblock socket after a while I'm writing a client server socket program in c on a ubuntu linux box.
the server side needs to handle many connections and both the server and client have a local socket to send received data to a local process after some manipulating it and the number of sent and received data are huge. (the size of data is not very huge, maximum 1500)
here is the diagram:
    [local process of client] <-> data <-> client <---------> server <-> data <-> [local process of server]
so all the sockets (client_local_socket, client_remote_socket, server_remote_socket,server_local_socket) need to be nonblock.
when I run the client and server in two computers in lan network, it works grate, but when move the server program to a linux server in internet (client connects to the server behind a nat) client starts communicating successfully with the server (both client and server get some EAGAIN error, but recover it after the next tries and as I know its pretty normal for nonblock) but after a while (more than 1000 send and receive packets), the client_remote_socket fails in writing with error code EAGAIN and can not recover it in the next tries and after that, it always gets this damn EAGAIN for writing. BTW client_remote_socket has no problem in reading and allways get packets from server. the server has no problem at all and client_local_socket works grate in both writing and reading.
I've used this code to make sockets nonblock:
int flags;
if ((flags = fcntl(client_remote_socket, F_GETFL, 0)) < 0)
    flags = 0;
flags = flags | O_NONBLOCK;
fcntl(client_remote_socket, F_SETFL, flags);

I also have tried it with:
fcntl(client_remote_socket, F_SETFL, O_NONBLOCK);

but the results is the same.
the only setsockopt that I've used is SO_REUSEADDR in the server side and client has no setsockopt.
its good to mention that I always check the value that write returns and when it is <0 I check the the errno and see its EAGAIN.
As I know, write returns EAGAIN, when the kernel has no available space for the write buffer and it does not make any sense that kernel has no memory for me in laptop with a 4 GB ram. and BTW it works grate when I run both client and server in a lan network.
when this hapens in client, server does not show any sign of broken client socket, and its right, because in the meantime, it can receive data from the server. I double checked the code again and again and tried to debug it many times and could not see anything wrong. I also used the select system call to check if the socket is available for writing and it always returns 0 when the time comes.
now I have no clue to solve this and any ideas would be very grate for me.
thanks.

A: I have gotten the same problem last week and after doing a research I found that it's because the peer's buffer is full. I tested this case.

When the remote buffer is full, it tells your local stack to stop sending. When data is cleared from the remote buffer (by being read by the remote application) then the remote system will inform the local system to send more data.

This is answer of Brian White
https://stackoverflow.com/a/14244450/3728361


text:
Q: How to re-format cURL command to AWS CLI s3 sync call I have a curl command:
curl -C - "https://fastmri-dataset.s3.amazonaws.com/knee_singlecoil_train.tar.gz?AWSAccessKeyId=<my-key>&Signature=<my-signature>&Expires=1634085391

I'm having trouble using AWS CLI sync, I'm doing this:
aws s3 sync . s3://fastmri-dataset/knee_singlecoil_train.tar.gz

I have the aws configure file setup with the access key, I set the secret up with the signature. I didn't otherwise get a secret.
Any help is appreciated.

A: Your first link is an Amazon S3 pre-signed URLs, which is a time-limited URL that provides temporary access to a private object. It can be accessed via an HTTP/S call.
The AWS CLI command you have shown instructs the AWS CLI to synchronize the local directory with a file on S3. (This is actually incorrect, since you cannot sync a directory to a file.)
These two commands are incompatible. The AWS CLI cannot use a pre-signed URL. It requires AWS credentials with an Access Key and Secret Key to make AWS API calls.
So, you cannot reformat the curl command to an AWS CLI command.


text:
Q: Find matrix of linear map of polynomials For the question below, I am not sure how to find the desired matrix relative to the standard basis.  $P_3$ refers to polynomials with up to degree $3$
Thanks in advance

for the linear map
$$T:P_3(\mathbb{R})\rightarrow\mathbb{R^4}, p\mapsto \big(p(0), p(1), p\prime(0), p\prime(1)  \big)$$
a) Find the matrix $[T]_\beta^\gamma$ of $T$ relative to the standard bases of $P_3(\mathbb{R})$ and of $\mathbb{R^4}$
b) Show that $T$ is an isomorphism

A: Let $B := \{1, X, X^2, X^3\}$ be the standard basis of $\mathbb{R}_{\leq3}[X]$, and $B' = \{e_1, e_2, e_3, e_4\}$ the standard basis of $\mathbb{R}^4$. Now, by definition, $[T]_{B}^{B'}$ has on column $i$ the coordinates in $B'$ of the image of the $i$-th vector of $B$. So, since $B'$ is the canonical basis, taking coordinates is redundant: it suffices to place $T(X^{i-1})$ in each column $i$. So,
$$
T(1) = (1,1,0,0)\\
T(X) = (0,1,1,1)\\
T(X^2) = (0,1,0,2)\\
T(X^3) = (0,1,0,3)
$$
and therefore,
$$[T]_{B}^{B'}=
\begin{bmatrix}
    1 & 0 & 0 & 0\\
    1 & 1 & 1 & 1\\
    0 & 1 & 0 & 0\\
    0 & 1 & 2 & 3
\end{bmatrix}
$$
To finish we must conclude that $T$ is an isomorphism. This follows from the fact that $[T]_{B}^{B'}$ is invertible, since
$$\det
\begin{bmatrix}
    1 & 0 & 0 & 0\\
    1 & 1 & 1 & 1\\
    0 & 1 & 0 & 0\\
    0 & 1 & 2 & 3
\end{bmatrix} =
\det \begin{bmatrix}
    1 & 1 & 1\\
    1 & 0 & 0\\
    1 & 2 & 3
\end{bmatrix} =
\det \begin{bmatrix}
    1 & 1\\
    2 & 3
\end{bmatrix} = 1 \neq 0
$$


text:
Q: webrtc can not see remote video but can hear audio I am the new in webrtc , I had some problems on webrtc.   i can not see remote video ,but can hear audio below android o .i can see remote video and hear audio on android o.  webrtc version implementation 'org.webrtc:google-webrtc:1.0.25003'

A: Ensure you create well the video track, put it on the stream and also it should be enabled.


text:
Q: grails database migration "Column not found" error I'm using the grails database migration plugin: runtime ':database-migration:1.4.1'. For the initial changelog everything seems to work, even going from an H2 development database to mysql.
However, I wanted to test an actual model change, and I'm getting an error I can't figure out.
We have the following User model:
class User {

    // spring security params:
    transient springSecurityService

    String username
    String password

    // Added this to test model changes:
    String removeme

    ...

    static mapping = {
        password column: '`password`'
    }
}

When I go to generate the diff, i.e.
grails dbm-gorm-diff --add change_test.groovy
I get the following exception:
liquibase.exception.DatabaseException: org.h2.jdbc.JdbcSQLException: Column "PASSWORD" not found; SQL statement:
SELECT password FROM user WHERE 1 = 0 [42122-176]
    at liquibase.snapshot.jvm.JdbcDatabaseSnapshotGenerator.createSnapshot(JdbcDatabaseSnapshotGenerator.java:251)
    at liquibase.snapshot.DatabaseSnapshotGeneratorFactory.createSnapshot(DatabaseSnapshotGeneratorFactory.java:69)
    at liquibase.diff.Diff.compare(Diff.java:71)
    at grails.plugin.databasemigration.GormDiff.compare(GormDiff.groovy:45)
    at grails.plugin.databasemigration.ScriptUtils.createAndPrintFixedDiff(ScriptUtils.groovy:244)
    at DbmGormDiff$_run_closure1$_closure2$_closure3.doCall(DbmGormDiff:53)
    at grails.plugin.databasemigration.MigrationUtils.executeInSession(MigrationUtils.groovy:137)
    at DbmGormDiff$_run_closure1$_closure2.doCall(DbmGormDiff:50)
    at grails.plugin.databasemigration.ScriptUtils.executeAndWrite(ScriptUtils.groovy:104)
    at DbmGormDiff$_run_closure1.doCall(DbmGormDiff:49)
Caused by: org.h2.jdbc.JdbcSQLException: Column "PASSWORD" not found; SQL statement:
SELECT password FROM user WHERE 1 = 0 [42122-176]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:344)
    at org.h2.message.DbException.get(DbException.java:178)
    at org.h2.message.DbException.get(DbException.java:154)
    at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:148)
    at org.h2.command.dml.Select.prepare(Select.java:831)
    at org.h2.command.Parser.prepareCommand(Parser.java:248)
    at org.h2.engine.Session.prepareLocal(Session.java:442)
    at org.h2.engine.Session.prepareCommand(Session.java:384)
    at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1188)
    at org.h2.jdbc.JdbcStatement.executeQuery(JdbcStatement.java:75)
    at liquibase.snapshot.jvm.JdbcDatabaseSnapshotGenerator.isColumnAutoIncrement(JdbcDatabaseSnapshotGenerator.java:842)
    at liquibase.snapshot.jvm.JdbcDatabaseSnapshotGenerator.readColumns(JdbcDatabaseSnapshotGenerator.java:369)
    at liquibase.snapshot.jvm.JdbcDatabaseSnapshotGenerator.createSnapshot(JdbcDatabaseSnapshotGenerator.java:244)

I can simply remove the removeme column and everything works as expected. This is only in our dev environment too, so only regarding the H2 database.

A: I solved this pretty much based on this answer:
How can I use Grails DB Migration with Spring Security and the default DB, H2?
Changed this
static mapping = {
    password column: '`password`'
}

to
static mapping = {
    password column: 'passwd'
}

Basically the above is preferred (IMO) because it avoids confusion in the database engine, and having to deal with weird escaping -- by just using something that isn't generally a reserved word.


text:
Q: Need help making a 3D mesh given co-ordinates of the vertices and vertex indices of each face for 3D Slicer - trimesh python Given the following data:

*

*The Cartesian co-ordinates of the vertices in the surface mesh: n vertices x 3

*The vertex indices of each face in the surface mesh: n faces x 3

I'm trying to export some 3D file that I can readily import to 3D Slicer for registration against a VTK file.
Faces: https://pastebin.com/qWq7aiEs
Vertices: https://pastebin.com/VxsxsdcM
I have been trying various packages/libraries etc. and keep running into various issues. The following issue is using the Trimesh in Python and I'm attributing the problem to my poor python ability rather than an issue with the package. I'm open to other solution as well.
I imported the CSV, extracted the arrays then converted to lists to match the example. I wasn't certain how to use the faces data given the example, so I just made a list that matched the length of vertices, not sure if that's right at all.
# Example: mesh objects can be created from existing faces and vertex data
mesh = trimesh.Trimesh(vertices=[[0, 0, 0], [0, 0, 1], [0, 1, 0]],
                       faces=[[0, 1, 2]])

# My attempt
vertex_x = vertices_csv[:,0]
vertex_y = vertices_csv[:,1]
vertex_z = vertices_csv[:,2]
vertex_x_list = vertex_x.tolist()
vertex_y_list = vertex_y.tolist()
vertex_z_list = vertex_z.tolist()
faces_list_mesh = [i for i in range(len(vertex_x_list))]

mesh = trimesh.Trimesh(vertices=[vertex_x_list, vertex_y_list, vertex_z_list],
...                        faces=[faces_list_mesh])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\...\Python\Python310\lib\site-packages\trimesh\base.py", line 190, in __init__
    self.process(validate=validate,
  File "C:\...\Python\Python310\lib\site-packages\trimesh\base.py", line 232, in process
    self.merge_vertices(merge_tex=merge_tex,
  File "C:\...\Python\Python310\lib\site-packages\trimesh\base.py", line 1123, in merge_vertices
    grouping.merge_vertices(
  File "C:\...\Python\Python310\lib\site-packages\trimesh\grouping.py", line 70, in merge_vertices
    referenced[mesh.faces] = True
IndexError: index 3 is out of bounds for axis 0 with size 3

Any advice how to troubleshoot is greatly appreciated!

A: By downloading the data you provided, I coded the following:
import numpy as np
import trimesh

vertices = np.loadtxt("vertices.txt", delimiter=",")
faces = np.loadtxt("faces.txt", delimiter=",") - 1

mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
mesh.export("mesh.stl")

So the code does work, however I am not so sure about the correctness of your input data. Vertices are indexed from 0 to vertex_count - 1, so in this case [0, 6500] That's why I have subtracted -1 to faces since vertices are 0-indexed.
The faces array consists of vertex indices, however its maximum index values (after subtracting -1) is 6500 and that's fine, but the minimum is 262. So check your data carefully.
The code above exports the following mesh: