text:
Q: Some weird results of apoc.coll.zip() I create 3 test nodes with name properties are "a", "b", "c", and use apoc.coll.zip() to combine two lists together:
MATCH (n:test)
WITH collect(n.name) as nodes
WITH apoc.coll.zip(nodes, range(0, size(nodes))) as pairs
RETURN pairs;

+--------------------------------+
| pairs                          |
+--------------------------------+
| [["a", 0], ["b", 1], ["c", 2]] |
+--------------------------------+

The result is expected. What is interesting is when I modify the query either by adding another column in the RETURN clause or by UNWINDing the pair.
1. RETURN pairs,n.name;
MATCH (n:test)
WITH n, collect(n.name) as nodes
WITH n, apoc.coll.zip(nodes, range(0, size(nodes))) as pairs
RETURN pairs,n.name;
+---------------------+
| pairs      | n.name |
+---------------------+
| [["a", 0]] | "a"    |
| [["b", 0]] | "b"    |
| [["c", 0]] | "c"    |
+---------------------+

I expect the result to be exactly the same with the query:
MATCH (n:test)
WITH n, [["a", 0], ["b", 1], ["c", 2]] as nested
RETURN nested, n.name;

+---------------------––––––––––––––––––--+
| pairs                          | n.name |
+---------------------––––––––––––––––––--+
| [["a", 0], ["b", 1], ["c", 2]] | "a"    |
| [["a", 0], ["b", 1], ["c", 2]] | "b"    |
| [["a", 0], ["b", 1], ["c", 2]] | "c"    |
+---------------------––––––––––––––––––--+

2. UNWIND pairs as pair RETURN pairs
MATCH (n:test)
WITH n, collect(n.name) as nodes
WITH n, apoc.coll.zip(nodes, range(0, size(nodes))) as pairs
UNWIND pairs as pair
RETURN pairs;

+------------+
| pairs      |
+------------+
| [["a", 0]] |
| [["b", 0]] |
| [["c", 0]] |
+------------+

I expect the result to be no different than having no UNWIND clause:
+--------------------------------+
| pairs                          |
+--------------------------------+
| [["a", 0], ["b", 1], ["c", 2]] |
+--------------------------------+

3. UNWIND pairs as pair RETURN pair
MATCH (n:test)
WITH n, collect(n.name) as nodes
WITH n, apoc.coll.zip(nodes, range(0, size(nodes))) as pairs
UNWIND pairs as pair
RETURN pair;
+----------+
| pair     |
+----------+
| ["a", 0] |
| ["b", 0] |
| ["c", 0] |
+----------+

I expect the result to be no different than simply UNWIND a nested list:
UNWIND [["a", 0], ["b", 1], ["c", 2]] as list
RETURN list;

+----------+
| list     |
+----------+
| ["a", 0] |
| ["b", 1] |
| ["c", 2] |
+----------+

Do you know why these happen? They don't seem to be explained in RETURN and UNWIND documentation.

A: For all the 3 queries listed, the key point is at,
...
WITH n, collect(n.name) as nodes
...

collect is an aggregating function and it can be grouped. Specifying 'n' in the WITH clause causes it to do "group by" similar to SQL grouping. Therefore if you have 3 nodes, you get 3 results.
You can debug by RETURNing after the WITH to see the result at each step,
like so,
MATCH (n:test)
WITH n, collect(n.name) as nodes
RETURN n, nodes


text:
Q: php generated css no output, net::ERR_INCOMPLETE_CHUNKED_ENCODING I am running apache on an ubuntu installation.
Several webapps are running on the same server.
I installed a new app, which required the pdo-sqlite extension to be installed.
Now my server is noticeably slower and doesn't seem to respond when asked for php generated CSS e.g. asking for:
  phpmyadmin/phpmyadmin.css.php

gives an empty page (not a 404 error)
This seems to apply to all web-apps on the server where css is being generated from a php file. Other pages also show net::ERR_INCOMPLETE_CHUNKED_ENCODING in Chrome whereas Firefox doesn't complain.
Firefox says Status OK ... 0 bytes
Chrome is throwing up a load of net::ERR_INCOMPLETE_CHUNKED_ENCODING errors for all sorts of pages, not just the .css.php
The same webapps run perfectly fine on the development server. (no errors from Chrome and .css being returned from .css.php files)
things I tried:

*

*uninstalling php5-sqlite

*rebooting the server

*disabling pdo extensions in php

*checking for any .htaccess files

Any clues much appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to set up svn server on my home computer? I have VisualSVN Server and I want to create a public facing repository on my computer but I can't seem to get it right. I created the repository, disabled https, and I'm trying to access the server through either
svn://xxx.xx.xxx.xxx:8080/svn/repo/trunk

http://xxx.xx.xxx.xxx:8080/svn/repo/trunk

but each case gives me an error.
In the case of svn protocol:
Can't connect to host 'xxx.xx.xxx.xxx': No connection could be made because the target machine actively refused it.

