text:
Q: "Illegal instruction: 4" shows up in OS X Lion Some C++ application compiled and run seamlessly in OS X Snow Leopard, but I changed recently to OS X Lion, and here, although there is no compilation error, when I try to run it I get the error "Illegal instruction: 4", I have no clue, what could be the reason?
PS:
These are the linking flags I use
-Wl,-stack_size,0x10000000,-stack_addr,0xc0000000

This is the output I get when I do sudo truss executable
setrlimit returned result = -1
    SYSCALL(args)        = return
getpid(0x0, 0x0, 0x0)        = 32993 0
__sysctl(0xBFFFF5EC, 0x3, 0xBFFFF5E8)        = 0 0
issetugid(0xBFFFF5EC, 0x3, 0xBFFFF5E8)       = 0 0
csops(0x0, 0x0, 0xBFFFF65C)      = 0 0
shared_region_check_np(0xBFFFD5E0, 0x0, 0xBFFFF65C)      = 0 0
stat64("/usr/lib/dtrace/libdtrace_dyld.dylib\0", 0xBFFFE830, 0xBFFFF65C)         = 0 0
open("/usr/lib/dtrace/libdtrace_dyld.dylib\0", 0x0, 0x0)         = 3 0
pread(0x3, "\312\376\272\276\0", 0x1000, 0x0)        = 4096 0
pread(0x3, "\316\372\355\376\a\0", 0x1000, 0x6000)       = 4096 0
mmap(0x4D3000, 0x2000, 0x1, 0x12, 0x3, 0x3)      = 0x4D3000 0
mmap(0x4D5000, 0x1000, 0x3, 0x12, 0x3, 0x3)      = 0x4D5000 0
mmap(0x4D6000, 0x1EF0, 0x1, 0x12, 0x3, 0x3)      = 0x4D6000 0
close(0x3)       = 0 0
stat64("/usr/lib/libstdc++.6.dylib\0", 0xBFFFE690, 0x1)      = 0 0
stat64("/usr/lib/libgcc_s.1.dylib\0", 0xBFFFE690, 0x1)       = 0 0
stat64("/usr/lib/libSystem.B.dylib\0", 0xBFFFE560, 0x1)      = 0 0
stat64("/usr/lib/libc++abi.dylib\0", 0xBFFFE5D0, 0x1)        = 0 0
stat64("/usr/lib/system/libcache.dylib\0", 0xBFFFE360, 0x1)      = 0 0
stat64("/usr/lib/system/libcommonCrypto.dylib\0", 0xBFFFE360, 0x1)       = 0 0
stat64("/usr/lib/system/libcompiler_rt.dylib\0", 0xBFFFE360, 0x1)        = 0 0
stat64("/usr/lib/system/libcopyfile.dylib\0", 0xBFFFE360, 0x1)       = 0 0
stat64("/usr/lib/system/libdispatch.dylib\0", 0xBFFFE360, 0x1)       = 0 0
stat64("/usr/lib/system/libdnsinfo.dylib\0", 0xBFFFE360, 0x1)        = 0 0
stat64("/usr/lib/system/libdyld.dylib\0", 0xBFFFE360, 0x1)       = 0 0
stat64("/usr/lib/system/libkeymgr.dylib\0", 0xBFFFE360, 0x1)         = 0 0
stat64("/usr/lib/system/liblaunch.dylib\0", 0xBFFFE360, 0x1)         = 0 0
stat64("/usr/lib/system/libmacho.dylib\0", 0xBFFFE360, 0x1)      = 0 0
stat64("/usr/lib/system/libmathCommon.A.dylib\0", 0xBFFFE360, 0x1)       = 0 0
stat64("/usr/lib/system/libquarantine.dylib\0", 0xBFFFE360, 0x1)         = 0 0
stat64("/usr/lib/system/libremovefile.dylib\0", 0xBFFFE360, 0x1)         = 0 0
stat64("/usr/lib/system/libsystem_blocks.dylib\0", 0xBFFFE360, 0x1)      = 0 0
stat64("/usr/lib/system/libsystem_c.dylib\0", 0xBFFFE360, 0x1)       = 0 0
stat64("/usr/lib/system/libsystem_dnssd.dylib\0", 0xBFFFE360, 0x1)       = 0 0
stat64("/usr/lib/system/libsystem_info.dylib\0", 0xBFFFE360, 0x1)        = 0 0
stat64("/usr/lib/system/libsystem_kernel.dylib\0", 0xBFFFE360, 0x1)      = 0 0
stat64("/usr/lib/system/libsystem_network.dylib\0", 0xBFFFE360, 0x1)         = 0 0
stat64("/usr/lib/system/libsystem_notify.dylib\0", 0xBFFFE360, 0x1)      = 0 0
stat64("/usr/lib/system/libsystem_sandbox.dylib\0", 0xBFFFE360, 0x1)         = 0 0
stat64("/usr/lib/system/libunc.dylib\0", 0xBFFFE360, 0x1)        = 0 0
stat64("/usr/lib/system/libunwind.dylib\0", 0xBFFFE360, 0x1)         = 0 0
stat64("/usr/lib/system/libxpc.dylib\0", 0xBFFFE360, 0x1)        = 0 0
open("/dev/dtracehelper\0", 0x2, 0xBFFFF5B0)         = 3 0
ioctl(0x3, 0x80086804, 0xBFFFF540)       = 0 0
close(0x3)       = 0 0
__sysctl(0xBFFFF1FC, 0x2, 0xBFFFF1F4)        = 0 0
bsdthread_register(0x92C9F6BC, 0x92C9F6E0, 0x1000)       = 0 0
thread_selfid(0x92C9F6BC, 0x92C9F6E0, 0x1000)        = 2500945 0
mmap(0x0, 0x2000, 0x3, 0x1002, 0x1000000, 0xAC308375)        = 0x4D8000 0
mprotect(0x4D8000, 0x44, 0x1)        = 0 0
mmap(0x0, 0xD000, 0x3, 0x1002, 0x1000000, 0x4D8034)      = 0x4DA000 0
mprotect(0x4DA000, 0x1000, 0x0)      = 0 0
mprotect(0x4E6000, 0x1000, 0x0)      = 0 0
mmap(0x0, 0xD000, 0x3, 0x1002, 0x1000000, 0x4DB000)      = 0x4E7000 0
mprotect(0x4E7000, 0x1000, 0x0)      = 0 0
mprotect(0x4F3000, 0x1000, 0x0)      = 0 0
mmap(0x0, 0x1000, 0x3, 0x1002, 0x1000000, 0x4E8000)      = 0x4F4000 0
mprotect(0x4F4000, 0x1000, 0x1)      = 0 0
mprotect(0x4D8000, 0x44, 0x3)        = 0 0
mmap(0x0, 0x200000, 0x3, 0x1002, 0x7000000, 0x4F4000)        = 0x4F5000 0
munmap(0x4F5000, 0xB000)         = 0 0
munmap(0x600000, 0xF5000)        = 0 0
mprotect(0x4D8000, 0x44, 0x1)        = 0 0
getpid(0x4D8000, 0x44, 0x1)      = 32993 0
__mac_syscall(0x973E8E8E, 0x2, 0xBFFFF0C8)       = 0 0
stat64("/AppleInternal\0", 0xBFFFF130, 0xBFFFF0C8)       = -1 Err#2
audit_session_self(0x92C1F4B6, 0xBFFFF130, 0xBFFFF0C8)       = 5635 0
geteuid(0x92C1F4B6, 0xBFFFF130, 0xBFFFF0C8)      = 0 0
getegid(0x92C1F4B6, 0xBFFFF130, 0xBFFFF0C8)      = 0 0
getaudit_addr(0xBFFFF0A8, 0x30, 0xBFFFF0C8)      = 0 0
csops(0x80E1, 0x7, 0xBFFFECF8)       = 0 0
mmap(0x0, 0x2000, 0x3, 0x1002, 0x1000000, 0xACA5EB00)        = 0x4F5000 0
mprotect(0x4F5000, 0x44, 0x1)        = 0 0
mmap(0x0, 0xD000, 0x3, 0x1002, 0x1000000, 0x4F5034)      = 0x600000 0
mprotect(0x600000, 0x1000, 0x0)      = 0 0
mprotect(0x60C000, 0x1000, 0x0)      = 0 0
mmap(0x0, 0xD000, 0x3, 0x1002, 0x1000000, 0x601000)      = 0x60D000 0
mprotect(0x60D000, 0x1000, 0x0)      = 0 0
mprotect(0x619000, 0x1000, 0x0)      = 0 0
mprotect(0x4F4000, 0x1000, 0x3)      = 0 0
mprotect(0x4F4000, 0x1000, 0x1)      = 0 0
mprotect(0x4F5000, 0x44, 0x3)        = 0 0
mmap(0x0, 0x200000, 0x3, 0x1002, 0x7000000, 0x4F4004)        = 0x61A000 0
munmap(0x61A000, 0xE6000)        = 0 0
munmap(0x800000, 0x1A000)        = 0 0
mprotect(0x4F5000, 0x44, 0x1)        = 0 0
getrlimit(0x1003, 0xBFFFF8DC, 0x1)       = 0 0
setrlimit(0x1003, 0xBFFFF8DC, 0x1)       = -1 Err#22
getrlimit(0x1008, 0xBF835C60, 0x1)       = 0 0
fstat64(0x1, 0xBF836090, 0x1F)       = 0 0
mmap(0x0, 0x1000000, 0x3, 0x1002, 0x2000000, 0xACA5B3E0)         = 0x800000 0
munmap(0x1000000, 0x800000)      = 0 0

PS2: If I remove the previously mentioned linking flag, the program runs, with no error. But when I input real data to the program, then I get
Segmentation fault: 11

I remember that this program had a problem with the stack, so it had to be increased. In Linux I did this and works
       const rlim_t kStackSize = 256L * 1024L * 1024L;   // min stack size = 64 Mb
    struct rlimit rl;
    int result;

    result = getrlimit(RLIMIT_STACK, &rl);
    if (result == 0)
    {
            if (rl.rlim_cur < kStackSize)
            {
                    rl.rlim_cur = kStackSize;
                    result = setrlimit(RLIMIT_STACK, &rl);
                    if (result != 0)
                    {
                            fprintf(stderr, "setrlimit returned result = %d\n", result);
                    }
            }
    }

but in OS X, since that did not work, I used the previously mentioned linking flag, and had no problem is OS X Snow Leopard, so it seems I still have the stack overflow problem in OS X Lion but the linking flag does not solve this. What could I do?

A: In OS X Lion (but also 10.5) the stack size hard limit is 65532 kbytes (just under 64 MiB).
This can be seen with:
bswift$ ulimit -Hs
65532

Even as root, I couldn't increase this value.
The soft limit defaults to only 8 MiB:
bswift$ ulimit -Ss
8192

Try raising the value to this maximum before starting you application:
bswift$ ulimit -Ss unlimited
bswift$ ulimit -Ss
65532