And in the http case:
OPTIONS of 'http://xxx.xx.xxx.xxx:8080/svn/repo': could not connect to server (http://xxx.xx.xxx.xxx:8080)

What am I missing?
Do I need to configure an apache server or something like that in order to be able to make the server public?
I'm running on Windows Seven, windows firewall is disabled, no other firewall is installed, except for the hardware firewall in the router, but I forwarded the ports to the router, which didn't really change much..
=(
what else can I try?

A:
If you right click and select properties for your server you might check the authentication tab to see whether you have set subversion or windows authentication. Additionally when you are viewing the repositories right-click one and Copy URL to make sure the address is what you expect.


text:
Q: Joomla Proper CMS for complex design i am very confused right now. I came from Wordpress,and laravel frameworks, and now i am assigned to develop Joomla! project.I thought i can easily manage to create custom template in joomla. I have been reading a lot of articles and documentation. I've manage to create a template and display modules.
But now, i need to start digging the right way to display the content and manage it in Joomla! back-end.
Here's my problem. I have home page (Long page) and inner pages (Short page). Here's the structure of my homepage

    ... header links and other necessary tags

            image and text here! (i made this as 1 modules in Custom HTML)

            video here (i made this as 1 modules in Custom HTML)

            form here (i made this as 1 modules in Custom HTML)

            image and text here! (i made this as 1 modules in Custom HTML)

            image and text here! (i made this as 1 modules in Custom HTML)

        video here (i made this as 1 modules in Custom HTML)

and this is my inner pages

 ... header links and other necessary tags

            Article Content (i will do as jdoc:inlucde type="component")

            sidebar Content (i will do this as 1 modules in Custom HTML)

Those template are really different.
Problem 1 : How can i make my inner pages if my homepage structure is very different? Or
Problem 2 :How can i make display my section (homepageonlysection) in home page only and display (innerpagessectiononly) in inner pages only?
Problem 3 : Is there a Advance Custom Field (ACF for wordpress) as joomla extension ?
Please advice. Any help would be appreciated.

A: One thing I recommend is really digging into the core templates (both front and backend) to understand how things work. In particular Isis the backend template illustrates a number of complex options.
Now, overall I think you probably do not want to do the homepage the way you are doing it, since it will be very inflexible and hard to change. On the other hand it's possible that you want it inflexible and hard to change. In reality you may not need to have separate layouts at all or the differences may be minimal and may not require any special code at all.
So, first, this document explains how to determine if you are on the home page. So you can clearly pretty easily test for that and then enclose your two separate designs in the true and false conditions. This is basically what you see in Isis. In your case you can place one or more module position inside the condition. In fact you could make it so this layout does not even load a component. Then you can just make an empty article and make the home page a single article link to that empty article. (I would put that article into a separate landing page category)
A second option if you really want to have a totally different design on the home page is to make a totally separate template for the home page.  If say you called this "my home template" and your other template "my everywhere else template" what you could do is make "my everywhere else template" the default and then on the default (homepage) menu item assign the "my home template" template. In this special template you can even use the module  jdoc:include (instead of modules) to call specific modules in highly customized ways. I would suggest you go read the docs on that. You can even set the options and the chrome right in the template.
However, I think you are missing a key feature of Joomla. In your question you have not said what kind of  menu link you are planning to use for your home page. The third option is that for the homepage you use the same template but a specific alternate layout that you use for this page. For your case what you would most likely want to do, assuming that you are not using the featured articles layout type anywhere else (i.e. that no articles are marked featured), is to make your homepage using an articles > featured menu link.  Then you can assign all the modules you made to the home page via the menu modules tab.  Depending on how your module positions are in the template it could just be that they will float up.
Your design is not a particularly unusual or complex however. Many Joomla homepages consist of multiple structured sections of text and media. These are made with menu types such as "featured" and "category blog." The advantage of using these menu types is that then you are storing your content in articles and these are much easier to manage. ALso you don't have to give someone access to the module manager in order to allow them to edit these snippets of content. So the fourth and possibly best approach is to use one of these standard content layouts. For example if you were to make a category called "home page content" and then put the content for each of the modules in a separate article and (assuming you want a consistent structure) put the image for each of them into the structured intro text image field, you can then make a "category blog" menu link to the "home page content" category as you default (home page) menu link.  Then what you can do is make one or more layout override for those individual items that gives the exact layout you want.  Assuming that they are all the same, you can select that as a alternate layout in your menu link. Actually even if they are not all the same you can just do a more complex layout instead of looping through the list and doing the same thing for each article, do each one separately.
A fifth approach is to use an alternative layout instead of an alternate layout. The difference there is that you would give the layout a new name (in either the category or featured  view) and then you will have the additional flexibility of being able to create options in the menu link that are different than those for the normal category/featured views.  It's up to you to decide what you might want to add there.
There are other options as well, because Joomla has a very strong template community and they like to have a lot of flexibility.  But that will get you started.


text:
Q: How to I make a table on a JDialog So I am making a game, and when you push the button called history, a JDialog pops up where it shows you the moves you have done. I was wondering how I would make a table on the JDialog with an ok button at the bottom it.
Example Table:
|Move|                 What Happened                    |
| 1  |A beam shot from 6 lands on 29                    |
| 2  |Guess at (3,5) with a direction of \ was incorrect|
| 3  |Guess at (4,3) with a direction of / was correct  |

A: You can create a custom dialog that extends JDialog, and display it when you click the history button...I always call a static method in the new custom dialog class such as "showDialog()" which then instantiates the dialog, sets it to visible, etc. You can add all the elements to the dialog you want, including your table, and an OK button whose listener will setVisible(false) and dispose() to return control back to the spot where you called the static method to show the dialog.


text:
Q: Producer Consumer using semaphores-c Problem:

*

*All processes have an array of elements.

*Producer stores a value in his array.

*All consumers(n) must store this value on their array before a producer can produce additional element.

*All consumers should store the element and wait until the producer creates a new one.

So in my implementation I'm using three semaphores: all(as a barrier)=1, new=0 and a mutex=1. I'm also using a shared counter=0 to count how many consumers have read the element.
Code:
#include <time.h>
#include <sys/shm.h>
#include "stdio.h"
#include "sys/sem.h"
#include "stdlib.h"
#include "unistd.h"

int sem_id;
int shmid;
typedef struct sharedMemory{
    int value;
}sharedMemory;

union semun {
    int                 val;
    struct semid_ds *   buf;
    unsigned short *    array;
};

#define M 4
#define N 2

typedef enum semIndex{
    mutex= 0,
    all=1,
    new=2
}semIndex;

int sem_init(semIndex index,int val){
    union semun sem_union;
    sem_union.val = val;
    if (semctl(sem_id, index, SETVAL, sem_union) == -1) return 0;
    return 1;
}

int up(semIndex index) {
    struct sembuf sem_b;
    sem_b.sem_num = index;
    sem_b.sem_op = 1;
    if (semop(sem_id, &sem_b, 1) == -1) {
        perror("Failed to up");
        return 0;
    }
    return 1;
}

int down(semIndex index) {
    struct sembuf sem_b;
    sem_b.sem_num = index;
    sem_b.sem_op = -1;
    if (semop(sem_id, &sem_b, 1) == -1) {
        perror("Failed to up");
        return 0;
    }
    return 1;
}

void *getShMemory(int memory) {
    shmid = shmget((key_t)1234+memory, sizeof(sharedMemory), 0666 | IPC_CREAT);
    if (shmid == -1) {
        fprintf(stderr, "shmget failed\n");
        exit(EXIT_FAILURE);
    }
    void* shared_memory = shmat(shmid, (void *)0, 0);
    if (shared_memory == (void *)-1) {
        fprintf(stderr, "shmat failed\n");
        exit(EXIT_FAILURE);
    }
    return shared_memory;
}

int main(void){
    srand(getpid() + rand()%500);
    int *array = malloc(M * sizeof(int));
    for (int i = 0; i < M; ++i) {
        array[i] = rand() % 20;
    }
    sem_id = semget(6846, 3, 0666 | IPC_CREAT);
    sharedMemory *sharedMem = (sharedMemory*) getShMemory(2);
    sem_init(all,1);
    sem_init(mutex,1);
    sem_init(new,0);
    pid_t pid = fork();
    if (pid>0){
        for (int i = 0; i < M; ++i) {
            down(all);
            down(mutex);
            sharedMem->value = array[i];
            up(mutex);
            up(new);
        }
        for (int j = 0; j < M; ++j) {
            printf("%d,",array[j]);
        }
        putchar('\n');
    }
    else{
        sem_id = semget(6846, 3, 0666 | IPC_CREAT);
        int *array = malloc(M*sizeof(int));
        sharedMemory* consumerMem = (sharedMemory*)getShMemory(1);
        down(new);
        consumerMem->value = 0;

        for(int i=0;i<N;++i){
                if(fork() == 0) {
                    for (int j = 0; j < M; ++j) {
                        down(mutex);
                        consumerMem = (sharedMemory*)getShMemory(1);
                        sharedMemory *sharedMem = (sharedMemory*) getShMemory(2);
                        array[j] = sharedMem->value;
                        consumerMem->value++;
                        up(mutex);

                        if (consumerMem->value == N) {
                            down(mutex);
                            consumerMem->value = 0;
                            up(mutex);
                            up(all);            //signal producer to create new element
                        }
                        down(new);   //wait for new element
                        up(new);     //unblock one more consumer
                    }
                    for (int j = 0; j < M; ++j) {
                        printf("%d,",array[j]);
                    }
                    putchar('\n');
                    exit(0);
                }
            }
        }
}

Sometimes it works as intended so it ought to be a race condition but I can't pinpoint it.Any clues?
Update:
I managed to run debug with Clion. I can't replicate the problem with the debugger so it's even harder to pinpoint the problem.


text:
Q: How to serve a static content using ingress nginx I have one service called "workspace-service-b6" which is running on port 5000, See the below ingress file. Now I want to serve the static content on the same service (workspace-service-b6) by adding the path route.
Example:- Service is working on https://workspace-b6.dev.example.com
Now if the user adds  "/workspace/v2/ "at the end of the URL.
Like this:- https://workspace-b6.dev.example.com/workspace/v2/ it will redirect to s3 bucket "https://s3.console/buckets/xyz/abc/build" where my static content is available.
My Ingress file :-
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: b6-ingress
namespace: b6
annotations:
kubernetes.io/ingress.class: "nginx"
kubernetes.io/tls-acme: "true"
spec:
tls:
- hosts:
- workspace-b6.dev.example.com
secretName: xyz-crt
rules:
- host: workspace-b6.dev.example.com
http:
paths:
- backend:
serviceName: workspace-service-b6
service port: 5000

A: While it's kind of possible, the real answer is "don't". The ingress system is just a proxy, set up separate pods for content.


text:
Q: Problem connecting to EC2 instance via GIT BASH I have a problem connecting to my aws ec2 instance, i can easily connect to my jumpbox instance and then when i try to ssh to my private ec2 it does not let me. I think it has something to do with my key pair, i only have one on my aws account so i don't know why it does not let me connect to it so i can install something. I didn't have this problem before but now i have been stuck on it for days. I have attached the error and says ECDSA key fingerprint twice when i ssh to my private instance so i'm guessing that has something to do with the problem.
If someone knows please advise.

enter code hereJUMPBOXSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
  GroupDescription: 'JUMPBOX Security Group'
  GroupName: JUMPBOXSG
  SecurityGroupIngress:
   - CidrIp: 0.0.0.0/0
     Description: 'SSH from my IP address'
     FromPort: 22
     ToPort: 22
     IpProtocol: tcp
  VpcId: !Ref Myvpc
  Tags:
     - Key: Name
       Value: JUMPBOXSecurityGroup

enter code hereJUMPBOXEC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-08e4e35cccc6189f4
InstanceType: t2.micro
NetworkInterfaces:
- AssociatePublicIpAddress: "true"
DeviceIndex: "0"  ### dodeluva public ip adressa na prviot interface
SubnetId: !Ref MyPublicSubnet
GroupSet:
- !Ref JUMPBOXSecurityGroup
KeyName: Key
Tags:
- Key: Name
Value: JUMPBOXEC2Instance
Here is my jumpbox instance with security group
enter code hereMyPublicEC2InstanceSG:
Type: AWS::EC2::SecurityGroup
Properties:
  GroupDescription: 'Public EC2 Security Group'
  SecurityGroupIngress:
   - CidrIp: 0.0.0.0/0
     Description: 'http from everuwhere'
     FromPort: 80
     ToPort: 80
     IpProtocol: tcp
   - SourceSecurityGroupId: !Ref JUMPBOXSecurityGroup
     Description: 'ssh from Jumpbox'
     FromPort: 22
     ToPort: 22
     IpProtocol: tcp
  VpcId: !Ref Myvpc
  Tags:
     - Key: Name
       Value: MyPublicEC2InstanceSG

MyPublicEC2Instance:

Type: AWS::EC2::Instance
Properties:
ImageId: ami-0b5eea76982371e91
InstanceType: t2.micro
NetworkInterfaces:
- AssociatePublicIpAddress: "true"
DeviceIndex: "0"  ### dodeluva public ip adressa na prviot network interface
SubnetId: !Ref MyPublicSubnet
GroupSet:
- !Ref MyPublicEC2InstanceSG
KeyName: Key
Tags:
- Key: Name
Value: MyPublicEC2Instance
Here is my public ec2 instance with security group

A: Since you're seeing an actual "permission denied" error, it's not likely a security group issue. Those tend to cause the connection to hang and/or time out.
Seems like the wrong ssh key is being used. From your "jumpbox" (i.e. not your local machine), add "-vvv" to the ssh command (ex. ssh -vvv es2-user@10.1.5.157). In the output, you'll see which key or config file is being used. If an ssh config file is being used on the jumpbox instance, be sure it's pointing to the correct key, and that the key exists on the jumpbox. If the wrong key is being used, simply supply the correct one using the -i option of the ssh command, or update the config file to point to the correct key location.
My guess is that the correct key doesn't exist on your jumpbox. SSH does not automatically forward your key between instances. So a quick fix would be to copy the key to the jumpbox. But the preferred way would be to enable agent forwarding from your local machine. (see: https://docs.github.com/en/developers/overview/using-ssh-agent-forwarding)
Actually, ideally you would connect using SSM instead! (see: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/session-manager.html) This has its own list of headaches, but once you get it running it lets you connect without a jumpbox and without keypairs. You also don't need to leave port 22 open on any instances.


text:
Q: No 'Access-Control- Allow-Origin' header is present on the requested resource. How to properly serve CORS requests in SWI-Prolog / ClioPatria? I'm trying to POST some data in my SWI-Prolog / ClioPatria application server through the UI application, and I keep getting the error:
Access to XMLHttpRequest at 'http://localhost:3020/testPost' from origin
'http://localhost:8000' has been blocked by CORS policy: No 'Access-
Control- Allow-Origin' header is present on the requested resource

How can I properly enable CORS in the server?
I've checked the swi-prolog CORS documentation, as well as this really good tutorial but I still can't make it work.
This is the prolog code I'm running in the server:
:- use_module(library(semweb/rdf11)).

:- use_module(library(http/http_client)).
:- use_module(library(http/html_write)).
:- use_module(library(http/http_json)).
:- use_module(library(http/json)).
:- use_module(library(http/json_convert)).
:- use_module(library(http/http_header)).
:- use_module(library(http/http_cors)).

:- set_setting(http:cors, [*]).

:- http_handler(root(testPost), testPost, []).

testPost(Request) :-
  option(method(post), Request), !,
  cors_enable(Request,
              [ methods([get,post,delete],
                headers(['Access-Control-Allow-Origin'('*')]))
              ]),
  http_read_data(Request, In, [application/x-www-form-urlencoded]),
  reply_json(In.label).

I'm sending the following request with vanilla javascript:
function sendTestRequest() {

    let url="http://localhost:3020/testPost"

    var body = {
        "label": "car_label",
        "title": "car_title",
        "description": "car_description",
        "weights": [0.7, 0.3]
    }

    var formBody = new FormData();

    for (var key in body) {
        formBody.set(key, formBody[key]);
        console.log(key + " -> " + body[key]);
    }

    //create CORS request
    var xhr = createCORSRequest('POST', url);

      if (!xhr) {
        alert('CORS not supported');
        return;
      }

    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    // Response handlers.
    xhr.onload = function() {
      var text = xhr.responseText;
          console.log("request successfully sent")
      console.log('Response from CORS request to ' + url + ': ' + text);
    };

    xhr.onerror = function() {
      console.log(xhr.responseText)
    };

    xhr.send(formBody);
}

function createCORSRequest(method, url) {

  var xhr = new XMLHttpRequest();

  if ("withCredentials" in xhr) {

    // Check if the XMLHttpRequest object has a "withCredentials" property.
    // "withCredentials" only exists on XMLHTTPRequest2 objects.
    xhr.open(method, url, true);

  } else if (typeof XDomainRequest != "undefined") {

    // Otherwise, check if XDomainRequest.
    // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
    xhr = new XDomainRequest();
    xhr.open(method, url);

  } else {

    // Otherwise, CORS is not supported by the browser.
    xhr = null;

  }
  return xhr;
}

sendTestRequest();


text:
Q: Why does task manager as administrator not show all tasks seen when NOT administrator? This is what I see as a user.  I am most interested in VBBatchPrint.exe.  I want to end the task, but I can't unless I log into task manager as admin.

When I enter taskman as administrator, however, those items do not appear.  Even in detail, the actual PIDS do not appear

1) Why does taskman as admin not show EVERYTHING?
2) How do I end processes I can't see as admin?

A: It's a matter of Rights. The "missing" processes are running at a higher level than the user account you are using.
To change this you can elevate the user account or you can run the processes at a lower level. (I am not suggesting either, security is there for a reason)


text:
Q: Running a docker container which uses GPU from kubernetes fails to find the GPU I want to run a docker container which uses GPU (it runs a cnn to detect objects on a video), and then run that container on Kubernetes.
I can run the container from docker alone without problems, but when I try to run the container from Kubernetes it fails to find the GPU.
I run it using this command:
kubectl exec -it namepod /bin/bash

This is the problem that I get:
kubectl exec -it tym-python-5bb7fcf76b-4c9z6 /bin/bash
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
root@tym-python-5bb7fcf76b-4c9z6:/opt# cd servicio/
root@tym-python-5bb7fcf76b-4c9z6:/opt/servicio# python3 TM_Servicev2.py
 Try to load cfg: /opt/darknet/cfg/yolov4.cfg, weights: /opt/yolov4.weights, clear = 0
CUDA status Error: file: ./src/dark_cuda.c : () : line: 620 : build time: Jul 30 2021 - 14:05:34

 CUDA Error: no CUDA-capable device is detected
python3: check_error: Unknown error -1979678822
root@tym-python-5bb7fcf76b-4c9z6:/opt/servicio#

EDIT.
I followed all the steps on the Nvidia docker 2 guide and downloaded the Nvidia plugin for Kubernetes.
however when I deploy Kubernetes it stays as "pending" and never actually starts. I don't get an error anymore, but it never starts.
The pod appears like this:
gpu-pod                       0/1     Pending   0          3m19s

EDIT 2.
I ended up reinstalling everything and now my pod appears completed but not running. like this.
default       gpu-operator-test                          0/1     Completed   0             62m

Answering Wiktor.
when I run this command:
kubectl describe pod gpu-operator-test

I get:
Name:         gpu-operator-test
Namespace:    default
Priority:     0
Node:         pdi-mc/192.168.0.15
Start Time:   Mon, 09 Aug 2021 12:09:51 -0500
Labels:       <none>
Annotations:  cni.projectcalico.org/containerID: 968e49d27fb3d86ed7e70769953279271b675177e188d52d45d7c4926bcdfbb2
              cni.projectcalico.org/podIP:
              cni.projectcalico.org/podIPs:
Status:       Succeeded
IP:           192.168.10.81
IPs:
  IP:  192.168.10.81
Containers:
  cuda-vector-add:
    Container ID:   docker://d49545fad730b2ec3ea81a45a85a2fef323edc82e29339cd3603f122abde9cef
    Image:          nvidia/samples:vectoradd-cuda10.2
    Image ID:       docker-pullable://nvidia/samples@sha256:4593078cdb8e786d35566faa2b84da1123acea42f0d4099e84e2af0448724af1
    Port:           <none>
    Host Port:      <none>
    State:          Terminated
      Reason:       Completed
      Exit Code:    0
      Started:      Mon, 09 Aug 2021 12:10:29 -0500
      Finished:     Mon, 09 Aug 2021 12:10:30 -0500
    Ready:          False
    Restart Count:  0
    Limits:
      nvidia.com/gpu:  1
    Requests:
      nvidia.com/gpu:  1
    Environment:       <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-9ktgq (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             False
  ContainersReady   False
  PodScheduled      True
Volumes:
  kube-api-access-9ktgq:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:                      <none>

I'm using this configuration file to create the pod
apiVersion: v1
kind: Pod
metadata:
  name: gpu-operator-test
spec:
  restartPolicy: OnFailure
  containers:
  - name: cuda-vector-add
    image: "nvidia/samples:vectoradd-cuda10.2"
    resources:
      limits:
         nvidia.com/gpu: 1

A: Addressing two topics here:

*

*The error you saw at the beginning:

kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.

Means that you tried to use a deprecated version of the kubectl exec command. The proper syntax is:
$ kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...]

See here for more details.

*According the the official docs the gpu-operator-test pod should run to completion:

You can see that the pod's status is Succeeded and also:

 State:          Terminated
   Reason:       Completed
   Exit Code:    0

Exit Code: 0 means that the specified container command completed successfully.
More details can be found in the official docs.


text:
Q: Подскажите почему не работает функция удаления блока из корзины? Извиняюсь, что не отсеял лишнее. Подскажите почему не отрабатывает кнопка del_button в корзине после добавления элементов. Что не так делаю?
42-49я строки
https://jsfiddle.net/fn1botva/1/
 //Функция удаления элемента из корзины
function delItem() {
    this.parentElement.remove()
}
//Обработка нажания на кнопку для удаления элементы из корзины
for (var i = 0; i < del_button.length; i++) {
    del_button[i].onclick = delItem;
}

A: Проблема в создании элемента.
При клонировании, клонируются атрибуты, но не клонируются обработчики навешанные с помощью addEventListener или свойств, например el.onclick = ...
Поэтому в последнем цикле, можно добавить всем атрибут:
del_button[i].setAttribute('onclick', 'delItem.call(this)');

.call(this) в данном случае нужен, чтобы не менять саму функцию обработчик.
При этом delItem должна быть объявлена глобально.
Пример:

//5* Реализовать модуль корзины. Создать блок товаров и блок корзины. У каждого товара есть кнопка «Купить», при нажатии на которую происходит добавление имени и цены товара в блок корзины. Корзина должна уметь считать общую сумму заказа.
let items = document.getElementsByClassName('item'),
  recycle = document.getElementById('recycle'),
  infotext = document.getElementById('infotext'),
  summ = document.getElementsByClassName('summ'),
  del_button = document.getElementsByClassName('del_button')
//Функция добавления элемента в корзину
function addItem() {
  //скрываем кнопку купить
  infotext.style.display = 'none';
  //добавляем элементы в корзину
  let item_clone = this.parentElement.cloneNode(true);
  recycle.appendChild(item_clone)

  //Считаем общую сумму покупок
  let prices = recycle.getElementsByClassName('price')
  totalprice = 0;
  for (let j = 0; j < prices.length; j++) {
    totalprice = totalprice + Number(prices[j].innerHTML);
    //console.log('Элемент N', j + 1, 'Сумма:', totalprice);
  }
  console.log('TOTAL PRICE', totalprice);
  summ[0].innerHTML = 'TOTAL PRICE ' + totalprice;
}

//Обработка нажатия на кнопку для добавления элемента в корзину
let item_button = document.getElementsByClassName('item_button');
for (var i = 0; i < item_button.length; i++) {
  item_button[i].onclick = addItem;
};
//Очистка корзины
let buttonClear = document.getElementById('clear');
buttonClear.onclick = function() {
  //очистка начального текста корзины
  recycle.innerHTML = ''
  recycle.appendChild(infotext)
  infotext.style.display = 'block';
  //очистка блока с общей суммой покупок
  summ[0].innerText = '';
}

//Функция удаления элемента из корзины
function delItem() {
  this.parentElement.remove()
}

//Обработка нажания на кнопку для удаления элементы из корзины
for (var i = 0; i < del_button.length; i++) {
  del_button[i].setAttribute('onclick', 'delItem.call(this)');
}
button {
  font-family: sans-serif;
  display: block;
  color: white;
  font-size: 17px;
  font-weight: 400;
  text-align: justify;
  text-decoration: none;
  background-color: purple;
  width: 132px;
  height: auto;
  padding: 10px;
  text-align: center;
  margin: 5px;
  text-transform: uppercase;
}

button:hover {
  color: purple;
  background-color: white;
}

p {
  color: #010101;
  font-size: 26px;
  font-weight: 300;
  line-height: 24px;
  text-align: center;
}

.item p {
  color: rebeccapurple;
  font-size: 26px;
  font-weight: 300;
  line-height: 24px;
  text-align: center;
  border: 1px solid black;
  background-color: white;
}

* {
  margin: 0;
  padding: 0;
}

.Container {
  width: 1280px;
  margin: 0 auto;
  background-color: White;
  height: 100%;
  border-right: 4px solid black;
  border-left: 4px solid black;
  height: 2000px;
}

.summ {
  font-family: sans-serif;
  color: #010101;
  font-size: 16px;
  font-weight: 700;
  line-height: 24px;
  text-align: center;
  width: 300px;
  height: 100px
}

.Recycle {
  margin-left: 0 auto;
}

.Recycle h1 {
  padding-left: 200px;
}

#recycle {
  width: auto;
  height: auto;
  border: 2px solid red;
  margin: 5%;
  display: flex;
  flex-wrap: wrap;
}

#recycle .item_button {
  display: none;
}

.del_button {
  display: none;
}

#recycle .del_button {
  display: block;
}

.Items {
  width: auto;
  display: flex;
  padding: 5%;
  height: 454px;
  justify-content: space-between;
  background-image: url(big/Layer8.png);
  background-repeat: no-repeat;
}

#recycleButton {
  float: right;
}

h1 {
  font-family: sans-serif;
  color: #000000;
  font-size: 40px;
  font-weight: 400;
  line-height: 49.542px;
  text-align: center;
}

.infoblock {
  float: right;
}

OUR TRENDING PRODUCTS

1000

      <button class='item_button'>BUY IT</button>
      <button class='del_button'>Del</button>

2000

      <button class='item_button'>BUY IT</button>
      <button class='del_button'>Del</button>

3000

      <button class='item_button'>BUY IT</button>
      <button class='del_button'>Del</button>

4000

      <button class='item_button'>BUY IT</button>
      <button class='del_button'>Del</button>

5000

      <button class='item_button'>BUY IT</button>
      <button class='del_button'>Del</button>

RECYCLE

      <address></address>

TOTAL SUMM

      <button id='clear'>CLEAR RECYCLE</button>

YOUR RECYCLE IS CLEAR


text:
Q: LocalDate to GregorianCalendar conversion I am trying to convert LocalDate to GregorianCalendar but GregorianCalendar output is giving me date which is one day before compare to LocalDate.
Below is the code snippet:
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.GregorianCalendar;

public class Test {
    public static void main(String[] arg){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        final LocalDate localDate = LocalDate.now(ZoneId.of("Australia/Victoria")).withDayOfMonth(16).withMonth(10).withYear(2017);
        final GregorianCalendar gregorianCalendar = GregorianCalendar.from(localDate.atStartOfDay(ZoneId.of("Australia/Victoria")));
        System.out.println(format.format(gregorianCalendar.getTime())); //prints 2017-10-15
    }
}

Issue comes when code runs on machine which has timezone other than "Australia/Victoria".
Can anyone please help me to point out what wrong I am doing?

A: tl;dr
You are mixing terrible legacy classes with modern java.time classes. Don't do that.
LocalDate
.parse( "2017-10-16" )
.atStartOfDay(
    ZoneId.of( "Australia/Victoria" )
)