Note: segmentation fault (SIGSEGV) (number 11) you observed is the signal sent to the process when the stack limit is exceeded according to man setrlimit
Note: Since the ulimit command needs to be a shell builtin, you will find it documented in man bash

A: I encountered this issue when building a product on Mountain Lion (10.8,) and then running on Lion. (10.7). The cause was that I made some changes to my build environment.
(I'm using mkbundle to ship a product that uses Mono.)
The fix was very simple, I had to tell clang that generated binaries need to work on OSX 10.6. I added the following argument to clang:
-mmacosx-version-min=10.6

Problem solved!

A: This could be a permissions issue.
To diagnose further, run your program from the terminal with sudo dtruss prefixed. See which syscall it runs before throwing the error.
Example: sudo dtruss /path/to/application
You can also diagnose it with the Xcode or GDB debuggers.


text:
Q: Git hook python script to call executable binary The image shows project structure. There is a binary executable (c++ output) which is supposed to be run by post-checkout script, and it fails.

post-checkout is python script
#!/bin/python3

import subprocess

file_path = r'../build/executable.x'
subprocess.check_call([file_path, '-list'], cwd=r'C:/code/MyProject/build')

The error that I get when running git checkout command is:

subprocess.CalledProcessError: Command '['../build/executable.x', '-list']' returned non-zero exit status 3221225785.

However if I run this script from windows cmd, it works fine.
To run it in cmd, I go to .githooks directory, and then run 'python3 post-checkout'
I am wondering if I miss setting the working directory correctly or it is git script that runs in an expected way in windows machine.

A: The problem was the python that run the script. There are two python interpreters available on my machine, one was under msys and the other one the standalone python for windows.
It seems the combination of msys python and windows git were not happy about running the binary. I tried windows python and windows git which successfully run the binary by trigger git hook.
I had to specify default python interpreter by flipping the order of env variable path, and bring up windows python to prioritize it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Generic method call code I have an interface with a bunch of methods with different signatures (context here is a WCF callback interface).  My server has a list of clients.  In response to events I want to call a method of the interface on every client.  There is a bunch of boiler plate code around this call (check client is alive, should this client be include in list to callback, try catch, drop client if operation fails etc).  Whats the best way to pull out this boiler plate code into a generic CallBackClients(SomeKindOfGenericDeligate method_to_call) where method_to_call is one of the interface methods.
ICallback {
    void Fish(string my_string);
    void SuperFish(int my_int, double my_double);
    ... etc ...
}

CallBackClients( -- ?? generic delegate ?? -- ) {
    foreach (IClientCallback client in client_list) {
        // The boiler plate code:
        if (((ICommunicationObject)client.callback).State == CommunicationState.Opened) {
            try {
               Do method call based on delagate / lamda code passed in - how ??
            }
            catch (Exception e) {
                Remove_client(client, method.ToString(), e);
            }
        }
        else
            Remove_client(client, method.ToString());
        }
    }
}

Pseudo code for caller:
void EventHandler_A() {
    // Call Fish method on all clients:
    CallBackClients(Fish("hello"));
}

void EventHandler_B() {
    // Call SuperFish method on all clients:
    CallBackClients(SuperFish(10, 5.3);
}

A: You can encapsulate a method to call later on any given IClientCallBack in an Action<IClientCallBack>:
CallBackClients(Action<IClientCallBack> actionOnDelegates) {
    foreach (IClientCallback client in client_list) {
        // The boiler plate code:
        if (((ICommunicationObject)client.callback).State == CommunicationState.Opened) {
            try {
               actionOnDelegates(client);
            }
            catch (Exception e) {
                Remove_client(client, method.ToString(), e);
            }
        }
        else
            Remove_client(client, method.ToString());
        }
    }
}

this would then be called like so; these create an anonymous method to call the method on the specified client:
void EventHandler_A() {
    // Call Fish method on all clients:
    CallBackClients(client => client.Fish("hello"));
}

void EventHandler_B() {
    // Call SuperFish method on all clients:
    CallBackClients(client => client.SuperFish(10, 5.3);
}


text:
Q: How to create this layout in Android code? UPDATE: problem solved. There is a litle bug in my real code. The below code work fine. Thanks all so so much for the supports!
==================================================================================
I have a linear layout and some text view like below. The Linear layout is in horizontall orientation. The below layout works as I want, but I want to add TextView to it dynamically, so I want to initialize it in code instead of xml. But when I do it in code, the text view appear on top of linear layout instead of bottom like I want. The xml layout file is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:baselineAligned="false">
      <TextView
           android:text="dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg dfg"
           android:layout_weight="1"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:background="#eeffee"
           android:layout_gravity="bottom"/>

      <TextView
           android:text="asd asd asd asd asd asd asd asd asd asd"
           android:layout_weight="1"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:background="#eeeeff"
           android:layout_gravity="bottom"/>

      <TextView
           android:text="qweoiu qweoiuqwe oiqwe qwoeiu qweoiu qweoiuq weoiuqw eoiquw eoiqwue oqiweu qowieu qowieu qoiweu qowieu qowieu qowieu qowieu qoiweu qowieu qoiwue "
           android:layout_weight="1"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:background="#ffeeee"
           android:layout_gravity="bottom"/>

 </LinearLayout>

My code is:
    LinearLayout container = new LinearLayout(getContext());
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    container.setLayoutParams(layoutParams);
    container.setOrientation(LinearLayout.HORIZONTAL);
    container.setBaselineAligned(false);

    TextView textView = new TextView(getContext());
    textView.setText("asgfg fgf");
    LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
    layoutParams1.gravity = Gravity.BOTTOM;
    textView.setLayoutParams(layoutParams1);
    container.addView(textView);

    TextView textView2 = new TextView(getContext());
    textView2.setText("asgfg fgf");
    LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
    layoutParams2.gravity = Gravity.BOTTOM;
    textView2.setLayoutParams(layoutParams2);
    container.addView(textView2);

    TextView textView3 = new TextView(getContext());
    textView3.setText("asgfg fgf");
    LinearLayout.LayoutParams layoutParams3 = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
    layoutParams3.gravity = Gravity.BOTTOM;
    textView3.setLayoutParams(layoutParams3);
    container.addView(textView3);

My code does not work, the Text View appear on top instead of bottom. Please help me take a look to see what I'm doing wrong. Thanks.

A: Setting gravity for TextView just says where its text should be placed - not the view. You must use layout_gravity or gravity param of layout (parent's gravity or gravity param of LayoutParams) but not TextView's gravity.
EDITED
((LinearLayout.LayoutParams)myTextView.getLayoutParams()).gravity = Gravity.BOTTOM;

EDITED AGAIN
LinearLayout container = new LinearLayout(getContext());
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.MATCH_PARENT);
layoutParams.gravity = Gravity.BOTTOM;
container.setLayoutParams(layoutParams);

A: If in your onCreate you are using
setContentView(R.layout.your_xml);

than you have to go with Deepzz answer.
or you can use
setContentView(container);


text:
Q: Parse JSON in Angular Js I need Parse to json in angularJS.
 {
    "status": true,
    "previous_status": "",
    "pass": true,
    "name": "N/A",
    "payment_date": "March 5, 2018 - 1:54 pm",
    "address": "N/A",
    "city": "N/A",
    "state": "N/A",
    "country": "N/A",
    "checksum": "1009-1",
    "custom_fields": [
        [
            "Ticket Type",
            "Friday ticket - 2018"
        ],
        [
            "Buyer Name",
            "Jhon Doe"
        ],
        [
            "Buyer E-mail",
            "demo@email.com"
        ]
    ]
}

I make ng-repeat but show this in HTML
["Ticket Type","Friday ticket"]
["Buyer Name","Jhon Doe"]
["Buyer E-mail","demo@email.com"]
I need same like this.
Ticket Type: Friday ticket
Code snippet :
function fetch() {
  $http({
    method: 'GET',
    url: url,
    timeout: 6000
  }).then(
    function(result) {
      $scope.tickets = result.data;
    }
  );

}

A: You need to map that array before to render it into the HTML.
This alternative doesn't mutate the original data.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.custom_fields = [
    ["Ticket Type", "Friday ticket - 2018"],
    ["Buyer Name", "Jhon Doe"],
    ["Buyer E-mail", "demo@email.com"]
  ];
  $scope.mapped = $scope.custom_fields.map(function(c) {
    return {
      title: c[0],
      text: c[1]
    };
  });
});

    {{entry.title}}: {{entry.text}}


text:
Q: Flask url_for() no cache I put some files in static directory and these files are keep updated by some back end processing. I used url_for() to return url to client side.
But I found that even if I removed the old files from static directory and regenerate the updated files, it still display the content of old files on the client browser. I think the old file has been cached.
Does anyone know how to set no-cache for the url_for() function?
Thanks in advance!

A: I wrote a blog post about this a while ago.
Basically, you need to create a response to send, then set some extra headers on the response, then send the response:
def send_url(method):

    response = app.make_response(url_for(method))

    response.headers.add('Last-Modified', datetime.datetime.now())
    response.headers.add('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0')
    response.headers.add('Pragma', 'no-cache')

    return response

A: Disabling all caching just because once in a while you have a new release is really not good practice.  Caching of css and js gives huge performance benefits.
What good sites do is to add a timestamp of the file to the resource URLs.  For example, in Flask, here is a way to do this transparently: http://flask.pocoo.org/snippets/40/


text:
Q: Something has changed in In-app billings on Android I've spent last few days on testing in app purchases, and what I see is that something has changed in Google Play. Since yesterday I'm getting other responses in some cases and even logs in my Google Wallet are different than previous (check screenshot below).

Here is my problem
Lets give it such a scenario:

*

*Try to purchase real subscription product without funds on associated credit card - ok Google play shows dialog and advices us to check Google Wallet, so I'm going there, everything looks good (except I have no money on my credit card - exactly it's a virtual prepaid card, and another thing is that when I click link to update payment informations I'm redirected to my transactions)

*Cancel your order in Google Wallet