If you must use the terrible GregorianCalendar class, use the new conversion method added to the old class.
GregorianCalendar  // Terrible legacy class. Use only if you *must*.
.from(
    LocalDate
    .parse( "2017-10-16" )
    .atStartOfDay(
        ZoneId.of( "Australia/Victoria" )
    )
)

Details
Your code is a strange mish-mash of the terrible legacy date-time classes ( SimpleDateFormat, GregorianCalendar ) with the modern java.time classes that supplanted them ( LocalDate ).
Specifically, ZonedDateTime replaced GregorianCalendar.
A LocalDate represents only a date, without time-of-day and without time zone. In contrast, a ZonedDateTime (and GregorianCalendar) represents a moment: a date, a time-of-day, and a time zone.
Start with a LocalDate.
LocalDate ld = LocalDate.parse( "2017-10-16" ) ;

Specify a time-of-day.
LocalTime lt = LocalTime.of( 15 , 30 ) ;  // 3:30 PM.

Specify the time zone you have in mind.
ZoneId z = ZoneId.of( "Australia/Victoria" ) ;

Combine to get a ZonedDateTime, a moment, a specific point on the timeline.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;

Or perhaps you want to use the first moment of the day as the time-of-day component. Do not hard-code this as 00:00:00. Some dates in some zones start at another time such as 01:00:00. Let java.time determine the first moment.
ZonedDateTime zdt = ld.atStartOfDay( z ) ;  // Determine the first moment of the day on that date in that zone.

See that same moment in UTC. Extract a Instant, which is always in UTC.
Instant instant = zdt.toInstant() ;

Notice that all of the above code comes from the java.time package family of classes.
Avoid GregorianCalendar wherever possible. But if you must interoperate with old code not yet updated to java.time, convert. Look to new to…/from… conversion methods added to old classes. In this case, see GregorianCalendar.from.
GregorianCalendar gc = GregorianCalendar.from( zdt ) ;

A: Set TimeZone to SimpleDateFormat like
public class Test {
    public static void main(String[] arg){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        ZoneId zoneId = ZoneId.of("Australia/Victoria");
        format.setTimeZone(TimeZone.getTimeZone(zoneId));
        final LocalDate localDate = LocalDate.now(zoneId).withDayOfMonth(16).withMonth(10).withYear(2017);
        final GregorianCalendar gregorianCalendar = GregorianCalendar.from(localDate.atStartOfDay(zoneId));
        System.out.println(format.format(gregorianCalendar.getTime())); //prints 2017-10-16
    }
}


text:
Q: SQL/PHP Database Connection to Client Side Display I've been starting to program in PHP, and I want to create a program that allows any visitor to click a button and have it increment a universal counter. Eg, a user clicks the button, the counter increments by 1, and you can refresh the page and that new number will have "stuck".
My thought was to use a database that would hold the current number of "clicks" and display it, then use a client-side JavaScript button to increment the database's value. I am able to access my database and get the current number of clicks held there statically, but I'm at a loss as to having the counter be interactional. I've tried googling around to see how to do this in JavaScript, and the results have been minimal. Are my goals even achievable in JavaScript? Or should I use a different language to connect my server-side ops with my client-side ones?
// connects to the database using hostname, user, pass, db name
$connect = mysqli_connect('HOSTNAME','USER','PASSWORD','epiz_33276135_ducks');

if (!$connect) {
    echo 'problem connecting to database';
}

//takes the query
$query = "SELECT Count,ID,AnimalName FROM ducks WHERE ID=1";

//connects result adn records it
$result = mysqli_query( $connect, $query);
$record = mysqli_fetch_assoc( $result);
if (!$result) {
    echo 'smthin weird';
}
echo '
'.$record['Count'].'
';

From my understanding, PHP is for server-side operations, and Javascript is for client-side work. Googling hasn't generated any answers, and I haven't been able to find a way that can edit hte

A: Typically, you'd have your client-side code make a request to a PHP script that increments the count and responds with the new value. You can either use a form which results in a full page load or use an asynchronous request for a more seamless experience.
On the front-end, you'd use something like this
<button id="increment-counter" type="button">Increment Counter</button>

// Add a "click" event listener to the button
document
  .getElementById("increment-counter")
  .addEventListener("click", async () => {
    // Make a PUT request to your PHP
    // The `method` probably isn't important but a GET request seemed wrong
    const res = await fetch("increment-counter.php", { method: "PUT" });

    // Check for any errors
    if (!res.ok) {
      throw new Error(
        `Increment counter failed: ${res.statusText} - ${await res.text()}`
      );
    }

    // now update the current count in-place
    document.querySelector("h2").textContent = (await res.json()).Count;
  });

On the server-side, something like this (and I'm using PDO because it's more beginner-friendly than MySQLi)
// increment-counter.php
if ($_SERVER['REQUEST_METHOD'] !== 'PUT') {
    // Only allow PUT requests
    http_response_code(405);
    exit;
}

// Connect to your DB
$pdo = new \PDO(
    'mysql:host=HOSTNAME;dbname=epiz_33276135_ducks',
    'USER',
    'PASSWORD',
    [
        \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
        \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
        \PDO::ATTR_EMULATE_PREPARES   => false,
    ]
);

$pdo->beginTransaction(); // atomic updates are important
try {
    // Select the current Count
    $count = $pdo
        ->query('SELECT `Count` FROM ducks WHERE ID = 1 FOR UPDATE')
        ->fetchColumn();

    // Update your Count column
    $pdo->exec('UPDATE ducks SET `Count` = `Count` + 1 WHERE ID = 1');

    $pdo->commit();

    // Respond with a JSON object containing the updated count
    header('content-type: application/json');
    echo json_encode(['Count' => $count + 1]);
    exit;
} catch ($err) {
    $pdo->rollBack();
    throw $err;
}

A: Learn one language at a time. PHP in this context writes HTML so you simply need to implement a page transition - i.e. fetch new html from the server....
<?php
$connect = mysqli_connect('HOSTNAME','USER','PASSWORD','epiz_33276135_ducks');

if (!$connect) {
    echo 'problem connecting to database';
}

//takes the query
$query = "SELECT Count,ID,AnimalName FROM ducks WHERE ID=1";

//connects result adn records it
$result = mysqli_query( $connect, $query);
$record = mysqli_fetch_assoc( $result);
if ($result) {
    $query="UPDATE ducks SET `Count`=`Count`+1";
    mysqli_query( $connect, $query);
} else {
    echo 'smthin weird: ' mysqli_error($result);
}

echo "
$record[Count]
";
echo "next";

Once you've got this working, have a look at HTML forms.
BTW its bad practice to use reserved words (Count) for attribute names.


text:
Q: Variable won't update using chrome storage API in a Chrome App I'm struggling with a piece of code. I'm new in javascript and I've been searching for a couple of days and can't find the answer.
I'm writing a Chrome App using AngularJs and the Chrome Storage API for storing two objects with information for offline usage. I have successfully written the data into the Chrome Storage and even have retrieved it, the only problem is, the variables in which I am storing that retrieved data won't update my html page.
This is the code I'm using for getting the data previously stored on with the Chrome Storage API:
   chrome.storage.local.get(null, function(result){

      app.headers = result.headersData;
      console.log('Headers recuperados');
      console.log(app.headers);

      app.maestros = result.maestrosData;
      console.log('Maestros recuperados');
      console.log(app.maestros);
  });

My html file has {{controller.maestros}} and the logs shows that the data was retrieved, but it won't reflect on the data showed.
Thank you very much in advance!

A: shouldn't you save those two vaues in the $scope and mark your html elements to be bound to that? e.g.
$scope.maestros = result.maestrosData

Bear in mind that, given the fact that the callback is executed outside the context of Angular, you might need to wrap your assignments with
$scope.$apply(function() {... your assignments here...})

The code would look something like this:
chrome.storage.local.get(null, function(result){

  $scope.$apply(function() {
    $scope.headers = result.headersData;
    $scope.maestros = result.maestrosData;
  }

});
that should force Angular to update those values and from your HTML file, by having something like this
<input ng-model="maestros">

you should see the updates on the UI.
Hope it helps!


text:
Q: linux pacemaker - prevent split brain since using CentOS 7, we switched from a regular heartbeat setup to pacemker.
Mainly we have IP resources that are active on one node and switch to a second node if a failover happens. Also we execute some scripts in case of a failover. Nothing special.
For resources to always start on the primary node, i use
pcs constraint location Cluster_IP prefers server1=master-server

I also use
pcs resource defaults resource-stickiness=INFINITY

to prevent resources moving back after failover.
This works fine for me, if the master fails (hardware failure for example).
Since its not a problem for me if the failover takes some time, i would like to implement some kind of delay in case of a short split brain.
Before doing anything, the slave should wait ~2 Minutes, before it takes over, in case the master is reachable again in this ~2 Minutes.
I was wondering, what would be the best way to do it?

A: I've never set a token timeout in Corosync to anything above 10 seconds, but you could try increasing/setting the token value in your corosync.conf to 120000 (120 seconds in milliseconds). token should be defined in the totem{} section of your corosync.conf; man corosync.conf for more detail.
That should prevent Corosync from declaring a node dead for 120s when the network flakes out.

A: You can change the monitor interval of the resource with op monitor interval=Ns where N is the number of seconds, and then set the migration-threshold on the resource to 2. Keep in mind with a setting of 120s you could see a total delay of 120-240s depending on when the initial failure occurs in the monitoring interval.
There are other caveats to this, in that the failure counter applied to migration-threshold does not reset on success. To do that you would also need to set failure-timeout or manually intervene.
With op monitor interval=120s, migration-threshold=2, failure-timeout=121s and your resource-stickiness setting, you would need to test to ensure this provides the functionality you expect and how the failure counters behave when the original master recovers. It could require manual intervention but I'm not 100% certain on that


text:
Q: Why this equation is true? Pardon my ignorance. I don't know enough calculus to understand this. I assume this is a very easy question for this amazing site. I saw this on the The Theory of Riemann Zeta Function Book.
$$\sum_{n=2}^{\infty}\pi (n)\int_{n}^{n+1}\frac{s}{x(x^{s}-1)}dx =s\int_{2}^{\infty}\frac{\pi (x)}{x(x^{s}-1)}dx$$
where $\pi(n)$ is the prime counting function.
Can someone explain to me how did that sum symbol get lost?

A: First, remember that if $a<b<c$, then $\int_{a}^{c}f\left(x\right)\;dx=\int_{a}^{b}f\left(x\right)\;dx+\int_{b}^{c}f\left(x\right)\;dx$. Also, since $\pi$ is constant on $\left[n,n+1\right)$, you can push it into the integral as $\pi\left(x\right)$. Then, if you look at the partial sums, at the $n$th term, you have
$$\pi\left(2\right)\int_{2}^{3}\frac{s}{x\left(x^{s}-1\right)}dx+\pi\left(3\right)\int_{3}^{4}\frac{s}{x\left(x^{s}-1\right)}dx+\cdots+\pi\left(n\right)\int_{n}^{n+1}\frac{s}{x\left(x^{s}-1\right)}dx=\\s\int_{2}^{3}\frac{\pi\left(x\right)}{x\left(x^{s}-1\right)}dx+s\int_{3}^{4}\frac{\pi\left(x\right)}{x\left(x^{s}-1\right)}dx+\cdots+s\int_{n}^{n+1}\frac{\pi\left(x\right)}{x\left(x^{s}-1\right)}dx=\\s\int_{2}^{n+1}\frac{\pi\left(x\right)}{x\left(x^{s}-1\right)}dx.$$
The sum is just
$$\lim_{n\to\infty}s\int_{2}^{n+1}\frac{\pi\left(x\right)}{x\left(x^{s}-1\right)}dx=s\int_{2}^{\infty}\frac{\pi\left(x\right)}{x\left(x^{s}-1\right)}dx.$$

A: Linearity of integral and $\pi$ is constant $\pi (n)$ on the interval $[n, n+1)$.
EDIT: Also: the set $[2, \infty)$ is broken to intervals $[n, n+1],$ that's not called linearity... (is it additivity?)


text:
Q: how to remove duplicates from an array without sorting i have an array which might contain duplicate objects.
I wonder if it's possible to find and remove the duplicates in the array:
- without sorting (strict requirement)
- without using a temporary secondary array
- possibily in O(N), with N the nb of the elements in the array
In my case the array is a Lua array, which contains tables:
t={
{a,1},
 {a,2},
 {b,1},
 {b,3},
 {a,2}
}

In my case, t[5] is a duplicate of t[2], while t[1] is not.

A: To summarize, you have the following options:

*

*time: O(n^2), no extra memory - for each element in the array look for an equal one linearly

*time: O(n*log n), no extra memory - sort first, walk over the array linearly after

*time: O(n), memory: O(n) - use a lookup table (edit: that's probably not an option as tables cannot be keys in other tables as far as I remember)

Pick one. There's no way to do what you want in O(n) time with no extra memory.

A: Can't be done in O(n) but ...
what you can do is

*

*Iterate thru the array

*For each member search forward for repetitions, remove those.

Worst case scenario complexity is O(n^2)

A: Iterate the array, stick every value in a hash, checking if the it exists first. If it does remove from original array (or don't write to the new one). Not very memory efficient, but only 0(n) since you are only iterating the array once.

A: Yes, depending on how you look at it.
You can override the object insertion to prevent insertion of duplicate items. This is O(n) per object insertion and may feel faster for smaller arrays.
If you provide sorted object insertion and deletion then it is O(log n). Essentially you always keep the list sorted as you insert and delete so that finding elements is a binary search. The cost here is that element retrieval is now O(log n) instead of O(1).
This can be also be implemented efficiently using things like red-black tree's and multitree's but at the cost of additional memory. Such implementations offer several benefits for certain problems. For example, we can have O(log n) type of behavior even very very large tables with small a small memory footprint by using nested tree's. The top level tree provides a sort of paired down overview of the dataset while subtree's provide more refined access when needed.
For example, to see this suppose we have N elements. We could partition that into n1 groups. Each of those groups could then further be partitions into n2 more groups and those groups into n2 groups. Hence we have a depth of N/n1n2...
As you can see, the product of n's can become quite huge very quickly even for small n's. If N = 1 Trillion elements and n1 = 1000, n2 = 1000, n3 = 1000 it takes only 1000 + 1000 + 1000 + 1000 s = 4000 per access time. Also, we only have 10^9 times per node memory footprint.
Compare this to the average 500 billion access time's required for a direct linear search. It is over 100 million times faster and 1000 times less memory than a binary tree but about 100 times slower! (of course there is some overhead for keeping the tree's consistent but even that can be reduced).
If we were to use a binary tree then it would have a depth of about 40. The problem is there are about 1 trillion nodes so that is a huge amount of additional memory. By storing multiple values per node(and in the above case each node actually partial values and other tree's) we can significantly reduce the memory footprint but still have impressive performance.
Essentially linear access prevails at lower numbers and tree's prevail at high numbers. Tree's. Tree's consume more memory. By using multitree's we can combine the best of both worlds by using linear access over smaller numbers and having a larger number of elements per node(compared to binary tree's).
Such tree's are not trivial to create but essentially follow the same algorithmic nature of standard binary tree's, red-black tree's, AVL tree's, etc...
So if you are dealing with large datasets it is not a huge issue for performance and memory. Essentially, as you probably know, as one goes up the other goes down. Multitree's, sort of find the optimal medium. (assuming you chose your node sizes correctly)

The depth of the multitree is N/product(n_k,k=1..m). The memory footprint is the number of nodes which is product(n_k,k=1..m) (which can generally be reduced by an order of magnitude or possibly n_m)


text:
Q: subprocess.call on path with space the string that contains a file looks like this in the console:
>>> target_file
'src//data//annual_filings//ABB Ltd//ABB_ar_2015.pdf'

I got the target_file from a call to os.walk
The goal is to build a command to run in subprocess.call
Something like:
from subprocess import call

cmd_ = r'qpdf-7.0.0/bin/qpdf --password=%s --decrypt %s %s' %('', target_file, target_file)
call([cmd_])

I tried different variations, setting shell to either True or False.
Replacing the // with /,\ etc.
The issue seems to be with the space in the folder (I can not change the folder name).
The python code needs to run on Windows

A: you have to define cmd_ as a list of arguments not a list with a sole string in it, or subprocess interprets the string as the command (doesn't even try to split the args):
cmd_ = ['qpdf-7.0.0/bin/qpdf','--password=%s'%'','--decrypt',target_file, target_file]
call(cmd_)

and leave the quoting to subprocess
As a side note, no need to double the slashes. It works, but that's unnecessary.


text:
Q: Create document from dotx template with Apache POI HWPF I would like to crate new document from existing dotx template.
I tried couple of ways listed here - How can I use predefined formats in DOCX with POI? But none of them work.
Setting styles has no affect whatsoever.
XWPFDocument template = new XWPFDocument(new FileInputStream(new File("template.dotx")));

XWPFDocument doc = new XWPFDocument();
XWPFStyles newStyles = doc.createStyles();
newStyles.setStyles(template.getStyle());

XWPFParagraph para = doc.createParagraph();
para.setStyle("Heading1");

XWPFRun run = para.createRun();
run.setText("Heading 1");

Creating document directly from template corrupts newly created document and MS Word fails to open it. Complaining that there is a problem inside the document, without any specific details.
XWPFDocument document = new XWPFDocument(new FileInputStream("template.docx");

Any ideas?

A: The easiest way I have found to accomplish this is to use the "replaceContentType" method of the OPCPackage.
OPCPackage pkg = OPCPackage.open(src.getAbsolutePath());
pkg.replaceContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");
pkg.save(dest);

In the above code both "src" and "dest" are java "File" objects.
Once you have saved the file you can then open it up as an XWPFDocument and perform whatever type of additional manipulation you desire.


text:
Q: ExecuteNonQuery() returns -1 when execute the stored procedure I'm trying to execute stored procedure in Visual Studio. Its given below.
CREATE PROCEDURE [dbo].[addStudent]
    @stuName varchar(50),
    @address varchar(100),
    @tel varchar(15),
    @etel varchar(15),
    @nic varchar (10),
    @dob date

AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @currentID INT
    DECLARE @existPerson INT
    SET @existPerson = (SELECT p_ID FROM Student WHERE s_NIC = @nic);
    IF @existPerson = null
        BEGIN
            INSERT INTO Person (p_Name, p_RegDate, p_Address, p_Tel, p_EmergeNo, p_Valid, p_Userlevel)
            VALUES (@stuName,  GETDATE(), @address, @tel, @etel, 0, 'Student' );
            SET @currentID = (SELECT MAX( p_ID) FROM Person);
            INSERT INTO Student (p_ID, s_Barcode, s_DOB, s_NIC) VALUES (@currentID , NULL, @dob, @nic);
            return 0;
        END
    ELSE
        return -1;
END

Im doing so by using this code below.
        SqlConnection con = new SqlConnection();
        Connect conn = new Connect();
        con = conn.getConnected();
        con.Open();
        cmd = new SqlCommand("addStudent", con);
        cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@stuName", SqlDbType.VarChar).Value = nameTxt.Text.ToString();
                cmd.Parameters.Add("@address", SqlDbType.VarChar).Value = addressTxt.Text.ToString();
                cmd.Parameters.Add("@tel", SqlDbType.VarChar).Value = telTxt.Text.ToString();
                cmd.Parameters.Add("@etel", SqlDbType.VarChar).Value = emerTxt.Text.ToString();
                cmd.Parameters.Add("@nic", SqlDbType.VarChar).Value = nicTxt.Text.ToString();
                cmd.Parameters.Add("@dob", SqlDbType.DateTime).Value = dobTime.Value.ToString("MM-dd-yyyy");

                    int n = cmd.ExecuteNonQuery();
                    MessageBox.Show(n.ToString());

But it returns me -1. I tried this stored procedure by entering the same values I captured from debugging. It was successful. What can be the possible error?
Thanks a lot!

A: Don't use = null, use is null
IF @existPerson is null

When you compare anything = null the result is always false (unless you have set ansi_nulls off, which you shouldn't, as such an option is deprecated)
Even better, you can use
IF NOT EXISTS (SELECT p_ID FROM Student WHERE s_NIC = @nic)

Also, you should use SCOPE_IDENTITY() instead of SET @currentID = (SELECT MAX( p_ID) FROM Person);
SET @currentID = SCOPE_IDENTITY()

Finally you also need to add a parameter to collect the return value
   SqlParameter retValue = cmd.Parameters.Add("return", SqlDbType.Int);
   retValue.Direction = ParameterDirection.ReturnValue;

then
MessageBox.Show(retValue.Value);

A: Let's have a look at the documentation for ExecuteNonQuery:

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. ... For all other types of statements, the return value is -1.

You're calling a stored procedure, which, in and of itself, is none of the 3 listed statements where a row count is returned.

If you want to determine the value that was passed to a return statement within the stored procedure, you need to add another parameter to the command, and set its Direction property to ReturnValue (the name you give to this parameter will be ignored)

A: To resolve this problem just remove "SET NOCOUNT ON" or Change it to "SET NOCOUNT OFF". and everything works fine!


text:
Q: Python - Create new log files after interval of 10 minutes I want to set up a new log file after a certain interval of suppose say 10 minutes and all the logs should go in the new log file.
I am having logger.py defined like this -
import logging
import os

class Logger():
    loggers = {}
    logger = None
    def getlogger(self,name):
        file_formatter = logging.Formatter('%(asctime)s %(levelname)s [%(module)s : %(funcName)s] : %('
                                           'message)s')

        console_formatter = logging.Formatter('%(levelname)s -- %(message)s')
        print(os.getcwd())
        file_name = "src/logs/"+name+".log"
        file_handler = logging.FileHandler(file_name)
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(file_formatter)

        logger = logging.getLogger(name)
        logger.addHandler(file_handler)
        logger.setLevel(logging.DEBUG)
        logger.propagate = False
        self.loggers[name] = logger

        return logger

    def getCommonLogger(self):
        if self.loggers.get("dashboard_asset_logs"):
            return self.loggers.get("dashboard_asset_logs")
        else:
            self.logger = self.getlogger("dashboard_asset_logs")
        return self.logger

I am having the app.py defined like this
from src.main import logger

logger_obj = logger.Logger()
logger = logger_obj.getCommonLogger()

def log_trial():
    logger.info("----------Log - start ---------------------")

if __name__ == '__main__':
    log_trial()

I am running the code like this python -m src.main.app
Can anyone tell how can the logs go to files like dashboard_asset_logs and then another file after every interval of 10 minutes?

A: What you are looking for is TimedRotatingFileHandler, for example
import logging.handlers
handler = logging.handlers.TimedRotatingFileHandler(
    filename=file_name,
    when="M",
    interval=10,
)

That handler will rotate the log file every 10 minutes.


text:
Q: Find the resultant force in a motion problem with a loop In the approximate diagram, the block with mass $m$ starts without movement in the position $P$ in the top of a hill with height $5R$. After that, the block falls down through the hill, and reaches a loop until it arrives at the position $Q$ with a height of $R$. If the loop is a circle of radius $R$ and there is no friction, what is the value of the resultant force in the point $Q$?
My try
I tried to use the law of conservation of energy in the points $P$ and $Q$, with this i get the speed, but i don't know how to continue in this problem.
Any hints?

A: My guess is that as it's a slope we''ll divide mg into components .Mg sintheta will provide linear acceleration whereas mgcostheta will provide centripetal acceleration.
Multiply by mass and u get the force .The resultant force would be the vector sum of centripetal force, and the force due to gravity.(As said in comment )

A: Hint: the net force will be the resultant of the normal force which is horizontal (equal to centripetal force) at A and obviously the weight(=mg)which acts vertically downwards.


text:
Q: How to achive below output using sql query in oracle 11g.? I have table with below data :
Block_id       Value
1             5
2             5
3             5
4             0
5             0
6             4
7             4

And I have to write query that give me below output :
Block_id
   1-3
   6-7

How to achieve this with pl/sql in Oracle 11g ?

A: you can do something like:
SQL> select * from data order by block_id;

  BLOCK_ID      VALUE
---------- ----------
         1          5
         2          5
         3          5
         4          0
         5          0
         6          4
         7          4
         9          5
        10          5
        12          2

SQL> select min(block_id) || '-' || max(block_id) block_range, value
  2    from (select block_id, value, max(grp) over (partition by value order by block_id) grp
  3            from (select block_id, value,
  4                         case
  5                           when lag(block_id) over (partition by value order by block_id) < block_id - 1
  6                           then
  7                             row_number() over (partition by value order by block_id)
  8                           when row_number() over (partition by value order by block_id) = 1 then 1
  9                           else null
 10                         end grp
 11                    from data
 12                   where value != 0))
 13   group by value, grp
 14   order by min(block_id);

BLOCK_RANG      VALUE
---------- ----------
1-3                 5
6-7                 4
9-10                5
12-12               2

A: You do not need PL/SQL to do this, a simple query will do:
CREATE TABLE test(
    a   INTEGER,
    b   INTEGER
);

INSERT INTO test VALUES (1, 5);
INSERT INTO test VALUES (2, 5);
INSERT INTO test VALUES (3, 5);
INSERT INTO test VALUES (4, 0);
INSERT INTO test VALUES (5, 0);
INSERT INTO test VALUES (6, 4);
INSERT INTO test VALUES (7, 4);

select min(a) || '-' || max(a) from test group by b order by 1;

A: An alternative approach is to use aggregate functions:
select distinct
        min(block_id) over (partition by value) || '-' ||
        max(block_id) over (partition by value)
   from whatever_your_table_is_called
   where value > 0;


text:
Q: Configure ethernet interface to accept unidirectional ethernet With switches you can configure an ethernet port to be unidirectional. This gives you the ability to double your traffic capabilities.
Can I configure my ethernet interface on a unix system to read traffic from both RX and TX signals instead of reserving half for transmission? How?
Will setting my interface in promiscuous mode enable my interface to read all packets from both RX and TX?
How can I configure a unix based system to read both TX and RX?

A: Unidirectional ethernet is actually something else entirely. You are asking about full-duplex ethernet vs. half-duplex ethernet.
Most modern ethernet ports support auto-detection for things like speed and duplex, and will negotiate the fastest speed, and full duplex (if available). Negotiation is optional in 10BASE-T and 100BASE-TX, but mandatory in 1000BASE-T.
Alternatively, you can set fixed speed and duplex on a port, but this is not recommended, and, since auto-negotiation is a requirement for 1000BASE-T, some vendors have opted to remove the ability to fix settings for that speed.
The reason you shouldn't mess with the speed and duplex setting has to do with the default duplex settings for 10BASE-T and 100BASE-TX. Both 10BASE-T and 100BASE-TX have a default of half duplex. When on side of a link is set to fixed settings, negotiation is disabled, and the other side can detect (not negotiate) the speed, but the duplex will be set at the default, half-duplex rate. This results in one side set to full duplex, and the other side at half duplex. This causes serious problems with the link, slowing the transfer rate to a crawl.
This isn't a problem for 1000BASE-T since the default duplex is full. In fact, when the standard for 1000BASE-T was debated, there was a large contingent of engineers who wanted to completely eliminate half duplex from the standard. Unfortunately, half duplex was left in, but the standard for 10GBASE-T finally eliminated the half-duplex option.


text:
Q: How to test the values of an XML file against a list of expected values? I am testing an API for a website.  I wrote a Selenium Webdriver script to change all of the fields for one customer record in the UI.
When I make a call to the API, it exports a list of customers to an XML file.
Is there a tool I can use validate that the API is exporting an XML file with the expected values for a particular record?
Sample of a record as it appears in the XML File:

<data>
<row><member_id>3bed8459-b581-52ed-0a12-53c088c55033</member_id>
<id>47ea91b3-379c-7153-1469-53c08b656327</id>
<date_modified>2014-07-12 01:11:14</date_modified>
<deleted>0</deleted>
<first_name>Aaron</first_name>
<last_name>Evddns</last_name>
<phone_mobile/>
<phone_work/>
<hire_date_c/>
<professional_designation_c>DDS</professional_designation_c>
<pte_fte_c/>
<salary_c/>
<title_1_c>Owner/Provider</title_1_c>
<gender_c>male</gender_c>
<status_c>Active</status_c>
<primary_location_c>None</primary_location_c>
<status_comments_c/>
<accreditation_c/>
<termination_date_c/>
<secondary_location_c/>
<email1>dhats@ungentaldental.com</email1>
</row>

For example:
For member_id '3bed8459-b581-52ed-0a12-53c088c55033'
validate id = '47ea91b3-379c-7153-1469-53c08b656327'
validate deleted = 0
validate first_name = 'Aaron'
validate last_name = 'Evans'

A: Well, I'm not sure about a tool to do that but you can definitely use C# XmlDocument Class to do the job. You can find the documentation here.
You can probably just iterate over the elements in your output XML and compare the values of the keys to the values you have used to fill in the data using your Webdriver script.


text:
Q: writing react components in a functional style I'm learning react and elm at the same time and the similarities made me wonder if I could write all of my react components like in the snippet bellow instead of using classes
import React from 'react';
import './App.css';

export default function App() {
  const [name, setName] = React.useState("oof")

  return (

      <Adorable name={name}/>
      <AdoreForm setName={setName}/>

  );
}

const Head = () =>
  Adorable Genator OwO

const Adorable = (props) =>
  <img src={`https://api.adorable.io/avatars/221/${props.name}@adorable.png`}/>

const AdoreForm = (props) =>

    <input onChange={(e) => props.setName(e.target.value)}/>

A: Yes you can write your code as you have shown in the snippet. You can also use arrow functions to create your app component as follows.
 const App = () => {
  const [name, setName] = React.useState("oof")

  return (

      <Adorable name={name}/>
      <AdoreForm setName={setName}/>

  );

}

export default App;

It doesn't matter what sort of method (i.e : class or functional) you are using to create components especially with the introduction of react hooks.


text:
Q: Key to Value to Key in Python Dictionary I feel this isn't the most elegant solution, but I'm looking for a way to to use values as keys in one and the same dictionary. The reasoning is that I can include multiple pieces of information in one place.
My current solution seems to work for only one of two dictionaries. I can't figure out why.

Pandas DataFrame:
import pandas as pd
df = pd.DataFrame(["BEAR ESTOX X12 S", "BEAR ESTOX X15 S", "BEAR AXP UN 3X VON", "BULL AXP UN x5 VON"], columns=["name"])

Two dictionaries:
sg = {"S":"SEG", "SG":"SEG", "SEG":"www.societegenerale.com"}
vontobel = {"VON":"Vontobel","Vontobel":"www.vontobel.com"}

issuer = sg.copy()
issuer.update(vontobel) #Combine both to one dictionary

I then do:
#Split last word in string to new column
df["issuer_spl"] = df.name.str.split().str.get(-1)

#Copy to column "issuer" and substitute abbreviations via dictionary
for i in issuer:
    df.loc[df.issuer_spl.str.contains(i), "issuer"] = issuer[i]

#Another pass in the dictionary, copying and substituting to column "website"
for w in issuer:
    df.loc[df.issuer.str.contains(w).fillna(False), "website"] = issuer[w]

Produces output:
name                    issuer_spl      issuer          website
"BEAR ESTOX X12 S"      "S"             "SEG"           "SEG"
"BEAR ESTOX X15 S"      "S"             "SEG"           "SEG"
"BULL AXP UN X3 VON"    "VON"           "Vontobel"      "www.vontobel.com"
"BEAR AXP UN X3 VON"    "VON"           "Vontobel"      "www.vontobel.com"

What am I doing wrong that makes it key only the website for "www.vontobel.com" but not "www.societegenerale.com"?
Is there an alternative way to do this which is more structured, e.g. a dictionary that also doubles as a "list" that can be accessed by [i]?

Desired output:
name                    issuer_spl      issuer       website
"BEAR ESTOX X12 S"      "S"             "SEG"        "www.societegenerale.com"
"BEAR ESTOX X15 S"      "S"             "SEG"        "www.societegenerale.com"
"BULL AXP UN X3 VON"    "VON"           "Vontobel"   "www.vontobel.com"
"BEAR AXP UN X3 VON"    "VON"           "Vontobel"   "www.vontobel.com"

A: If you add the print statement:
for w in issuer:
    print(w)
    df.loc[df.issuer.str.contains(w).fillna(False), "website"] = issuer[w]

you may see:
SEG
S
SG
VON
Vontobel

which shows that w is bound to 'S' after it is bound to 'SEG'.
Since
In [220]: df.issuer.str.contains('SEG')
Out[220]:
0     True
1     True
2    False
3    False
Name: issuer, dtype: bool

In [221]: df.issuer.str.contains('S')
Out[221]:
0     True
1     True
2    False
3    False
Name: issuer, dtype: bool

The statement
df.loc[df.issuer.str.contains(w).fillna(False), "website"] = issuer[w]

ultimately sets the first two rows with the value issuer['S'], which equals
'SEG', since w was bound to 'S' after 'SEG'.
Note that the order over which the keys of a dict are iterated is not specified
by the Python language; dict keys are not ordered. In Python3 the order may
change with each run of the program. So in Python3 your code may sometimes
"work", and sometimes not.

Instead, you could use Series.map:
import pandas as pd
df = pd.DataFrame(["BEAR ESTOX X12 S", "BEAR ESTOX X15 S", "BEAR AXP UN 3X VON", "BULL AXP UN x5 VON"], columns=["name"])

sg = {"S":"SEG", "SG":"SEG", "SEG":"www.societegenerale.com"}
vontobel = {"VON":"Vontobel","Vontobel":"www.vontobel.com"}

issuer = sg.copy()
issuer.update(vontobel) #Combine both to one dictionary

#Split last word in string to new column
df["issuer_spl"] = df.name.str.split().str.get(-1)

df['issuer'] = df['issuer_spl'].map(issuer)
df['website'] = df['issuer'].map(issuer)

print(df)

yields
                 name issuer_spl    issuer                  website
0    BEAR ESTOX X12 S          S       SEG  www.societegenerale.com
1    BEAR ESTOX X15 S          S       SEG  www.societegenerale.com
2  BEAR AXP UN 3X VON        VON  Vontobel         www.vontobel.com
3  BULL AXP UN x5 VON        VON  Vontobel         www.vontobel.com

provided the values in issuer_spl are keys in issuer. Note that this requires strict equality, whereas df.issuer_spl.str.contains(w) matches if w is a substring of a value in issuer_spl.

Alternatively, if you can define a rule to distinguish
which value in the sg, vontobel dicts represents the website, then you could process the dicts into two separate data structures, issuer and website.
For example, if a website value always starts with www or ends with .com, then
you could use
issuer = dict()
website = dict()
for dct in [sg, vontobel]:
    for key, val in dct.items():
        if val.startswith('www') or val.endswith('.com'):
            website[key] = val
        else:
            issuer[key] = val

to separate the issuer data from the website data.
In [291]: issuer
Out[291]: {'S': 'SEG', 'SG': 'SEG', 'VON': 'Vontobel'}

In [292]: website
Out[292]: {'SEG': 'www.societegenerale.com', 'Vontobel': 'www.vontobel.com'}

Then you could build the desired DataFrame without relying on exact key matches:
import pandas as pd
df = pd.DataFrame(["BEAR ESTOX X12 S", "BEAR ESTOX X15 S", "BEAR AXP UN 3X VON",
                   "BULL AXP UN x5 VON", "BEAR DAX X3 SG 2"], columns=["name"])

sg = {"S":"SEG", "SG":"SEG", "SEG":"www.societegenerale.com"}
vontobel = {"VON":"Vontobel","Vontobel":"www.vontobel.com"}

issuer = dict()
website = dict()
for dct in [sg, vontobel]:
    for key, val in dct.items():
        if val.startswith('www') or val.endswith('.com'):
            website[key] = val
        else:
            issuer[key] = val

df["issuer_spl"] = df.name.str.extract(r'(\S+\s+\S+)$')

for i in issuer:
    df.loc[df.issuer_spl.str.contains(i), "issuer"] = issuer[i]

df['website'] = df['issuer'].map(website)
print(df)

yields
                 name issuer_spl    issuer                  website
0    BEAR ESTOX X12 S      X12 S       SEG  www.societegenerale.com
1    BEAR ESTOX X15 S      X15 S       SEG  www.societegenerale.com
2  BEAR AXP UN 3X VON     3X VON  Vontobel         www.vontobel.com
3  BULL AXP UN x5 VON     x5 VON  Vontobel         www.vontobel.com
4    BEAR DAX X3 SG 2       SG 2       SEG  www.societegenerale.com

A: I believe you could also solve it by this way:
Instead of using df.issuer.str.contains, using df.issuer.str.endswith.
for w in issuer:
     df.loc[df.issuer.str.endswith(w).fillna(False), "website"] = issuer[w]


text:
Q: Create a system user without password and home directory on Centos machine I want to create system user without password and home directory. I found some similar solution but not properly get my answer. I am using a centos machine.
in ubuntu: adduser mprobe --disabled-password --system --no-create-home --group
its working but in centos it says disable-password not found.
thanks in advance.

A: AFAIK adduser isn't a coreutils command, it's just a convenience script, so it may vary drastically from distro to distro.
A quick Google search yields, that password could be disabled for an existing user with passwd -d <username>. So my recommendation would be to:
sudo -s # Enter a root shell

then:
adduser mprobe --system --no-create-home --group # Create the user in question
passwd -d mprobe # Delete its password
exit # Drop root privileges


text:
Q: Dynamic fixed navbar position I have a navbar on the side of my page and I want it to change its position from fixed to absolute at a certain point. I am basically trying to get it to appear like its been stopped by my footer as the user scrolls past it.
I am currently using this code,
$(window).scroll(function(){
    $("#myNavbar").css("top",Math.min( 562 , 1020 - $(this).scrollTop() ) );
});

This works great on one of the pages as the scroll top defined. Unfortunately I need to repeat this behavior on 12 pages all with varying heights.
How would I need to approach this, calculating percentages? Any help would be much appreciated!

A: What you want to do is get the scrollTop() position of the footer. From there, you compare the scrollTop() of the nav bar (+ nab bar height()) and as soon as the navs scrollTop() + height() > the footers scrollTop(), you change the class of the nav bar addClass('not-sticky'). Where .not-sticky{position:absolute}. Hope this helps


text:
Q: Single Click VBA code for date Excel 2010 The date shows in column A cell with a single click on cell in column A through C in that row. Is there a code for that? Here is the code I have already that shows the date when clicking anywhere in the row
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Cells(Target.Row, 1) = Date
End Sub

A: Try it as,
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    if not intersect(target, range("A:C")) is nothing then
        dim trg as range
        for each trg in intersect(target, range("A:C"))
            cells(trg.row, "A") = date
        next trg
    end if
End Sub


text:
Q: How to edit menu item's style in activity_main_drawer.xml So basically i just want to edit the style of those "menu items" which are in activity main drawer file
when i tried adding the code like android:textColor = "@color/some" ,it didn't worked
My goal is to edit the style of those menu items as i don't want to keep them so boring looking
Thanks

A: There are several ways to do this, easiest is to use <selector> in styles
But since your question is very vague and non specific I have a few links for you
Check This Question
and these YouTube Videos ,This One and This One
Sorry I can't really help you since your question doesn't supply a lot of information


text:
Q: Middle Term of List from Inputs I need to take 3 numbers and print the max, min and middle term. Here's what I wrote:
new_list = []
for i in range(3):
    new_list.append(int(input("Enter a number: ")))

x = min(new_list)
y = max(new_list)
z =

print("The max is %d, the middle is %d and the min is é %d." % (y, x , z))

But I don't know how to define z so it can be the middle term. Any help?

A: Just sort them:
x, z, y = sorted(new_list)

A: you can also do it using list comprehension.
new_list = []
for i in range(3):
    new_list.append(int(input("Enter a number: ")))

x = min(new_list)
y = max(new_list)
z = [i for i in new_list if i!=x and i!=y][0]

print("The max is %d, the middle is %d and the min is é %d." % (y, z , x))


text:
Q: How to send data in a JSON format to an HTTP End Point from a custom web page? I have created a simple custom web page using HTML and JavaScript, that allows a user to select multiple languages of their choice to translate text.
For example, lets say the user chooses English(en-US) and French(fr-FR) and clicks on "Submit". I want to take the user's request, and send that data to an [Azure Logic HTTP End Point][1]  where I have set up my JSON schema to take "languages" property of type "array". The JSON schema is defined on the HTTP Trigger like below :

A: you can check the network tab in the dev tool and from what i see is that your page is sending the data in json format. however the there is an error on parsing the response body(check out your end point's response).


text:
Q: iOS url scheme to open specific youtube page in youtube app Is there anyway to use an iOS URL Scheme to open the YouTube to a particular user's profile I've tried youtube://user/myusername but that did not seem to work.

A: To open a Youtube page in Youtube app (if it's installed on the device)
you can check whether the device can open the page:
// URL scheme for youtube app
NSString *youtubeURL = @"youtube://www.youtube.com/user/";

// Page name(or channel name)
NSString *youtubePageName = @"YourPageName";

// Check if the device can open in Youtube app or not.
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString: [youtubeURL stringByAppendingString:youtubePageName]]]){
    // Open in Youtube app
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: [youtubeURL stringByAppendingString:youtubePageName]]];
}else{
    // If device cannot open in youtube app, open the page in browser.
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http://www.youtube.com/user/YourPageName"]];
}

This solution worked for me
iOS 9 edit: Target app's URL scheme must be added to info.plist under LSApplicationQueriesSchemeskey.
Here is a related post: iOS 9 not opening Instagram app with URL SCHEME

A: This forum post's lack of responses indicates there probably isn't a way to do this currently: YouTube iOS URL Scheme for Channels
But you may be able to request that feature on YouTube's iOS app feedback page. And in the meantime, I'd recommend just linking to users' HTML YouTube pages.

A: No, few weeks ago I was looking for the same, but i didn't found anything. Instead I've opted for use a UIWebView to show the youtube channel or using the openURL: UIApplication's method to open the channel with Safari.
If you want to save some time, you can use the easy-to-implement TSMiniWebBrowser's control at this Github page.

A: Here is the youtube Channel Url scheme, try to load it in UIWebView and it will works.
http://m.youtube.com/#/user/channel_name for e.g http://m.youtube.com/#/user/whartonmagazine


text:
Q: How to remove Important dates section from Django User view? I want to remove Important dates section from django Admin User view.

Tried this:
class UserAdmin(admin.ModelAdmin):
    exclude = ('last_login', 'date_joined',)

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

But it's saying:
"Key 'last_login' not found in 'UserForm'. Choices are: email, first_name, groups, is_active, is_staff, is_superuser, last_name, password, user_permissions, username."

How to remove this section from default User view django admin.
Thanks

A: There is two way to do this:
1) You can use css:
- Inspect element in browser.
- IN css file add css for these ids:
     display:none;

2) You can use js file:
- Hide or delete the elements by their ids(Ids you find by inspecting element.)


text:
Q: The string is missing the terminator: ". powershell jenkins have a strange problem trying to automate a powershell line.
On my powershell it works but under Jenkins pipeline it always says the following error :
The string is missing the terminator: ".
+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

My code line :
powershell $mybranch = (get-content F:\software\branchname) -replace '.*?/'; new-Item -ItemType Directory -Force -Path "\\myserver\sw\software\rs\2020-RC1_$branchname"; copy-item -path "E:\Temp\2020-07-22_1.1.1-RC1_$branchname.zip" -destination "\\myserver\sw\software\rs\2020-RC1_$branchname\"

A: It's trailing backslash before double quote in … -destination "\\myserver\sw\software\rs\2020-RC1_$branchname\". Double it.
Example:
powershell -noprofile dir "packages\"

The string is missing the terminator: ".
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

powershell -noprofile dir "packages\\"

    Directory: D:\bat\packages

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        01.06.2020     10:41                com.company.sft


text:
Q: How do I get text value from a dropdown unordered list using jQuery? This is the unordered list:

     Liquor

Bourbon

Gin

Rum

Tequila

Vodka

Whiskey

   ...
</ul

And this is the code I'm using to get the text and use it as a label elsewhere on the page:
var liquor_selected  = document.querySelector('#liquor-category');
      var selected = liquor_selected.addEventListener('click',function(e){
          document.getElementById("category-name-box").innerHTML = "Liquor Sub-Category Here";
      });

It prints the generic text, but I'd like it to print the sub-category. A little help please.

A: The click handler is bound to the parent so you have to find the e.target clicked:
var liquor_selected = document.querySelector('#liquor-category');
var selected = liquor_selected.addEventListener('click', function (e) {
  document.getElementById("category-name-box").innerHTML = e.target.innerText;
});

In jQuery you can do the same:
$('#liquor-category').on('click', function (e) {
  $('#category-name-box').text($(e.target).text());
});

or you can bind to the a selector more easily in jQuery
$('#liquor-category a').on('click', function (e) {
  $('#category-name-box').text($(this).text());
});

A: I'm assuming that you want to achieve the following (in jQuery)
Example in JsFiddle: https://jsfiddle.net/282u8avw/
HTML:

Bourbon

Gin

Rum

Tequila

Vodka

Whiskey

Javascript/jQuery:
  $(document).ready(function() {
    $('#liquor-category a').click(function() {
      $('#category-name-box').text($(this).text());
    });
  })


text:
Q: How can I change the configuration of /etc/updatedb.conf file? Based on the man page of the command "updatedb", we can change and override the configuration of /etc/updatedb.conf using the below commands:
   --prune-bind-mounts FLAG
          Set PRUNE_BIND_MOUNTS to FLAG, overriding the configuration file.

   --prunefs FS
          Set PRUNEFS to FS, overriding the configuration file.

   --prunenames NAMES
          Set PRUNENAMES to NAMES, overriding the configuration file.

   --prunepaths PATHS
          Set PRUNEPATHS to PATHS, overriding the configuration file.

But when I try to use them, there is no change. For example I expect the command below to change the flag to "no", but nothing happens:
sudo updatedb --prune-bind-mounts no

Just it takes a while to execute and exits without any warnings or errors, when I check the /etc/updatedb.conf content, it's the same as before.

A: These flags don't change the configuration file; they affect the invocation of updatedb they are attached to, ignoring the configuration file.
Thus
sudo updatedb --prune-bind-mounts no

runs updatedb with PRUNE_BIND_MOUNTS set to no, regardless of the value set in the configuration file.
If you want to change /etc/updatedb.conf, edit it.


text:
Q: How to construct an in-memory virtual file system and then write this structure to disk I'm looking for a way to create a virtual file system in Python for creating directories and files, before writing these directories and files to disk.
Using PyFilesystem I can construct a memory filesystem using the following:
>>> import fs
>>> dir = fs.open_fs('mem://')
>>> dir.makedirs('fruit')
SubFS(MemoryFS(), '/fruit')
>>> dir.makedirs('vegetables')
SubFS(MemoryFS(), '/vegetables')
>>> with dir.open('fruit/apple.txt', 'w') as apple: apple.write('braeburn')
...
8
>>> dir.tree()
├── fruit
│   └── apple.txt
└── vegetables

Ideally, I want to be able to do something like:
dir.write_to_disk('<base path>')

To write this structure to disk, where <base path> is the parent directory in which this structure will be created.
As far as I can tell, PyFilesystem has no way of achieving this. Is there anything else I could use instead or would I have to implement this myself?

A: If you just want to stage a file system tree in memory, look at the tarfile module.
Creating files and directories is a bit involved:
tarblob = io.BytesIO()
tar = tarfile.TarFile(mode="w", fileobj=tarblob)
dirinfo = tarfile.TarInfo("directory")
dirinfo.mode = 0o755
dirinfo.type = tarfile.DIRTYPE
tar.addfile(dirinfo, None)

filedata = io.BytesIO(b"Hello, world!\n")
fileinfo = tarfile.TarInfo("directory/file")
fileinfo.size = len(filedata.getbuffer())
tar.addfile(fileinfo, filedata)
tar.close()

But then you can create the file system hierarchy using TarFile.extractall:
tarblob.seek(0) # Rewind to the beginning of the buffer.
tar = tarfile.TarFile(mode="r", fileobj=tarblob)
tar.extractall()

A: You can use fs.copy.copy_fs() to copy from one filesystem to another, or fs.move.move_fs() to move the filesystem altogether.
Given that PyFilesystem also abstracts around the underlying system filesystem - OSFS - in fact, it's the default protocol, all you need is to copy your in-memory filesystem (MemoryFS) to it and, in effect, you'll have it written to the disk:
import fs
import fs.copy

mem_fs = fs.open_fs('mem://')
mem_fs.makedirs('fruit')
mem_fs.makedirs('vegetables')
with mem_fs.open('fruit/apple.txt', 'w') as apple:
    apple.write('braeburn')

# write to the CWD for testing...
with fs.open_fs(".") as os_fs:  # use a custom path if you want, i.e. osfs://<base_path>
    fs.copy.copy_fs(mem_fs, os_fs)


text:
Q: Posting a json to a distant server(REST) I want to send some json data using this code to a distant server (Rest, outside my control), following the way I'm sending it :
I create the url and the request method first  :
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(gUrlDot);
        request.Method = "POST";
        Dictionary<String, String> lDictionary = new Dictionary<String, String>();
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        Dot lDot= new Dot();
        serviceContext lserviceContext = new serviceContext();
        items litems = new items();
        lDot.rad = pClient;
        lDictionary.Add("companyId", "00230");
        lDictionary.Add("treatmentDate", lGlobals.FormatDateYYYYMMDD());
        lDictionary.Add("country", "FR");
        lDictionary.Add("language", "fr");
        lDictionary.Add("Id", "test");

        litems.contextItem = lDictionary;
        lDot.serviceContext = lserviceContext;
        lDot.serviceContext.items = litems;
        String Input=_Tools.JsonSerializer(lDot);
        log.Debug("Input Dot " + Input);

        Byte[] byteArray = encoding.GetBytes(Input);

        request.ContentLength = byteArray.Length;
        request.ContentType = @"application/json";

        using (Stream dataStream = request.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);
        }

        long length = 0;

When i'm getting here it crashes with an execption : Error 500 !
        try
        {
          using (var response = (HttpWebResponse)request.GetResponse())
            {
                length = response.ContentLength;
                string output = response.ToString();
                lTrace.AppendLine("-Flux Json recu => " + response.StatusCode + "  " + length);
                log.Debug("Output Dot " + output);

            }
           log.Info(LogsHelper.LogHeader("End processing Get list  ", pClient, Service.SrvGetList, "", lResponse.StatusCode, lResponse.StatusLabel, lResponse.ResponseObject, ref lTrace));

        }
        catch (Exception ex)
        {
            lResponse.StatusCode = StatusCodes.ERROR_COMMUNICATION;
            log.Error(LogsHelper.LogHeader("End processing Get list", pClient, Service.SrvGetList, "", lResponse.StatusCode, ex.Message, lResponse.ResponseObject, ref lTrace));
        }

        return lResponse;
    }