*Try to purchase it once again and I get "You have already purchased this item, or purchase is still pending" dialog. No matter if transactions was restored and how much time goes off (now I'm about 24h after first try). I'm getting this response even if I have money on card

And finally I'm unable to purchase my products. So my questions are - how to solve my problem? And what exactly has changed? Except logs in Wallet and time latency between try to purchase and cancel notification on no funds (now its instant, but up to 27 it was few minutes - first comes Purchased status and then Canceled).

A: I have experience same errors for about a few weeks. I've contacted with Google Play Support Team and they confirmed problems on their side. They also sad a fix is already in testing stage now and should be deployed soon.


text:
Q: How to use pointers to interface in go as internal data structure for collection-like types? TLDR; I need to use pointers to interface e.g. *Comparable as an internal Data's object in my Node as a part of Tree. Data should conform to pointer to Comparable interface that has only one method Less which compares two objects of Comparable interface type.
If I am using just Comparable as type for Data in Node, without pointer, everything works fine. However after I switch to *Comparable compiler gives strange errors and code won't compile
Code with Comparable:
package main

type Comparable interface {
    Less(than Comparable) bool
}

type Node struct {
    Data Comparable
}

func NewNode(data Comparable) *Node {
    return &Node{Data: data} }

type Tree struct {
    root *Node
}

func NewTree() *Tree {
    return &Tree{}
}

func (t *Tree) insert(data Comparable) {
    if t.root == nil || t.root.Data.Less(data) {
        t.root = NewNode(data)
    }
}

type Row struct {
    Row []string
}

func NewRow(row[] string) *Row {
    return &Row{Row: row}
}

func (r Row) Less(other Comparable) bool {
    return r.Row[0] < other.(Row).Row[0]
}

func main() {
    t := NewTree()
    t.insert(*NewRow([]string{"123"}))
    fmt.Printf("%v\n", t.root.Data.(Row).Row)
}

tests:
package main

import (
    "reflect"
    "testing"
)

func TestInsert(t *testing.T) {
    d := []string{"42"}
    tree := NewTree()
    tree.insert(*NewRow(d))
    if !reflect.DeepEqual(tree.root.Data.(Row).Row, d) {
        t.Error("returned elements are not matching")
    }
}

func TestInsert2x(t *testing.T) {
    d1 := []string{"42"}
    d2 := []string{"99"}
    tree := NewTree()
    tree.insert(*NewRow(d1))
    tree.insert(*NewRow(d2))
    if !reflect.DeepEqual(tree.root.Data.(Row).Row, d2) {
        t.Error("returned elements are not matching")
    }
}

However when I convert Comparable to *Comparable, everything breaks and the root cause is something like *Row is not equal to *Comparable compiler error:
for line return r.Row[0] < other.(*Row).Row[0]

Invalid type assertion: other.(*Row) (non-interface type *Comparable on left)

and for line if t.root == nil || t.root.Data.Less(data) {

Unresolved reference 'Less'

package main

type Comparable interface {
    Less(than *Comparable) bool
}

type Node struct {
    Data *Comparable
}

func NewNode(data *Comparable) *Node {
    return &Node{Data: data}
}

type Tree struct {
    root *Node
}

func NewTree() *Tree {
    return &Tree{}
}

func (t *Tree) insert(data *Comparable) {
    if t.root == nil || t.root.Data.Less(data) {
        t.root = NewNode(data)
    }
}

type Row struct {
    Row []string
}

func NewRow(row[] string) *Row {
    return &Row{Row: row}
}

func (r *Row) Less(other *Comparable) bool {
    return r.Row[0] < other.(*Row).Row[0]
}

func main() {
    t := NewTree()
    t.insert(NewRow([]string{"123"}))
    fmt.Printf("%v\n", t.root.Data.(*Row).Row)
}

tests:
package main

import (
    "reflect"
    "testing"
)

func TestInsert(t *testing.T) {
    d := []string{"42"}
    tree := NewTree()
    tree.insert(NewRow(d))
    if !reflect.DeepEqual(tree.root.Data.(*Row).Row, d) {
        t.Error("returned elements are not matching")
    }
}

func TestInsert2x(t *testing.T) {
    d1 := []string{"42"}
    d2 := []string{"99"}
    tree := NewTree()
    tree.insert(NewRow(d1))
    tree.insert(NewRow(d2))
    if !reflect.DeepEqual(tree.root.Data.(*Row).Row, d2) {
        t.Error("returned elements are not matching")
    }
}

The question is how to use *Comparable as type of Data in Node so that code above compiles. I tried a couple ugly options with interface{} type for Data and explicit casts everywhere. This approach I didn't like as it is very unsafe.
You can check all code parts in my github repo

A: Interfaces can accept both structs and pointers to structs.
You can pass in a pointer to Row (*Row) to Tree.insert(data Comparable), by combining your 1st Tree.insert(data Comparable) function definition with your 2nd main() function calls.
Here's a full running example, also on Go Playground: https://play.golang.org/p/Gh_RT3R-Fy0 .
package main

import (
    "fmt"
)

type Comparable interface {
    Less(than Comparable) bool
}

type Node struct {
    Data Comparable
}

func NewNode(data Comparable) *Node {
    return &Node{Data: data}
}

type Tree struct {
    root *Node
}

func NewTree() *Tree {
    return &Tree{}
}

func (t *Tree) insert(data Comparable) {
    if t.root == nil || t.root.Data.Less(data) {
        t.root = NewNode(data)
    }
}

type Row struct {
    Row []string
}

func NewRow(row []string) *Row {
    return &Row{Row: row}
}

func (r Row) Less(other Comparable) bool {
    return r.Row[0] < other.(*Row).Row[0]
}

func main() {
    t := NewTree()
    t.insert(NewRow([]string{"123"}))
    fmt.Printf("%v\n", t.root.Data.(*Row).Row)
}

That being said, this is brittle code since the Row.Less function accesses the underlying type of Comparable and assumes the array has at a 0 index value (length > 0).
func (r Row) Less(other Comparable) bool {
    return r.Row[0] < other.(*Row).Row[0]
}

It's much better to remove any dependency on the underlying type of Comparable when interface functions are called. You can do this augmenting the Comparable interface and Row.Less definition as follows. In this approach, there's no need to cast in the Row struct definition.
On Go Playground: https://play.golang.org/p/8-71-pEn-zK
type Comparable interface {
    Less(than Comparable) bool
    CompareValue() string
}

func (r Row) CompareValue() string {
    if len(r.Row) == 0 {
        return ""
    }
    return r.Row[0]
}

func (r Row) Less(other Comparable) bool {
    return r.CompareValue() < other.CompareValue()
}

For more information on pointer to interfaces, see the Go FAQ on using pointers to interfaces:
https://golang.org/doc/faq#pointer_to_interface

When should I use a pointer to an interface?
Almost never. Pointers to interface values arise only in rare, tricky situations involving disguising an interface value's type for delayed evaluation.
It is a common mistake to pass a pointer to an interface value to a function expecting an interface. The compiler will complain about this error but the situation can still be confusing, because sometimes a pointer is necessary to satisfy an interface. The insight is that although a pointer to a concrete type can satisfy an interface, with one exception a pointer to an interface can never satisfy an interface.
[...]
The one exception is that any value, even a pointer to an interface, can be assigned to a variable of empty interface type (interface{}). Even so, it's almost certainly a mistake if the value is a pointer to an interface; the result can be confusing.


text:
Q: I am getting the following error While adding cloud firestore to my flutter app Here is the error I'm getting:
Launching lib\main.dart on RMX2189 in debug mode...
FAILURE: Build failed with an exception.

*

*What went wrong:
A problem occurred configuring project ':cloud_firestore'.

Could not resolve all artifacts for configuration ':cloud_firestore:classpath'.
Could not resolve org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.4.32.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:sdk-common:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:repository:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:aaptcompiler:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.analytics-library:shared:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.lint:lint-model:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > androidx.databinding:databinding-compiler-common:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.utp:android-test-plugin-host-retention-proto:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:builder:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:builder-model:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:gradle-api:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:sdk-common:30.0.2 > com.android.tools:common:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:builder:7.0.2 > com.android.tools.analytics-library:tracker:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:builder:7.0.2 > com.android.tools.build:manifest-merger:30.0.2
> Could not resolve org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.4.32.
> Could not get resource 'https://repo.maven.apache.org/maven2/org/jetbrains/kotlin/kotlin-stdlib-jdk8/1.4.32/kotlin-stdlib-jdk8-1.4.32.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/org/jetbrains/kotlin/kotlin-stdlib-jdk8/1.4.32/kotlin-stdlib-jdk8-1.4.32.pom'.
> Remote host terminated the handshake
Could not resolve io.grpc:grpc-core:1.21.1.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:30.0.2
> Could not resolve io.grpc:grpc-core:1.21.1.
> Could not get resource 'https://repo.maven.apache.org/maven2/io/grpc/grpc-core/1.21.1/grpc-core-1.21.1.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/io/grpc/grpc-core/1.21.1/grpc-core-1.21.1.pom'.
> Remote host terminated the handshake
Could not resolve io.grpc:grpc-netty:1.21.1.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:30.0.2
> Could not resolve io.grpc:grpc-netty:1.21.1.
> Could not get resource 'https://repo.maven.apache.org/maven2/io/grpc/grpc-netty/1.21.1/grpc-netty-1.21.1.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/io/grpc/grpc-netty/1.21.1/grpc-netty-1.21.1.pom'.
> Remote host terminated the handshake
Could not resolve io.grpc:grpc-protobuf:1.21.1.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:30.0.2
> Could not resolve io.grpc:grpc-protobuf:1.21.1.
> Could not get resource 'https://repo.maven.apache.org/maven2/io/grpc/grpc-protobuf/1.21.1/grpc-protobuf-1.21.1.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/io/grpc/grpc-protobuf/1.21.1/grpc-protobuf-1.21.1.pom'.
> Remote host terminated the handshake
Could not resolve io.grpc:grpc-stub:1.21.1.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:30.0.2
> Could not resolve io.grpc:grpc-stub:1.21.1.
> Could not get resource 'https://repo.maven.apache.org/maven2/io/grpc/grpc-stub/1.21.1/grpc-stub-1.21.1.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/io/grpc/grpc-stub/1.21.1/grpc-stub-1.21.1.pom'.
> Remote host terminated the handshake
Could not resolve com.google.guava:guava:30.1-jre.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:sdk-common:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:aaptcompiler:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.analytics-library:crash:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.analytics-library:shared:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > androidx.databinding:databinding-compiler-common:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:builder-test-api:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:bundletool:1.6.0
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:gradle-api:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:sdk-common:30.0.2 > com.android.tools:common:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:builder:7.0.2 > com.android.tools.analytics-library:tracker:30.0.2
> Could not resolve com.google.guava:guava:30.1-jre.
> Could not get resource 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Remote host terminated the handshake
Could not resolve org.apache.commons:commons-compress:1.20.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:sdklib:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:repository:30.0.2
> Could not resolve org.apache.commons:commons-compress:1.20.
> Could not get resource 'https://repo.maven.apache.org/maven2/org/apache/commons/commons-compress/1.20/commons-compress-1.20.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/org/apache/commons/commons-compress/1.20/commons-compress-1.20.pom'.
> Remote host terminated the handshake
Could not resolve com.google.guava:guava:30.1-jre.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.google.protobuf:protobuf-java-util:3.10.0
> Could not resolve com.google.guava:guava:30.1-jre.
> Could not get resource 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Remote host terminated the handshake
Could not resolve com.google.guava:guava:30.1-jre.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:repository:30.0.2 > com.google.jimfs:jimfs:1.1
> Could not resolve com.google.guava:guava:30.1-jre.
> Could not get resource 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Remote host terminated the handshake
Could not resolve com.google.guava:guava:30.1-jre.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:builder:7.0.2 > com.android.tools.build:apkzlib:7.0.2
> Could not resolve com.google.guava:guava:30.1-jre.
> Could not get resource 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Remote host terminated the handshake
Failed to notify project evaluation listener.
Could not get unknown property 'android' for project ':cloud_firestore' of type org.gradle.api.Project.
Could not find method implementation() for arguments [project ':firebase_core'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
Could not get unknown property 'android' for project ':cloud_firestore' of type org.gradle.api.Project.

*

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
BUILD FAILED in 29s
[!] Gradle threw an error while downloading artifacts from the network. Retrying to download...
FAILURE: Build failed with an exception.

*

*What went wrong:
A problem occurred configuring project ':cloud_firestore'.

Could not resolve all artifacts for configuration ':cloud_firestore:classpath'.
Could not resolve org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.4.32.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:sdk-common:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:repository:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:aaptcompiler:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.analytics-library:shared:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.lint:lint-model:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > androidx.databinding:databinding-compiler-common:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.utp:android-test-plugin-host-retention-proto:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:builder:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:builder-model:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:gradle-api:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:sdk-common:30.0.2 > com.android.tools:common:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:builder:7.0.2 > com.android.tools.analytics-library:tracker:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:builder:7.0.2 > com.android.tools.build:manifest-merger:30.0.2
> Could not resolve org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.4.32.
> Could not get resource 'https://repo.maven.apache.org/maven2/org/jetbrains/kotlin/kotlin-stdlib-jdk8/1.4.32/kotlin-stdlib-jdk8-1.4.32.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/org/jetbrains/kotlin/kotlin-stdlib-jdk8/1.4.32/kotlin-stdlib-jdk8-1.4.32.pom'.
> Remote host terminated the handshake
Could not resolve io.grpc:grpc-core:1.21.1.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:30.0.2
> Could not resolve io.grpc:grpc-core:1.21.1.
> Could not get resource 'https://repo.maven.apache.org/maven2/io/grpc/grpc-core/1.21.1/grpc-core-1.21.1.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/io/grpc/grpc-core/1.21.1/grpc-core-1.21.1.pom'.
> Remote host terminated the handshake
Could not resolve io.grpc:grpc-netty:1.21.1.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:30.0.2
> Could not resolve io.grpc:grpc-netty:1.21.1.
> Could not get resource 'https://repo.maven.apache.org/maven2/io/grpc/grpc-netty/1.21.1/grpc-netty-1.21.1.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/io/grpc/grpc-netty/1.21.1/grpc-netty-1.21.1.pom'.
> Remote host terminated the handshake
Could not resolve io.grpc:grpc-protobuf:1.21.1.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:30.0.2
> Could not resolve io.grpc:grpc-protobuf:1.21.1.
> Could not get resource 'https://repo.maven.apache.org/maven2/io/grpc/grpc-protobuf/1.21.1/grpc-protobuf-1.21.1.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/io/grpc/grpc-protobuf/1.21.1/grpc-protobuf-1.21.1.pom'.
> Remote host terminated the handshake
Could not resolve io.grpc:grpc-stub:1.21.1.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:30.0.2
> Could not resolve io.grpc:grpc-stub:1.21.1.
> Could not get resource 'https://repo.maven.apache.org/maven2/io/grpc/grpc-stub/1.21.1/grpc-stub-1.21.1.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/io/grpc/grpc-stub/1.21.1/grpc-stub-1.21.1.pom'.
> Remote host terminated the handshake
Could not resolve com.google.guava:guava:30.1-jre.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:sdk-common:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:aaptcompiler:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.analytics-library:crash:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.analytics-library:shared:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > androidx.databinding:databinding-compiler-common:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:builder-test-api:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.utp:android-test-plugin-result-listener-gradle-proto:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:bundletool:1.6.0
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:gradle-api:7.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:sdk-common:30.0.2 > com.android.tools:common:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:builder:7.0.2 > com.android.tools.analytics-library:tracker:30.0.2
> Could not resolve com.google.guava:guava:30.1-jre.
> Could not get resource 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Remote host terminated the handshake
Could not resolve org.apache.commons:commons-compress:1.20.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:sdklib:30.0.2
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:repository:30.0.2
> Could not resolve org.apache.commons:commons-compress:1.20.
> Could not get resource 'https://repo.maven.apache.org/maven2/org/apache/commons/commons-compress/1.20/commons-compress-1.20.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/org/apache/commons/commons-compress/1.20/commons-compress-1.20.pom'.
> Remote host terminated the handshake
Could not resolve com.google.guava:guava:30.1-jre.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.google.protobuf:protobuf-java-util:3.10.0
> Could not resolve com.google.guava:guava:30.1-jre.
> Could not get resource 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Remote host terminated the handshake
Could not resolve com.google.guava:guava:30.1-jre.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools:repository:30.0.2 > com.google.jimfs:jimfs:1.1
> Could not resolve com.google.guava:guava:30.1-jre.
> Could not get resource 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Remote host terminated the handshake
Could not resolve com.google.guava:guava:30.1-jre.
Required by:
project :cloud_firestore > com.android.tools.build:gradle:7.0.2 > com.android.tools.build:builder:7.0.2 > com.android.tools.build:apkzlib:7.0.2
> Could not resolve com.google.guava:guava:30.1-jre.
> Could not get resource 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Could not GET 'https://repo.maven.apache.org/maven2/com/google/guava/guava/30.1-jre/guava-30.1-jre.pom'.
> Remote host terminated the handshake
Failed to notify project evaluation listener.
Could not get unknown property 'android' for project ':cloud_firestore' of type org.gradle.api.Project.
Could not find method implementation() for arguments [project ':firebase_core'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
Could not get unknown property 'android' for project ':cloud_firestore' of type org.gradle.api.Project.

*

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
BUILD FAILED in 24s
[!] Gradle threw an error while downloading artifacts from the network. Retrying to download...
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)


text:
Q: Javascript element style I'm curious why this one

    fdsfsd

.overlay{
    width: 100px;
    height: 200px;
    background-color:red;
}
alert(document.getElementsByClassName("overlay")[0].style.width);

is not alerting nothing. Of course I can write

then everthing works fine, but it is not good for me, I need css.
Here you can find a jsfiddle demo
So exact question is: why this code is not alerting width of div and how alert it if width is given by css?

A: The JavaScript .style only relates to inline styles on the element.
See Documentation.
If you want to get the width of an element you should use offsetWidth.
document.getElementsByClassName("overlay")[0].offsetWidth

http://jsfiddle.net/9kwap3zy/7/

A: As noted elsewhere, the problem is that HTMLElement.style retrieves the values from the style attribute of the element; as you're setting your style with CSS, you need to instead use window.getComputedStyle(element, null).width:

var elem = document.getElementsByClassName("overlay")[0],
  width = window.getComputedStyle(elem, null).width;

console.log(width);
.overlay {
  width: 100px;
  height: 200px;
  background-color: red;
}

  fdsfsd

References:

*

*HTMLElement.style.

*window.getComputedStyle().

A: The style gives access only to information which is put into elem.style. In your example style doesn't tell anything about the margin defined in CSS. Use getComputedStyle().
var computedStyle = getComputedStyle(document.getElementsByClassName("overlay")[0], null)

alert(computedStyle.width);

jsfiddle demo

A: The .style is inline style="width:100px;" only...
If it's in CSS (rather than inline) you need getComputedStyle -
https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle


text:
Q: Quantifiers and patterns (QBF formula) I'm trying to encode a QBF in smt-lib 2 syntax for z3. Running z3 results in a warning

WARNING: failed to find a pattern for quantifier (quantifier id: k!14)

and the satisfiability result is "unknown".
The code is as follows:
(declare-fun R (Bool Bool Bool Bool) Bool)
(assert
  (forall ((x2 Bool) (x3 Bool))
    (exists ((y Bool))
      (forall ((x1 Bool))
        (R x1 x2 x3 y)
      )
    )
  )
)
(check-sat)

I got rid of the warning by rewriting the code to
(set-option :auto-config false)
(set-option :mbqi false)
(declare-fun R (Bool Bool Bool Bool) Bool)
(declare-fun x1 () Bool)
(declare-fun x2 () Bool)
(declare-fun x3 () Bool)
(declare-fun y () Bool)
(assert
  (forall ((x2 Bool) (x3 Bool))
  (!
    (exists ((y Bool))
    (!
      (forall ((x1 Bool))
      (!
        (R x1 x2 x3 y)
      :pattern((R x1 x2 x3 y)))
      )
    :pattern((R x1 x2 x3 y)))
    )
  :pattern((R x1 x2 x3 y)))
  )
)
(check-sat)

The result for the sat-query, however, remains "unknown".
I'm guessing that I need to get the patterns right? How do I specify them for nested quantifiers? Simpler examples with quantifiers seem to work without pattern annotation, though.
The answer to What is the reason behind the warning message in Z3: "failed to find a pattern for quantifier (quantifier id: k!18) " and the z3 guide didn't help me too much, unfortunately.

A: This warning message can be ignored. It is just informing you that the E-matching engine will not be able to process this quantified formula.
E-matching is only effective for showing that a problem is unsatisfiable. Since your example is satisfiable, E-matching will not be very useful. That is, Z3 will not be able to return sat using the E-matching engine. Model based quantifier instantiation (MBQI) is the only engine in Z3 that is capable of showing that problems containing quantifiers are satisfiable.
Using the default configuration, Z3 will return sat for your example. It returns unknown because you disabled the MBQI module.
The MBQI engine guarantees that Z3 is a decision procedure for many fragments (see http://rise4fun.com/Z3/tutorial/guide). However, it is very expensive in general, and should be disabled when quick and approximated answers are sufficient. In this case, unknown may be read as probably sat. Verification tools such as VCC disable MBQI module since it is incapable of deciding formulas produced by them. That is, the formulas produced by VCC are not in any of the fragments that can be decided by the MBQI engine.
We say a fragment can be decided by Z3 when for any formula in the fragment Z3 will return sat or unsat (i.e., it does not return unknown). Of course, this claim  assumes we have a unlimited amount of resources. That is, Z3 may also fail (i.e., return unknown) for decidable fragments when it runs out of memory, or a timeout was specified by the user.
Finally, Z3 3.2 has a bug in the MBQI engine. The bug has been fixed, and it does not affect your problem. If you need I can give you a pre-release version of Z3 4.0 which contains the bug fix.


text:
Q: Paying by PayPal returns the customer to a manual Place Order page instead of completing order I've just completed my first run through purchasing a product on a Magento 1.9.2.4
 CE site I've just been putting together. The payment gateway is PayPal Payment Pro.
When PayPal returns you to the site, after paying, you end up on a page that asks you to Place Order. It also allows you to change shipping methods, which changes the cost, even though the customer has just paid.
How do I change this so that paying completes the order?
Here is the dev site: http://www.gtechniq.high-speed.net.au
I can't think of any other e-commerce site that makes you take extra action to complete the order after you've paid. I suspect my client will have lots of payments in PayPal and no completed ordered in Magento, especially as you have to scroll the page down to find the Place Order button.
Thanks for any help

A: Turns out that, yes, it was  something simple and instead of deleting this, I'll give the answer for anyone else who can't find it: "Skip Order Review Step" should be set to Yes.
I had interpreted this as meaning something else, but removing it completes the order automatically (if you have Payment Action set to Sale) after you have completed your payment.


text:
Q: XPath - get parent of text nodes with condition <doc ok="yes">
    <a>
        <b>
            <c>
                aa
                <d ok="yes">
                    bb
                </d>
                cc
            </c>
        </b>
    </a>
    <e>
        ee
    </e>
    <f ok="no">
        no
    </f>
</doc>

I need to retrieve list of nodes using XPath, where each node must satisfy these conditions:

*

*node has at least one child text node

*if the node (or closest node in ancestor axis) has an attribute "ok", the value must be "yes"

*when any ancestor is a part of the result, exclude node
So in my sample I would like to get <c> and <e>. Node <d> is excluded because it is a child of <c>, which is a part of the result.
I've started with condition (1) using this expression //*[count(./text()[normalize-space()])>0]. It returns <c>, <d>, <e>  and <f>. I have no idea how to exclude <d>

A: I would devide this into 2 steps.
First, consider only condition number 1 and 2.
//*[text()[normalize-space()]]
   [
      ancestor-or-self::*[not(@ok)]
        or
      ancestor-or-self::*[@ok][1][@ok='yes']
    ]

Given XML in question as input, above xpath return 3 elements : <c>, <d>, and <e>.
Next step would be implementing the condition number 3. That can be done by repeating the same predicate that was used in the first step, but now for ancestor::* instead of current node. Then negate the repeated predicate using not() as we want the ancestor to fail the condition no 1 & 2 (we want ancestor of current node not being part of the result already) :
[not(
        ancestor::*[text()[normalize-space()]]
        [
            ancestor-or-self::*[not(@ok)]
                or
            ancestor-or-self::*[@ok][1][@ok='yes']
        ]
    )
]

Combining both steps together you get the following xpath :
//*[text()[normalize-space()]]
   [
      ancestor-or-self::*[not(@ok)]
        or
      ancestor-or-self::*[@ok][1][@ok='yes']
    ]
    [not(
            ancestor::*[text()[normalize-space()]]
            [
                ancestor-or-self::*[not(@ok)]
                    or
                ancestor-or-self::*[@ok][1][@ok='yes']
            ]
        )
    ]

Each of the outer predicate ([]) in the final xpath, in order, represents condition no 1, 2, and 3.


text:
Q: get req.body from node express server side code to take array from front end I'm trying to save a user's array to mongo and it goes from the bridge to the posts.  The posts receive it as some weird object with string versions of its indices.  I'm trying to convert it to a normal array so it can save to mongo but it's very sensitive and keeps erroring out, is there some sort of parsing operation I'm missing?
bridge:
static saveUsers(users){
    try{
        let command = 'saveUsers';
        return axios.post(url + command, {
            params: users
        });
    } catch(err){
        reject(err);
    }
}

posts:
router.post('/saveUsers', async (req, res) => {
    let collection = await loadCollection('users');
    let userArray = req.body.params.toArray(); // this causes error
    await collection.insertMany(
        userArray
    );
        res.status(201).send();
});

A: static saveUsers(users){
    try{
        let command = 'saveUsers';
        return axios.post(url + command, {
            params: JSON.stringify(users) // send users as a string with stringify
        });
    } catch(err){
        reject(err);
    }
}

router.post('/saveUsers', async (req, res) => {
    let collection = await loadCollection('users');
    let userArray = JSON.parse(req.body.params) // parse params
    await collection.insertMany(
        userArray
    );
        res.status(201).send();
});


text:
Q: Conjugation and generators
Let $G$ be a finite group and $x\in G$ be of order $4$. So $o(x)=4$. Suppose that all cyclic subgroups of $G$ of order 4 are conjugate. Show that there exists an involution $g\in G$ such that $\langle x,g\rangle=G$. Further, $x$ is not conjugate to $x^{-1}$ in $\operatorname{Aut}(G)$.

You can even consider $G$  as Suzuki group $Sz(q)$. The group whose order is $q^2 (q^2 +1)(q−1)$ and $q=2^m$   which $m$  is odd. Also, any two Sylow 2-subgroups of $G$ have trivial intersection.

A: The group $G={\rm SL}_2(3)$ of order $48$ has three cyclic subgroups of order $4$, which are all conjugate in $G$. But $G$ has a normal Sylow $2$-subgroup of order $8$, so $G$ cannot be generated by an element of order $4$ and an element of order $2$. Furthermore, if $x$ has order $4$ then $x$ is conjugate to $x^{-1}$ in $G$ (and hence also in ${\rm Aut}(G))$.
So something is badly wrong with this exercise!

A: I don't understand if the final sentence "Further, $x$ is not conjugate to $x^{−1}$ in $Aut(G)$ is an hypothesis or a conclusion.
But $G = \mathbb{Z}_4 \times \mathbb{Z}_4$ has a lot of cyclic subgroups of order $4$; which are not conjugate since $G$ is abelian. And there don't exist elements $x$ and $g$ of order $4$ and $2$ such that $<x,g> = G$.
Edit: Sorry, I don't know why I gave this example where subgroups of order $4$ are NOT conjugate...


text:
Q: Why shouldn't I give all my DynamoDB items in the same partition key value? There are plenty of resources that recommend using high-cardinality attributes as partition keys. My question is, what will happen if I instead do the exact opposite of this and give all of my items the same partition key value (differentiating only by sort key), allowing me to query over the entire table?
Will this cause performance and/or hot partition issues? Do hot partitions even matter with adaptive capacity if they aren't reaching 3000 RCUs/1000 WCUs? Even then, what if queries are evenly distributed among my sort key?
Consensus seems to be that we shouldn't do this, but my question is: Why not?

A: The recommendations and best practices are there to guide you to benefit the most from using DynamoDB. Typically, people use DynamoDB for storing massive and high-velocity data that suffers from scalability problems in the traditional RDBMS.
If you are talking about a small amount of data where the aggregated access velocity doesn't exceed 3000 RCUs/1000 WCUs, that's not enough for you to reach the pain point of using DynamoDB. In fact, you can probably achieve the same level of performance if you use a traditional RDBMS. However, as soon as your app becomes popular, or even if your app just encountered a spike over the time span of 5 minutes, the amount of data and velocity quickly increases, and you will feel the pain. That's why following best practices will usually give you this kind of future proof benefit.

Even then, what if queries are evenly distributed among my sort key?

DynamoDB splits partitions by sort key if the collection size grows bigger than 10 GB. [ref] So it's likely that you will still have the hot partition problem.
Don't get me wrong. There are use cases that require using the same partition key, such as modeling one-to-many and many-to-many relations of your data. These are valid use cases since data is relational by nature and that's the only way to efficiently model it in DynamoDB. However, if you choose to do the exact opposite of what the documentation suggests, your scalability is limited and you will not be able to take the full benefit from DynamoDB.

A: Alright, here we go and I will do it with an example app.
Let's say you are creating a census application for Canada. Your partition key is going to be the province or territory name, of which there are 13 total iirc. You load the initial data in and all is fine. You open it up for users to come in. Everything is going ok, but hit the evening when everyone is home and just got a card saying they should go to your site. Well, where are the population centers in Canada? Ontario and Quebec have the most and they just so happen to be in the same table partition. Oops. Yes, adaptive capacity will try and save you, but in short order there are now 10s of thousands of people (or more) trying to use your site. That partition is now hot as it hits the 3000 IOPS per partition quota with just one section of Toronto online. DynamoDB is already trying to move items to other partitions and creating more to save you from your blunder, but your users are already getting throttled. You chose poorly. Twitter/reddit/etc is now erupting with nasty comments I shall not quote here. Meanwhile the partition that has Prince Edward Island and Yukon in it is not doing much at all. If you had picked a different partition key or used write sharding with the province/territory name, items would be more evenly spread and this would not be a problem.
That said, in another scenario, with a lightly used application and low cardinality PK, all might be well. As that app scales, that is when your blunder will become apparent. If it will never scale then it might be fine…by why hassle with that?
Hopefully you get the point. Also, this kind of thing is not unique to DynamoDB. I have worked with plenty of other databases that do partitioning where this could be a problem. At least DynamoDB is smart enough to try and save you from your blunder over time for you, but why set yourself up for problems?

A: For a scalable app you just can't assume its IOPS is never hit. And because the traffic is never coming evenly from each region, some of the data centers may have much higher traffic than another. And during some special events a huge spike of traffic is expected (e.g., Alexa device accessing on Christmas), adaptive capacity takes effect with an uncertain delay for such case --- so you need to plan for a scale up in advance, and of course try to avoid potential hot partition issues at the very beginning.


text:
Q: Display shadow-box over contained elements I'd like to display a list of elements inside of a container div. This container div has an inner shadow box. Unfortunately, the shadow box goes underneath the contained elements, as you can see here

Now obviously, this is both illogical and non-esthetic. I dug around, and someone gave this solution. The problem is, I need to be able to scroll inside of this container, for the contained divs will most likely overflow.
Is there a way to display this shadow over the contained divs ?

A: Since you have not provided any source code, some better way to achive this is

.parent {
    box-shadow : inset 0 0 5px 0 black;
    height:200px;
    position :relative;
    overflow-y: scroll;
}

.content {
    background : rgba(0,0,0,0.2);
    height:1000px;
    width:200px;
    margin:auto;
}

    foo

bar


text:
Q: Select all posts created by all users a given user follows I am trying to obtain all posts created by all users a given user follows.
Tables: posts, users, followers
Users
id int(255)

Which is associated with:
Followers
id int(255)
user_id int(255) //The id of person that's is following
following int(255) //The id of person being followed

Which is also associated with:
Posts
id int(255)
user_id(255) //The id of person who created the post

I don't know what is needed here to achieve this in a single query. Normally, I would obtain all users the user follows and then loop through all users obtaining the posts of each. Using this approach, my results are first sorted by user, then sorted by date. I want to sort all posts by date.
Any suggestions?

A: A simple join should suffice. The ? is where the user id of the 'follower' goes.
SELECT * FROM Posts p
INNER JOIN Followers f ON (f.following = p.user_id)
WHERE f.user_id = ?;

A: To do this queries you just have to join multiple tables
    SELECT P.*
      FROM users     U
INNER JOIN followers F ON (F.user_id = U.id)
INNER JOIN users    FU ON (FU.id = F.following)
INNER JOIN posts     P ON(P.user_id = F.id)
     WHERE U.id = :id

A: SELECT posts.id as post_id
FROM users
JOIN followers ON followers.user_id = users.id
JOIN posts ON posts.user_id = followers.following
WHERE users.user_id = ?

All you need is to join the 3 tables. Join users to followers and then join followers to posts.

A: the followers table has the id of the user you are looking at so there is no need to join to the users table specifically if you are only looking at posts.
Also, note I have used a derived table to filter the results early so that we are only getting those records from the posts table we are interested in... if we filter in the outer query we have to get everything from what could be large tables and then apply the filter... i.e. this is one way you could improve the performance of the query.
select p.*
from
    (select following from followers where user_id = @your_user) f
    inner join posts p
        on p.user_id = f.following
order by p.date

Although you don't specify it, my query assumes the date column is in the posts table. I also am interpreting what you have stated in the question as you are wanting to sort by date only.


text:
Q: Semantic UI combine all tags from multiple Dropdown with Multiselection I am trying to create a complex Filter for a table. I created several dropdown menus with multiselection in Semantic UI. The selected tags are shown inside the dropdown field for every dropdown (Standard Semantic UI Multiselection Dropdown).
Question: Is it possible to collect all the Tags inside a separate Field - no matter wich dropdown they have been chosen (see image)?
Above: 2 Standard Semantic UI Filter // Below: Photoshopped Result

          <input type="hidden" name="filters">

          Filter location

              <input type="text" placeholder="Search locations...">

                Hamburg

                Berlin

                Munich

          <input type="hidden" name="filters">

          Filter product category

              <input type="text" placeholder="Search category...">

                Furniture

                Electronics

                Food


text:
Q: Trouble interacting with Parse when building app I am using xCode and I am trying to create a user Sign Up and Sign In with Parse as my backend. I have created a code in which the console should print a line when I attempt to Sign in or Sign Up. However nothing prints. Please Help. Below is my Code
func authenticate()
    {
        var email = self.emailTextField?.text
        var password = self.passwordTextField?.text

        if (email?.isEmpty == true || password?.isEmpty == true || email?.isEmailAddress() == false) //is this an email adress
        {
            // alert the user
            return
        }

        if authMode == .SignIn
        {
            self.signIn(email!, password: password!)
        }

        else
        {
            self.signUp(email!, password: password!)
        }
    }

    func signIn(email: String?, password: String?)
    {

        PFUser.logInWithUsernameInBackground(email!, password: password!) {
            (user: PFUser?, error: NSError?) -> Void in

            if ((user) != nil)
            {
                println("sign in success")
            }

            else
            {
                println("sign in failure! (alert the user)")
            }
        }

    }

    func signUp(email: String?, password: String?)
    {
        var user = PFUser()
        user.username = email
        user.email = email
        user.password = password

        user.signUpInBackgroundWithBlock {
            (succeeded: Bool, error: NSError?) -> Void in

            if (error == nil)
            {
                println("sign up success")
            }
            else
            {
                println("sign up failure! (alert the user!)")
            }
        }
    }
}


text:
Q: Derivatives Problem: Why is second term's coefficient less than zero? Problem:

If $f(x)=cx^2+dx+e$ for the function shown in the graph, then what values can $c$, $d$, and $e$ take on?

The answer is $c<0$, $d<0$, $e>0$. I just don't understand why $d<0$. Since the slope of $f(x)$ is always negative, $f'(x)<0$ and since $f'(x)=(2c)x+d$, $(2c)x+d<0$. Since $c<0$, let's choose $c=-1$, and let's choose $x=3$. $(2)(-1)(3)+d<0$ which leads to $-6+d<0$ which leads to $d<6$. And the maximum value (in this case 6) of this open inequality can change based on what $c$ and $x$ values are chosen. So where am I wrong?

A: The $x$-coordinate ( $\frac{-d}{2c}$ ) of the parabola vertex must be negative (to the left of the y-axis).
We know $c$ must be negative, because the parabola opens downwards.
So $d$ must be negative.

A: $$f'(x)=2cx+d \implies f'(0)=d.$$
The slope at $x=0$ is negative, therefore $d<0$.

A: No, for a quadratic polynomial, the slope  doesn't have a constant sign (otherwise, the polynomial wouldn't have an extremum).
If $c<0$, you can see on the graph that the parabola  has a maximum obtained at a point with a negative abscissa. As this maximum is obtained at $x=-\frac d{2c}$ (result from high school), what can you conclude for $d$?

A: First, note $c$ and $d$ are fixed values. From the diagram,
$$f'(x) = (2c)x + d \lt 0 \tag{1}\label{eq1}$$
for all $x \ge 0$, as well as some $x \lt 0$ (in particular to just before the vertex at $x = \frac{-d}{2c}$). What you've shown is that $d \lt 6$ when checking at $x = 3$ with $c = -1$. However, $d$ must also satisfy the inequality \eqref{eq1} for all $x$ where $f'(x) \lt 0$, i.e., for $x \gt \frac{-d}{2c}$, with this including $x = 0$. As pointed out in another answer, at $x = 0$, you get $f'(0) = d$, so $d \lt 0$, regardless of the value of $c$. This is still consistent with your determination of $d \lt 6$ (with $c = -1$), but it's just more stringent.

A:
If $f(x)=cx^2+dx+e$ for the function shown in the graph, then what values can $c$, $d$, and $e$ take on?

Note: $c<0$, because the branches of the parabola open down. $e>0$, because $f(0)=e>0$.

Since the slope of $f(x)$ is always negative, $f'(x)<0$ and since $f'(x)=(2c)x+d$, $(2c)x+d<0$.

No, the slope of $f(x)$ is not always negative, but:
$$\begin{cases}f'(x)>0, x<-\frac{d}{2c}\\
f'(x)<0,x>-\frac{d}{2c}\end{cases}$$
where $x=-\frac{d}{2c}$ is the $x$-coordinate of the vertex.

Since $c<0$, let's choose $c=−1$, and let's choose $x=3$. $(2)(−1)(3)+d<0$ which leads to $−6+d<0$ which leads to $d<6$. And the maximum value (in this case 6) of this open inequality can change based on what $c$ and $x$ values are chosen. So where am I wrong?

If $c=-1,x=3$, then $f'(x)<0\iff x>-\frac{d}{2c} \Rightarrow 3>\frac{d}{2} \iff d<6$ is necessary, but not sufficient condition for the given parabola. Why? Because, from the graph it is visible that the vertex is on the left of origin (i.e. $x<0$). So, the vertex must be $x=-\frac{d}{2c}=\frac{d}{2}<0 \Rightarrow d<0$, which is the sufficient condition.


text:
Q: Drop down menu for CakePHP 3.x of URLs to views I have a table called a_forms, and I'm trying to create a drop down menu on a page of AForms that has a list of all the rows of a_forms. I want each choice in the drop down to link directly to the view of that form. Here is my forms table:

fid int(3) unsigned auto_increment (primary key)
title varchar(100)
created timestamp CURRENT_TIMESTAMP on update
modified timestamp

I was able to get as far populating the drop down menu, however I'm having trouble with the second part - linking each choice with the view selected. I'm a beginner to CakePHP so I am probably missing something. Here is the function in AFormsController:
public function forms($id = null)
{
    $query = $this->AssessmentForms->find('all');
    $result = $query->toArray();
    $assessmentForm = $this->AssessmentForms->get($id, [ 'contain' => [] ]);
    $this->set('assessmentForm', $assessmentForm);
    $this->set('_serialize', ['assessmentForm']);
    $data = $this->AssessmentForms->find('list', array('fields' => array('fid', 'title')));
    $this->set('forms', $data);
}

forms.ctp:
<?php $this->Form->input('aform.select one', ['type' => 'select', 'options' => $forms, 'empty' => 'Choose One', 'onchange' => 'this.form.submit();']);?>

That gives me "Record not found in table "a_forms" with primary key [NULL]"
I also tried:
<?php $this->Form->create('Forms', array( 'url' => ['controller'=>'a_forms', 'action'=>'view', $aForm->fid])); ?>

And added this to the controller:
$aForms = $this->AForms->find('list');

It doesn't throw an error but I get a "Undefined variable: aForms [APP/Template/AForms/forms.ctp, line 10" in the view
I saw other people struggling with the 'onchange' method so I'm not sure if that's the right approach. I'm using version 3.1.0. Let me know if you need any more information!

A: Still don't quite know how to appropriately create queries with find(), but I found a way around with:

      <?php foreach ($aForms as $aForm): ?>

 <?= $this->Html->link($aForm->title, ['action' => 'fill', $aForm->fid]) ?>

      <?php endforeach; ?>

And this in the controller:
$this->set('assessmentForms', $this->paginate($this->AssessmentForms));
$this->set('_serialize', ['assessmentForms']);

I pulled that directly from the bake-generated index() function. If anyone has a more syntactically non-hackish way of solving this, please let me know!


text:
Q: ValueError: invalid literal for int() with base 10: when give 2 values in different lines I wrote this in PyCharm 2022.1.1:
a = int(input())
b = int(input())
print(a)
print(b)

I input 7 press Enter and input 10 and press Enter - no extra spaces.
But error was happend (ValueError: invalid literal for int() with base 10: ''). The error was happened exactly in second line.
I save it into the file and run from command line - work perfectly.
What am I doing wrong?
Screenshot


text:
Q: Why can't i use keyPressed anymore once the if-statement is true in the run()-methode? I'm trying to make a kind of brickbreaker game but once I press the start button ("starten" = true). I can't use the keyPressed()-utility anymore but before i pressed the start button I could use the keyPressed()-utility. Could somebody please tell me why I suddenly can't use the keyPressed()-utility anymore and give me a possible solution too?
import java.util.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class VGKernel extends JPanel implements KeyListener {

public Rectangle screen, ball, block; // The screen area and ball location/size.
public Rectangle bounds;  // The boundaries of the drawing area.
public JFrame frame; // A JFrame to put the graphics into.
public VGTimerTask vgTask; // The TimerTask that runs the game.
public boolean down, right, starten = false; // Direction of ball's travel.
public JButton start;

public VGKernel(){
    super();
    screen = new Rectangle(0, 0, 600, 400);
    ball   = new Rectangle(0, 0, 20, 20);
    block = new Rectangle(260, 350, 40, 10);
    bounds = new Rectangle(0, 0, 600, 400); // Give some starter values.
    frame = new JFrame("VGKernel");
    vgTask = new VGTimerTask();
    addKeyListener(this);
    setFocusable(true);
    start = new JButton("Start");
    start.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            starten = true;
        }
    });
    add(start);
}