what am i missing here?

A: A 500 error means there's a problem on the server you're making the request to.  You'll need to check to make sure two things;
1) Make sure your request is properly formatted, and doesn't have any surprises or invalid values for the requested resource.
2) that the server you want to talk to CAN get requests, and that its up-to-date (if you control the client).
In either case, the most common reason for a 500 is that something outside of your control has gone wrong on the client server.


text:
Q: How to sum values in typescript array based on array items property? I'm working on small angular project. I have an array of receipt items, e.g. coke, fanta, pepsi, juice etc, with their prices and quantity of course.
receiptItems: Array<ReceiptItem>;

This is how ReceiptItem looks :
export class ReceiptItem {

  public id: string;
  public product: Product;
  public unitOfMeasure: UnitOfMeasure;
  public discount: number;
  public price: number;
  public quantity: number;
  public total: number;
  public tax:Tax;

 }

How can I in typescript get sum of total amount but only where property tax for example is equal to "25%"?
In C# I remember I've used lambda expressions like this:
IEnumerable<ReceiptItems> results = receiptItems.Where(s => s.Tax == "25.00");
   totalSum = results.Sum(x => (x.TotalAmount));

How to achieve something similar in TypeScript / Angular?

A: Arrays in JavaScript/TypeScript also have these kind of methods. You can again filter with you condition and then use reduce aggregation function to sum the items.
const sum = receiptItems.filter(item => item.tax === '25.00')
                        .reduce((sum, current) => sum + current.total, 0);