class VGTimerTask extends TimerTask{
    public void run(){
        repaint();

        if(starten){
        moveBall();
        frame.repaint();
        }
    }
  }

// Now the instance methods:
  public void paintComponent(Graphics g){
    // Get the drawing area bounds for game logic.
    bounds = g.getClipBounds();
    // Clear the drawing area, then draw the ball.
    g.clearRect(screen.x, screen.y, screen.width, screen.height);
    g.fillRect(ball.x, ball.y, ball.width, ball.height);
    g.fillRect(block.x, block.y, block.width, block.height);
  }

  public void moveBall(){
  // Ball should really be its own class with this as a method.
    if (right) ball.x+=1; // If right is true, move ball right,
    else ball.x-=1;       // otherwise move left.
    if (down)  ball.y+=1; // Same for up/down.
    else ball.y-=1;
    if (ball.x > (bounds.width - ball.width)) // Detect edges and bounce.
      { right = false; ball.x = bounds.width -  ball.width; }
    if (ball.y > (bounds.height - ball.height))
      { down  = false; ball.y = bounds.height - ball.height;}
    if (ball.x == 0) { right = true; ball.x = 0; }
    if (ball.y == 0) { down  = true; ball.y = 0; }
  }

  public void keyPressed(KeyEvent evt) {
      if(evt.getKeyCode() == KeyEvent.VK_G && block.x > 0) {
          block.x -= 20;
      }

      if(evt.getKeyCode() == KeyEvent.VK_H && block.x < 540) {
          block.x += 20;
      }
  }

  public void keyTyped(KeyEvent evt){  }
  public void keyReleased(KeyEvent evt){ }

  public void startActionPerformed(java.awt.event.ActionEvent evt) {
      starten = true;
  }

  public static void main(String arg[]){
    java.util.Timer vgTimer = new java.util.Timer();  // Create a Timer.
    VGKernel panel = new VGKernel(); // Create and instance of our kernel.

    // Set the intial ball movement direction.
    panel.down = true;
    panel.right = true;

    // Set up our JFRame
    panel.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    panel.frame.setSize(panel.screen.width, panel.screen.height);
    panel.frame.setContentPane(panel);
    panel.frame.setVisible(true);

    // Set up a timer to do the vgTask regularly.
    vgTimer.schedule(panel.vgTask, 0, 10);
  }

}