item.tax === '25.00' - this part you must adjust with your logic


text:
Q: How to get table field name from a FormBuildStringControl control I would like to ask how I can take the physical table field Name from  a FormBuildStringControl.
Genarally I could say that I have to loop all string controls of a form.
and find the correcponding Table field Names.
At first I achive to navigate through all controls with the help of the following link. Loop form fields
The first part works like a charm and I can navigate into form controls without any promlems, but  my Problem is when I would like to find the Table fieldName.
     switch(control.handle())
       {
          case classnum(FormBuildStringControl):

          FormBuildStringControl   formBuildStrControl =Control FormBuildStringControl;
          str name = formBuildStrControl.name();
          info( formBuildStrControl.name()); // THE CORRECT VALUE  CustTable_CustAccount

          info(fieldId2Name(formBuildStrControl.dataSource(),formStrControl.Datafield()));// THE FALSE VALUE ORDERID

         info(tableId2Name(formBuildStrControl.dataSource()))// false  value SalesLine

         break;
    }

I have not the excpected results from the methods fieldId2Name(), and tableId2Name(). the reason is the datadield and the datasource() methods does not return the corrects IDs from the SalesTable and from CustAccount
Have someone any suggestion how I can get out the correct table field Name from a FormBuildStringControl ?
Thanks
Nikos.