A: You need to make sure whatever component you're listening for KeyEvents on has the focus.
Once you click the button, that button has focus instead of your JPanel. More info here: http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html
You can use the requestFocusInWindow() method on your JPanel, or you can call setFocusable(false) on your JButton.
Or you could use key bindings instead: http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html

A: Add VGKernel.this.grabFocus(); to the ActionListener to return focus to the VGKernel panel after clicking the button.
start.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        starten = true;
        VGKernel.this.grabFocus();
    }
});


text:
Q: How to convert time string to custom Date format? I have a column in my spark dataframe called "Fiscal Month" in which the values are "January 2015","February 2015" and so on. So the format is "Month Year" which has the datatype String.
How do I convert this to a date format using Spark SQL?

A: using unix_timestamp something like
import org.apache.spark.sql.functions.unix_timestamp

df.select(unix_timestamp($"Fiscal Month","MMMM yy"))

See functions object.


text:
Q: Update a column value, replacing part of a string I have a table with the following columns in a MySQL database
[id, url]

And the URLs are like:
 http://domain1.example/images/img1.jpg

I want to update all the URLs to another domain
 http://domain2.example/otherfolder/img1.jpg

keeping the name of the file as is.
What's the query must I run?

A: You need the WHERE clause to replace ONLY the records that complies with the condition in the WHERE clause (as opposed to all records). You use % sign to indicate partial string: I.E.
LIKE ('...//example.com/images/%');

means all records that BEGIN with "...//example.com/images/" and have anything AFTER (that's the % for...)
Another example:
LIKE ('%http://example.com/images/%')

which means all records that contains "http://example.com/images/"
in any part of the string...

A: UPDATE urls
SET url = REPLACE(url, 'domain1.example/images/', 'domain2.example/otherfolder/')

A: Try using the REPLACE function:
mysql> SELECT REPLACE('www.example.com', 'w', 'Ww');
        -> 'WwWwWw.example.com'

Note that it is case sensitive.

A: UPDATE yourtable
SET url = REPLACE(url, 'http://domain1.example/images/', 'http://domain2.example/otherfolder/')
WHERE url LIKE ('http://domain1.example/images/%');

relevant docs: http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_replace

A: First, have to check
SELECT * FROM `university` WHERE course_name LIKE '%&amp%'

Next, have to update
UPDATE university
SET course_name = REPLACE(course_name, '&amp', '&') WHERE id = 1

Results: Engineering &amp Technology => Engineering & Technology

A: Try this...
update [table_name] set [field_name] =
replace([field_name],'[string_to_find]','[string_to_replace]');


text:
Q: IE9 not showing page content on scroll down This issue is occurring on IE 9, all pages are displayed properly in IE 8 and Firefox. In IE9 all content below the scrollbar is blanked out. The page shows properly for the page on display, but the content below if scrolled down shows blank. This happens for all pages in the Application for IE9 only.
is there an issue with a particular style in IE9?
I have attached the screenshot.

Thanks in advance


text:
Q: plsql dbms_xmlgen.getxmltype change xml tag format We have been using SQL developer's database export function to create some data dump files. The file format looks like this:

<?xml version='1.0'  encoding='Cp1252' ?>
<RESULTS>
  <ROW>
      <COLUMN NAME="A_ID"><![CDATA[3]]></COLUMN>
      <COLUMN NAME="B_ID"><![CDATA[A3V09LJAF]]></COLUMN>
  </ROW>
  <ROW>
      <COLUMN NAME="A_ID"><![CDATA[5]]></COLUMN>
      <COLUMN NAME="B_ID"><![CDATA[4FAPU90FSD]]></COLUMN>
  </ROW>
</RESULTS>

But recently the management decided to automate the process, one option is to use spool:
SPOOL 'D:\SOME\PATH\TO\DIR\1.XML'
SELECT dbms_xmlgen.getxmltype('SELECT A_ID, B_ID FROM SOME_TABLE') FROM DUAL;
SPOOL OFF;

However the dbms_xmlgen.getxmltype gives different tag type in the exported file:

 <ROWSET>
   <ROW>
     <A_ID>3</A_ID>
     <B_ID>A3V09LJAF</B_ID>
   </ROW>
   <ROW>
     <A_ID>5</A_ID>
     <B_ID>4FAPU90FSD</B_ID>
   </ROW>
 </ROWSET>

Is there a way to change the TAG format and add the CDATA to be exact as SQL developer export file?
Thank you for your time.

A: Perhaps an easier way would be use SQLcl, which has the same "engine" as SQL Developer.  Thus in SQLcl you would do this
SQL> SET SQLFORMAT XML
SQL> SELECT * FROM emp WHERE deptno = 20;
<?xml version='1.0'  encoding='UTF8' ?>
<RESULTS>
        <ROW>
                <COLUMN NAME="EMPNO"><![CDATA[7369]]></COLUMN>
                <COLUMN NAME="ENAME"><![CDATA[SMITH]]></COLUMN>
                <COLUMN NAME="JOB"><![CDATA[CLERK]]></COLUMN>
                <COLUMN NAME="MGR"><![CDATA[7902]]></COLUMN>
                <COLUMN NAME="HIREDATE"><![CDATA[17-DEC-80]]></COLUMN>
                <COLUMN NAME="SAL"><![CDATA[800]]></COLUMN>
                <COLUMN NAME="COMM"><![CDATA[]]></COLUMN>
                <COLUMN NAME="DEPTNO"><![CDATA[20]]></COLUMN>
        </ROW>

Download SQLcl from here
https://www.oracle.com/au/tools/downloads/sqlcl-downloads.html


text:
Q: DataGrid area not filled with Cells How can I access DataGrid area not filled with Cells?

I want to add context menu for this area only

A: You can assign a ContextMenu to the DataGrid itself for the "Blank" area, but it will also appear for any rows you right-click on, if you don't have a different context menu assigned to the rows (or the "DataGrid.RowStyle" property).
The 'workaround' is to simply assign a different context menu to the rows, specifically.
<DataGrid>
    <DataGrid.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Menu Item in Blank Area" />
        </ContextMenu>
    </DataGrid.ContextMenu>
    <DataGrid.RowStyle>
        <Style TargetType="{x:Type DataGridRow}">
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu>
                        <MenuItem Header="Menu Item just for Populated Rows" />
                    </ContextMenu>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

A: Based on your comment to a previous answer, I see that you want to set one ContextMenu on your headers, and a separate one for your cells and empty space. I was able to set separate ContextMenus by overriding the Template:
<Window x:Class="Apc_System_Generator.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Resources>
            <ResourceDictionary>
                <ContextMenu x:Key="cmenu">
                    <MenuItem Header="FOO" />
                    <MenuItem Header="BAR" />
                </ContextMenu>
                <ContextMenu x:Key="omenu">
                    <MenuItem Header="LOL" />
                    <MenuItem Header="WUT" />
                </ContextMenu>
            </ResourceDictionary>
        </Grid.Resources>
        <DataGrid Name="LOL" AutoGenerateColumns="True" ContextMenu="{StaticResource cmenu}">
            <DataGrid.Template>
                <ControlTemplate TargetType="{x:Type DataGrid}">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="*" />
                        </Grid.RowDefinitions>
                        <DataGridColumnHeadersPresenter Grid.Row="0" ContextMenu="{StaticResource omenu}" />
                        <DataGridRowsPresenter Background="gray" Grid.Row="1" IsItemsHost="True" />
                    </Grid>
                </ControlTemplate>
            </DataGrid.Template>
        </DataGrid>
    </Grid>
</Window>


text:
Q: Upper bound for Poisson distribution For a Poisson random variable $Z$ with the parameter $\lambda,\,$ what would be a good upper bound (sub-exponential type perhaps?) for $P(Z \geq \frac{\lambda}{2})?$
The issue here is that I can't use the large deviation bound for Poisson. What would be an alternative argument?

A: $P(Z \ge \frac \lambda 2) \to 1$ as $\lambda$ increases, with jumps every time $\lambda$ is an even integer.
So $1$ is a trivial upper bound.
$1-e^{-\lambda}$ is slightly better, but is $P(Z \gt 0)$, so exact when $\lambda \le 2$ but not so brilliant for larger $\lambda$.
Empirically something like $1-0.1e^{-0.16 \lambda}$ looks better as an upper bound for $\lambda>2$.
For an empirical lower bound at least for $\lambda>1$, it seems $1-0.6e^{-0.15 \lambda}$ also seems to work reasonably.
This chart compares these bounds:

and the following chart shows the same bounds for the logarithm of the complementary probability with larger $\lambda$

A: Note: definitely worth checking the computations, and trivial things like the base of the logarithm. It's late here.
If you can show a sufficiently good bound of that sort for a Binomial random variables with parameters $n$ and $p$, then you will get what you want by applying it to $X^{(n)}\sim \mathrm{Bin}(n,\lambda/n)$ and taking the limit as $n\to \infty$:
$$
\mathbb{P}\{X^{(n)} \geq \lambda/2\} \xrightarrow[n\to\infty]{} \mathbb{P}\{Z \geq \lambda/2\}
$$
where $Z\sim \mathrm{Poisson}(\lambda)$. Now, using the computations by Thomas Ahle here, for $k := \frac{np_n}{2} = \frac{\lambda}{2}$, we get
$$
\mathbb{P}\{X^{(n)} > \lambda/2\} \leq 1- \frac{1}{\sqrt{4\lambda(1-\lambda/(2n))}}e^{-n D\left(\frac{p_n}{2} \,\big\|\, p_n\right)}
$$
where, again, $p_n := \frac{\lambda}{n}$. From the definition of the relative entropy and our $p_n$
$$
n D\left(\frac{p_n}{2} \,\big\|\, p_n\right) =  \frac{1-\log 2}{2}\cdot \lambda + o(1)
$$
and so
$$
\boxed{\mathbb{P}\{Z > \lambda/2\} \leq 1- \frac{1}{2\sqrt{\lambda}}e^{-\frac{1-\log 2}{2}\cdot \lambda} }
$$
Note that $\frac{1-\log 2}{2} \approx 0.153$, so this appears to be consistent with the empirical upper bound provided by Henry.

Why this behaviour is nearly tight (up to the low-order term in the exponent).
We also have, by standard bounds on Binomial r.v.'s, that
$$
\mathbb{P}\{X^{(n)} \leq \lambda/2\} \leq e^{-n D\left(\frac{p_n}{2} \,\big\|\, p_n\right)} \xrightarrow[n\to\infty]{}  e^{-\frac{1-\log 2}{2}\cdot \lambda}
$$
and so
$$
\boxed{\mathbb{P}\{Z > \lambda/2\} \geq 1-e^{-\frac{1-\log 2}{2}\cdot \lambda} }
$$


text:
Q: NIL when Parsing JSON I am trying to parse and get the values from this structure of JSON:
["mst_customer": 1, "data": {
    0 = 2;
    1 = 1;
    2 = 1;
    3 = "JAYSON TAMAYO";
    4 = "581-113-113";
    5 = 56;
    6 = on;
    7 = g;
    8 = jayson;
    9 = active;
    "app_access" = on;
    id = 2;
    "mst_customer" = 1;
    name = "Jayson Tamayo";
    status = active;
    territory = 1;
}, "status": OK, "staff_id": 2, "staff_name": Jayson Tamayo]

I use the following Swift code to get the values:
    (data: Dictionary<String, AnyObject>, error: String?) -> Void in
                    if error != nil {
                        print(error)
                    } else {

                        if let feed = data["data"] as? NSDictionary ,let entries = data["data"] as? NSArray{
                        for elem: AnyObject in entries{
                              if let staff_name = elem["name"] as? String{
                              print(staff_name)
                              }
                        }
                     }
    }

I am trying to get the name by using the keys name or staff_name. But I always get nil.

A: for elem: AnyObject in entries{
    if let songName = elem["name"] as? String{
       print(songName)
    }
}

//replace above code with below code

if let songName : String = entries["name"] as? String{
   print(songName)
}

A: you want to access staff_name, which is not in "data" variable ... you can simply get that like
 if error != nil {
     print(error)
  } else {
      if let name = data["staff_name"] as? String{
          print(name)
      }
  }


text:
Q: 2 threads entering a locked block of code at the same time I am attempting to allow only 1 thread at a time to enter a certain block of code thusly:
private static object lockObject = new object();

protected override void WndProc(ref Message message) {
    if (id != null) {
        id.ProcessMessage(message);

        lock(lockObject) {
            if (id.ScanCode.Length > 4) {
                ...
            }
        }
    }

    base.WndProc(ref message);
}

Sometimes 2 threads get in there and both execute the code. I have confirmed this in the VS debugger. Sometimes only 1 thread gets in, which is good, but at least half the time, 2 threads get in -- never more than 2 it seems.
Inside that if-block I'm doing this:
id.ScanCode = string.Empty;
return;

To me it seems this should prevent the 2nd thread from entering, if it did get blocked. But maybe I'm doing this wrong. What's the simplest way to prevent the 2nd thread from getting in there? Could they be entering simultaneously?

A: Lock does not prevent any number of threads from ever entering that block. It just delays them until it gets freed. It will only assure you that only one thread AT A TIME will enter that block of code. As soon as the first thread exists, the second will lock the code and run it. And so on...
If you need only the FIRST thread to execute that block of code, just set a flag once it first gets run and for the consecutive threads just check that flag first.


text:
Q: changing class to static blocks serialport datareceived event I am having trouble with SerialPort.DataReceived event being blocked by ShowDialog from MainWindow. Originally, the code worked as follows:
Printer connected to COM port using Windows Print Driver for operation. To check status, I must "move" windows printer COM port to COM1, and connect directly to the printer via SerialPort and send it a certain array of bytes. The printer will answer back >>LOW STOCK<< if out of paper or >>READY<< if status OK. I receive this through the serialport.datareceived event that I set up when switching the com port. If I get >>LOW STOCK<<, I continue to poll the printer over the serial port every 2 seconds.
public class PrintController
{
    private PrintMonitor DefaultPrintMonitor;

    public Printcontroller()
    {
        Initialize();
    }

    private void Initialize()
    {
        // Some code here to determine which printer type to load monitor for
        DefaultPrintMonitor = new PrintMonitor();
    }

}

And the Print Monitor:
public class PrintMonitor
{
    private SerialPort Port;
    private TimeoutManager TimeoutQueue = new TimeoutQueue();
    private readonly char[] PrinterStatusCommand = new char[7] { ... The printers report status command ...};

    public PrintMonitor() {}

    public void StartPrintMonitor()
    {
        Thread thread = new Thread(new ThreadStart(RefreshPrintQueue))
        {
            IsBackground = true
        };
        thread.Start();
    }

    private void RefreshPrintQueue()
    {
        // This checks the Printer's Queue for any jobs remaining
        // If the number of jobs = 0, all data has been transferred to the printer
        // and we can switch the COM port so the printer can be polled for it's status
        // Code omitted for brevity
        if (jobs.Count() > 0)
        {
            // This will wait 1000ms and execute the method RefreshPrintQueue
            TimeoutQueue.AddTimeout(RefreshPrintQueue, 1000);
        }
        else
        {
            TimeoutQueue.AddTimeout(GetStatus, 500);
        }
    }

    private void GetStatus()
    {
        // Connect windows print driver to COM1
        SetWindowsPrintDriver("COM1");
        // Connect to printer using new SerialPort
        ConnectSerialPrintDriver();
        // Poll the printer over new SerialPort connection
        QueryPrinterStatus();
    }

    private void ConnectSerialPrintDriver()
    {
        //Create new serial port to Port, and open
        Port.DataReceived += Port_DataReceived;
    }

    private void QueryPrinterStatus()
    {
        byte[] send = Encoding.ASCII.GetBytes(PrinterStatusCommand);
        Port.Write(send, 0, send.Length);
        TimeoutQueue.AddTimeout(QueryPrinterStatus, 2000);
    }

    private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        Thread.Sleep(100);
        SerialPort p = sender as SerialPort;
        string recv = p.ReadExisting().Trim();
        if (recv.Contains(">>READY<<"))
        {
            // Stop Polling loop
            TimeoutQueue.ClearAllTimeouts();
            DisconnectSerialPrintDriver();
            // Raises event to Main to close ShowDialog
        }
        else
        {
            // Raises event to Main to open ShowDialog
        }
    }

    private void DisconnectSerialPrintDriver()
    {
        // Closes/Disconnects serial port from printer
        // unsubscribes event listener
        // Sets Port to null and connects windows print driver back to printers COM port
        // Ready to accept print jobs again
    }

Believe it or not, this works very well. When the paper is reloaded in the printer, the dialog window showing the paper out message is dismissed.
However, I recently had to make a change to the print controller to make it a static class. Now, when I open the dialog window at Main, the Port_DataReceived event stops firing. The polling of the printer continues, and the responses just seem to back up until the dialog window is manually dismissed, and then I get one more dataReceived event with the results of all the polling that went on while showing the dialog window.
Can anyone tell me what could be happening here?


text:
Q: Error de Conexion a base de datos SQL Server Si yo otra vez. Aquí con otra duda. Ya había hecho una pregunta con respecto a la conexión entre SQL Server y PHP. Ahora debo hacer una conexión para la validación de datos en un formulario Login. Necesito que la pagina tome los datos que el usuario ingreso y los compare con los que estan en la base de datos SQL Server, si coinciden entra a otra pagina, si no, que muestre un mensaje de error. Cuando ejecuto todo en el localhost de xampp solo sale una pantalla en blanco y en el link de la pagina esta es el archivo PHP.
Aquí esta mi código HTML de la pagina que estoy desarrollando con el formulario incluido:
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="ventanaReportes.css">

    <title>¡Unete al parche! - Reportes Administrador</title>

Ventana Reportes Administrador - ¡Unete al parche!

            Página principal

            Home

        <textarea name="mensaje" rows="6" id="texto" readonly="readonly" disabled="disabled">Esta ventana es exclusiva para los administradores de la plataforma, tenga en cuenta que los administradores tienen más privilegios que los usuarios regulares.Para garantizar una mejor funcionalidad de protección a la privacidad y evitar inconvenientes entre los administradores y los usuarios le pediremos que se registre para poder acceder y verificar su rol como administrador. Si usted es usuario regular el ingreso sera fallido.

Si usted es administrador por favor digite la información solicitada en el siguiente formulario:
        </textarea>

        <form name="LoginAdmin" method="post" action="validar.php" class="login" id="formulario" onsubmit="return validacion()">
            Nombre Administrador*:

            <input type="text" id="AdminName" name="AdminName" placeholder="🔐Ingrese su nombre">

            Contraseña*:

            <input type="password" id="contrasena" name="contrasena" placeholder="🔐ej: 1234**">

            <input type="submit" value="Entrar" name="EnviarFormularioAdmin" class="button">
        </form>

© 2019 - Alcaldía de Fusagasugá

Y aqui esta mi codigo PHP que se encarga de la validacion del formulario Login
<?php
ini_set('display_errors', 0);

    if(isset($_POST['EnviarFormularioAdmin'])){
        //conectar a la base de datos
        $server = "AFTIC004";
        $base = array("Database"=>"UneteAlParche_BD", "UID"=> "codestack", "PWD"=>"jrdLpWad5ik3rFWatjLQ");
        try {
            $conexion = new PDO($server, $base);
            echo "Conexion exitosa";
        } catch (PDOException $e){
            echo "Fallo la conexión" . $e->getMessage();
        }
        $administrador=($_POST['AdminName']);
        $contraseña=md5($_POST['contrasena']);
        //establecer la consulta
        $consulta = "SELECT * FROM sisAdministrador WHERE IdAdmin = 1, Nombre = '$administrador' AND Password = '$contraseña' AND IdRol = 3";
        $resultado= sqlsrv_query ($conexion, $consulta);

        if($row = sqlsrv_fetch_array($resultado)){
            if($row['Password'] == $contraseña){
                session_start();
                $_SESSION['Nombre'] = $administrador;
                echo "Datos correctos";
                header("Location:https://localhost/Ventana%20/VentanaReportesAdminIngresado.php");
            }else{
                echo "Hubo algun error en los datos ingresados";
                header("Location:validar.php");
                exit();
            }
        }else{
            echo "Ocurrio algun error";
            exit();
        }
    }
?>

Me seria muy útil si me explican paso a paso lo que debo hacer para resolver este problema y pues, obviamente, para aprender. Les agradecería su colaboración y comprensión

A: Es bastante dificil de leer tu código, te recomendaria que:

*

*Aprendas php orientado a objetos

*Patron de diseño MVC (Modelo, Vista, Controlador)
Te va ayudar mucho dominar lo antes mencionado, hay muchos videotutoriales para aprender en youtube.
Aca te sugiero uno que me gusto mucho:
enter link description here