A: The problem is with your value formStrControl.dataSource().
Change that to formStrControl.dataSourceObject().table().
Something you may find more useful is FieldBinding from formStringControl.fieldBinding(), which provides all of the information you'd probably want.
Here's some code that shows what I'm talking about:
FormStringControl           fsc;
FieldBinding                fieldBinding;

// Using your current method
fsc = element.control(element.controlId('CustTable_AccountNum'));
info(strFmt("%1", fieldId2name(fsc.dataSourceObject().table(), fsc.dataField())));

// Using Field Binding
fieldBinding = fsc.fieldBinding();
info(strFmt("%1, %2, %3", fieldBinding.fieldId(), fieldBinding.fieldName(), fieldBinding.tableId()));

A: I would like to post my solution for my question which come out from the post of @Alex Kwitny
                case classnum(FormBuildStringControl):

                FormStringControl        fsc =  new FormStringControl(control as FormBuildStringControl,_formRun)  ;
                FieldBinding             fieldBinding;

                fieldBinding = fsc.fieldBinding();
                info(strFmt("%1, %2, %3", fieldId2Name(fieldBinding.tableId(),fieldBinding.fieldId()), fieldBinding.fieldName(), tableId2Name( fieldBinding.tableId())));

                 _this.add(fieldBinding.fieldId());

                 break;