text:
Q: Incorrect value after calling promise async function in js I'm trying to make a function that checks how many records in database and sends the number to variable:
var records = -1;

async function howManyRecords() {
    let myPromise = new Promise(function (resolve) {

        DB.transaction(function (tx) {
            tx.executeSql('SELECT count(*) AS mycount FROM DemoTable', [], function (tx, rs) {
                records = rs.rows.item(0).mycount;
                resolve();
            },);
        });
    });
    await myPromise;
    console.log("records from promise function: " + records);
    return myPromise;
}

Then I would like to use the number in another functions, for example display in the console log when device is ready:
onDeviceReady.then(function () {
    howManyRecords();
    console.log("after calling function records are: " + records);
}

The howManyRecords function counts records correctly, but then variable records is not correct:
IMG: after calling function records are: -1 // records from promise function: 5
I really need some help, I'm new to the topic and stuck here since a long time and can't go on.
I'm using cordova sqlite.

A: Try this:
onDeviceReady.then(async function () {
await howManyRecords();
console.log("after calling function records are: " + records);}

A: This problem is not for your asynchronous behavior. Here actually you re assign the value of records variable in the function. That's why the value of records change.
If you want to get rid of from the issue you can take another variable in the function for counting records. And initialize the variable with let. As let is block scope, that's why its' value will not go through the function.

var records = -1;

async function howManyRecords() {
    let records = -1;

    let myPromise = new Promise(function (resolve) {

        DB.transaction(function (tx) {
            tx.executeSql('SELECT count(*) AS mycount FROM DemoTable', [], function (tx, rs) {
                records = rs.rows.item(0).mycount;
                resolve();
            },);
        });
    });
    await myPromise;
    console.log("records from promise function: " + records);
    return myPromise;
}


text:
Q: Passing event to DOM element underneath I have developped this web application which uses Microsoft Seadragon Technology.
On top of the Seadragon viewport, the user can draw measurements and annotations.  Those annotations are drawn into a Canvas on top of the Seadragon.
In order to be able to edit the annotation, my application has to be into "Edit Annotation" mode.  What this mode does, it simply removes the CSS style pointer-events: none; from the annotation canvas.  When this mode is off, I put back the pointer-events: none; to the annotation canvas so that the Seadragon viewport can receive the mouse events.
The problem I have is that the pointer-events property is not supported by IExplorer and Opera.  Since the annotation canvas is drawn on top of the Seadragon viewport, in IExplorer9 and Opera, I can NEVER have the mouse event to reach the Seadragon Viewport.
I gave it a try by passing the mouseevent to the DOM element used to created the Seadragon viewport, but it does not seem to work.
$('#annotationCanvas').mousedown(function(){ $('#seadragonVP').trigger('mousedown'); });
But this does not work...
Can someone help me on how to :

*

*Either pass the mouse event to elements underneath another element

*or to call directly the mouse events from Seadragon

You can have a look at the application at : http://fibics.interplex.ca
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: AssertionError [ERR_ASSERTION]: Missing expected rejection (Error) So, I am trying to write some unit tests for my code using MochaJS, SinonJS, rewire, chai and assert. An i got the following error:
 1) async function addOneRoom(db, newRoom)
   should reject error when the maximum room number has been reached:
 AssertionError [ERR_ASSERTION]: Missing expected rejection (Error).
  at async Context.<anonymous> (test\test.js:33:9).

So the function I am testing is the following one:
async function addOneRoom(db, newRoom) {
const roomNumber = await createRoomNumber(db, newRoom.floor);

if (roomNumber !== 0) {
    newRoom.roomNumber = roomNumber;
    const result = await db.rooms.insertOne(newRoom);
    return newRoom
} else return new Error("No room can be added on this floor. The maximum numar of rooms has been reached")}

And my unit test for it is:
describe("async function addOneRoom(db, newRoom)", () => {
const addOneRoom = rewired.__get__("addOneRoom")
const sandBox = sinon.createSandbox()

it("should reject error when the maximum room number has been reached", async () => {
    const newRoom = {
        floor: 1,
        sqm: 20,
        capacity: 5,
        features: {
            videoProjector: 1,
            stage: 2
        }
    }

    const insertOne = sandBox.stub().returns()
    const mockedCreateRoomNumber = sandBox.stub().resolves(0)

    const db = {
        rooms: { insertOne }
    }

    const stubbedRoomNumber = rewired.__set__({ createRoomNumber: mockedCreateRoomNumber })
    await assert.rejects(addOneRoom(db, newRoom), new Error("No room can be added on this floor. The maximum numar of rooms has been reached"))

    // sandBox.assert.calledOnceWithExactly(stubbedRoomNumber)
    sandBox.assert.calledOnceWithExactly(insertOne, {newRoom})

    const order = [
        // stubbedRoomNumber,
        insertOne
    ]

    sandBox.assert.callOrder(...order)
    stubbedRoomNumber()
})

I would appreciate any help!

A: Don't return the Error, throw it:
throw new Error("No room can be added on this floor. The maximum numar of rooms has been reached")}

Returning an Error is no different from returning anything else, and will not cause a promise rejection.


text:
Q: What are all the ways to find repetitive elements in array in javascript I have been asked in the interview to find repetitive elements in array. I have found using for loop, but the interviewer asked for more improved way to find out, with effect to performance with out for loop . I am beginner in exploring Java script. Could any one help to find other methods for finding repetitive elements in array. Below is my code for the answer

var a = [1,2,3,3,4,4,5,5,6,7,8,8,9,10,11,12];

var repeatElements = [];
for (var i=0;i<a.length;i++){
 for(var j=1+i; j<a.length;j++){
 if (a[i]===a[j]){
repeatElements.push(a[i]);
}

}
}
console.log(repeatElements);

I have checked the answer of this stack overflow question Get all unique values in a JavaScript array (remove duplicates) Whether using filter for finding repetitive would be more efficient way?

A: A good way to do this in linear time is to use a frequency table:
var a = [1,2,3,3,4,4,5,5,6,7,8,8,9,10,11,12];

var frequencyTable = {};
var repeatElements = [];
for (var i=0; i<a.length; i++){
 if (frequencyTable[a[i]]){
  frequencyTable[a[i]]++;
  repeatElements.push(a[i]);
 } else {
  frequencyTable[a[i]] = 1;
 }
}

console.log(repeatElements);

This way you only loop through the array once.

A: Your solution has O(n^2) complexity. I think interviewer was expecting you to provide O(n) solution, which involves usage of some sort of dictionary of repetitive items. That looks like this:

const a = [1,2,3,3,4,4,5,5,6,7,8,8,9,10,11,12];

function getRepetitives(arr) {
  const itemsDuplicates = {}

  arr.forEach(item => {
    itemsDuplicates[item] = itemsDuplicates.hasOwnProperty(item)
      ? itemsDuplicates[item] + 1
      : 1
  })

  const repetitives = Object.entries(itemsDuplicates).filter(([ k ,v ]) => v > 1).map(([k]) => k)

  return repetitives
}

console.log(getRepetitives(a))


text:
Q: Using volume for mounting a file I'm creating a volume like this:
docker volume create php

and want to mount a single file /etc/php.ini while running the container:
docker run -it -v php:/etc/php.ini image-name

This throws an error:
docker: Error response from daemon: readdirent: not a directory.
See 'docker run --help'.

Can I use volumes for this purpose or they are meant to handle directories only? What could be the solution here?

A: According to this answer:

when you create a named volume and run a service/container with docker run -v my_volume:/root/volume my_container, data is stored in /var/lib/docker/volumes/my_volume/_data

Following this affirmation, it is unpossible to create a named volume and mount it as a file inside a container.


text:
Q: MALFORMED_REQUEST on PayPal execute payment I've lost almost two whole days trying to solve PayPal related issues.
I'm trying to execute a payment after user's approval, but I'm getting MALFORMED_REQUEST everytime I send the Curl request.
def execute
 # Get the access_token
    token = get_paypal_token(false)
    payer_id = params[:PayerID]
    payment_id = params[:paymentId]
    # Creating the data object
    stringJson = {:payer_id => "#{payer_id}"}

    # You can see that I hard-coded the payer_id to ensure the JSON is correct
    curlString = `curl -v -H "Authorization: Bearer #{token}" -H "Content-Type:     application/json" -d '{"payer_id" : "QULQSFESGMCX2"}' https://api.sandbox.paypal.com/v1/payments/payment/#{payment_id}/execute/`
end

And the response is:
"{\"name\":\"MALFORMED_REQUEST\",\"message\":\"The request JSON is not well formed.\",\"information_link\":\"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST\",\"debug_id\":\"6431589715660\"}"

A: Looks like you are running it from windows. I tried your command from my windows and my test server receiving the json as '{payer_id. It is happening because of your single quote.
I have changed the single quotes into double and it is working fine here with me.
-d "{\"payer_id\" : \"QULQSFESGMCX2\"}"

You can run the curl command from the console and see what happens, after that you can push it inside your ruby script code.


text:
Q: Nuxt i18n does not load cookie language in root directory Whenever I select a language in my application, it saves this parameter in the "lang" cookie, but accessing the root (http://localhost) without the language path (http://localhost/en) it loads the default language "pt", even the cookie set in another language "en" or "es". This is normal? Or is there any configuration for this type of situation?
[
  'nuxt-i18n',
  {
    locales: [
      {
        code: 'en',
        file: 'en.js'
      },
      {
        code: 'es',
        file: 'es.js'
      },
      {
        code: 'pt',
        file: 'pt.js'
      }
    ],
    lazy: true,
    langDir: 'lang/',
    parsePages: false,
    strategy: 'prefix',
    defaultLocale: 'pt',
    rootRedirect: 'pt',
    detectBrowserLanguage: {
      useCookie: true,
      cookieDomain: null,
      cookieKey: 'lang',
      alwaysRedirect: false,
      fallbackLocale: 'pt'
    },
  }
]

Method change lang:
changeLanguage(lang) {
        this.locale = lang
        this.$i18n.setLocale(lang)
        this.$moment.locale(lang);
    },

A: I found that I needed to set the alwaysRedirect parameter to true, it forces the redirect by the cookie.
detectBrowserLanguage: {
  alwaysRedirect: true
},


text:
Q: Replacing a symbol in a .txt file Alright, I've been given a program that requires me to take a .txt file of varying symbols in rows and columns that would look like this.
..........00
...0....0000
...000000000
0000.....000
............
..#########.
..#...#####.
......#####.
...00000....

and using command arguments to specify row and column, requires me to select a symbol and replace that symbol with an asterisk. The problem i have with this is that it then requires me to recur up, down, left, and right any of the same symbol and change those into an asterisk.
As i understand it, if i were to enter "1 2" into my argument list it would change the above text into.
**********00
***0....0000
***000000000
0000.....000
............
..#########.
..#...#####.
......#####.
...00000....

While selecting the specified character itself isn't a problem, how do i have any similar, adjacent symbols change and then the ones next to those. I have looked around but can't find any information and as my teacher has had a different subs for the last 3 weeks, i havent had a chance to clarify my questions with them. I've been told that recursion can be used, but my actual experience using recursion is limited. Any suggestions or links i can follow to get a better idea on what to do? Would it make sense to add a recursive method that takes the coordinates given adds and subtracts from the row and column respectively to check if the symbol is the same and repeats?

A: Load in char by char, row by row, into a 2D array of characters. That'll make it a lot easier to move up and down and left and right, all you need to do is move one of the array indexes.
You can also take advantage of recursion. Make a function that changes all adjacent matching characters, and then call that same function on all adjacent matching characters.


text:
Q: Минимальный элемент в столбце двумерного массива. Питон Нужна критика метода решения и подсказка по вопросу (даже если способ решения логически неверен, сам вопрос остается актуальным для понимания питона как такового).
Решаю задачу на сортировку. Есть N сортированных списков чисел, они объединяются в новый отсортированный список. Естественно, метод sort() использовать нельзя))
На степике была задача с двумя списками (и описание метода решения), но теперь число списков произвольное. Вначале я пытался приспособить метод объединения двух списков к ситуации, когда число списков равно N. Но потом отказался от этой идеи, т.к. решил что тут не поможет простая экстраполяция, да и пришла другая идея решения.
Допустим, у нас есть список из трех списков:
[[1, 2, 3, 7, 12]
 [4, 6, 45, 655]
 [23, 56, 789]]

Тут даже не надо учитывать тот факт, что у вложенных списков может быть разная длина. Делаю цикл, в котором сравниваю элементы столбца имеющие индекс i[0] и минимальное число в столбце добавляю в пустой результирующий список. После этого удаляю это минимальное число из первого списка и повторяю поиск, в результате чего первый "список списков" становится пустым, а результирующий наполняется элементами в порядке возрастания.
Но возникает ошибка при попытке найти минимум из элементов столбца:
for i in range(a):
    print(min(i[0]))

TypeError: 'int' object is not subscriptable

Ошибка получается и если сделать через i-j:
for i in range(a):
    for j in i:
        print(min(i[0]))

При этом если я вывожу элементы первого столбца:
for i in bl:
    print(i[0], end=' ')

то благополучно получаю 1, 4, 23. Но я ведь перебираю первые элементы вложенных списков, а не пытаюсь перебрать сам элемент, на что мне указывает питон.
В интернете не нашел разбора задач на нахождение минимального (либо максимального) элемента столбца двумерного списка. Но ведь это должно как-то решаться, задача по идее нередкая.
Что думаете по поводу самого метода решения? (помня что по условия метод sort не используем).
Спасибо!
Кусок кода с вводом числа списков и проверкой вывода:
a = int(input())
result = []
bl = []
for i in range(a):
    bl.append(list(map(int, input().split())))

print('\n'.join(map(str, bl)))

for i in bl:
    print(i[0], end=' ')   # вывожу элементы первого столбца

for i in range(a):
    print(min(i[0]))  # ищу минимум в первом столбце (и получаю сообщ. об ошибке)

A: Идея подхода у вас верная, реализация подкачала.
В общем, слияние К сортированных списков наиболее выгодно осуществлять с помощью структуры данных "Очередь по приоритетам", обычно она делается на основе бинарной кучи (binary heap).
Возможная реализация:

*

*в кучу складывается К пар - (индекс в списке; номер списка). Можно сделать триплет, первым элементом ещё добавить значение соответствующего элемента.

*на каждом шаге снимается вершина кучи - самый маленький из текущих элементов, его значение идёт на выход, индекс соответствующего списка увеличивается, если он не вышел за пределы - то триплет с обновленным значением и индексом снова кладется в кучу

*повторяется до исчерпания кучи

По большому счету, слияние двух списков - то же самое, только куча из двух элементов неявная.
В Python есть стандартный модуль heapq, с его помощью легко организовать кучу над списком (триплетов или пар). Создали список туплей М, затем heapq.heapify(М)  на каждом шаге с=heapq.heappop(М), heapq.heappush(М, new_c)


text:
Q: Split long word/string in smaller words/strings in javascript I want to split a word like microsoft in to mic ros oft.

A: You can also split word to each letter in javascript. Hope this will help you.
var txt="microsoft";

txtArray=txt.split('');
txtLength=txtArray.length;

var text="";
for(var i=1;i<=txtLength;i++) {

  text+=txtArray[i-1];
  if(i%3==0) text+=" ";
}
  alert(text);


text:
Q: Connectedness of $\mathbb{C} \setminus E$ given $E$ is connected. Suppose that $E \subset \mathbb{C}$ is connected. Is it true that $\mathbb{C} \setminus E$ is also connected ?
The only few examples I have tell me it seems True but maybe there is a simple counter-example or a simple proof to this. Any help ?


text:
Q: How to order nodes inside a subgraph in dot I can't get the nodes to appear in the same order I wrote them
Here is the code I'm trying to use with dot:
digraph G {
        fontname = "Hilda 10"
        rankdir=LR
        splines=line
        nodesep=.08;
        ranksep=1;
        edge [color=black, arrowsize=.5];
        node [fixedsize=true,style=filled,color=none,fillcolor=gray,shape=circle,fontcolor=black]

        subgraph cluster_0 {
                color=none;
                node [style=filled, color=white, penwidth=15,fillcolor=gray shape=circle];
                { l10 l11 }
                label = Input;
        }

        subgraph cluster_1 {
                color=none;
                node [style=filled, color=white, penwidth=15,fillcolor=gray shape=circle];
                { l20 l21 l22 }
                label = Output;
        }

        l10 -> l20;
        l10 -> l21;
        l10 -> l22;
        l11 -> l20;
        l11 -> l21;
        l11 -> l22;
}

In my second column I was hoping to get l20 on top followed by l21 and l22 on the bottom, but instead I'm getting the image below, with l21 on top and l20 on the bottom
Result
I also tried with:
        rankdir=TB

...
        rank=same
        l20 -> l21 -> l22 [style = invis]

...
      edge [constraint=false]
        l10 -> l20;
        l10 -> l21;
        l10 -> l22;
        l11 -> l20;
        l11 -> l21;
        l11 -> l22;

but this way the first column loses its vertical centering
2nd try

A: A really annoying problem.  There are already MRs against this problem.  (search https://gitlab.com/graphviz/graphviz/-/issues for "order")
Here is a solution, but it requires changing the ranking and then adding one invisible node (plus other tweaks).
digraph G {
        fontname = "Hilda 10"
//       rankdir=LR  // change ranking
        splines=line
  ranksep=.05
  nodesep=.05
        edge [color=black, arrowsize=.5];
        node [fixedsize=true,style=filled,color=none,fillcolor=gray,shape=circle,fontcolor=black]

        subgraph cluster_0 {
                color=none;
                node [style=filled, color=white, penwidth=15,fillcolor=gray shape=circle];

                {
        // add an inviz node to drop nodes down 1 rank
        spacer1 [label="" style=invis]
        spacer1 -> l10 [minlen=1 style=invis]
        edge [style=invis minlen=2]  // 2 ranks between
        l10 -> l11
        }
                label = Input;
        }

        subgraph cluster_1 {
                color=none;
                node [style=filled, color=white, penwidth=15,fillcolor=gray shape=circle];
                { XXrank=same
        XXordering=out
        edge [style=invis]

        edge[minlen=2]
        l20 -> l21 -> l22
        }
                label = Output;
        }

edge[constraint=false]
        l10 -> l20;
        l10 -> l21;
        l10 -> l22;
        l11 -> l20;
        l11 -> l21;
        l11 -> l22;
}

Giving:


text:
Q: I want to extract values of cx,cy,r which all reside in column 3 Below is my sample data in CSV file
filename, file_size, region_shape_attributes
1.jpg, 2551045, {"name":"circle","cx":371,"cy":2921,"r":73}
2.jpg, 2551045, {"name":"circle","cx":505,"cy":2951,"r":62}
3.jpg, 2551045, {"name":"circle","cx":619,"cy":2865,"r":83}
4.jpg, 2551045, {"name":"circle","cx":769,"cy":2793,"r":82}
5.jpg, 2551045, {"name":"circle","cx":885,"cy":2669,"r":87}

I want output as follow:
name   cx  cy   r
circle 371 2921 73
circle 371 2921 73
circle 371 2921 73

A: import ast

# read your data
d = pd.read_clipboard()

# transform string to dictionary
d["region_shape_attributes"] = d["region_shape_attributes"].apply(lambda x: ast.literal_eval(x))

# convert column of dictionary to dataframe
pd.DataFrame(list(d['region_shape_attributes']))

It gives you the result.
    cx  cy      name    r
0   371 2921    circle  73
1   505 2951    circle  62
2   619 2865    circle  83
3   769 2793    circle  82
4   885 2669    circle  87

A: Read CSV file in a Dataframe:
df=pd.DataFrame({'img':['1.jpg','2.jpg','3jpg','4.jpg','5.jpg'],'id':[2551045,2551045,2551045,2551045,2551045],'dict':[{"name":"circle","cx":371,"cy":2921,"r":73},
                                       {"name":"circle","cx":505,"cy":2951,"r":62},
                                      {"name":"circle","cx":619,"cy":2865,"r":83},
                                      {"name":"circle","cx":769,"cy":2793,"r":82},
                                      {"name":"circle","cx":885,"cy":2669,"r":87}]})

use .apply(pd.Series)
df['dict'].apply(pd.Series)

Output:
   cx   cy      name    r
0   371 2921    circle  73
1   505 2951    circle  62
2   619 2865    circle  83
3   769 2793    circle  82
4   885 2669    circle  87

A: Old School way (without any package/module):
list.txt:
filename, file_size, region_shape_attributes
1.jpg, 2551045, {"name":"circle","cx":371,"cy":2921,"r":73}
2.jpg, 2551045, {"name":"circle","cx":505,"cy":2951,"r":62}
3.jpg, 2551045, {"name":"circle","cx":619,"cy":2865,"r":83}
4.jpg, 2551045, {"name":"circle","cx":769,"cy":2793,"r":82}
5.jpg, 2551045, {"name":"circle","cx":885,"cy":2669,"r":87}

and then:
logFile = "list.txt"

with open(logFile) as f:
    content = f.readlines()

# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]

dict_list = []
for line in content[1:]:
    l = line.split("{", 1)[1].strip("}")
    dict_list.append(l)

print("name \t", end="")
print("cx \t\t", end="")
print("cy \t\t", end="")
print("r \t", )
for elem in dict_list:
    x = elem.split(",")
    print(x[0].split(":", 2)[1].replace('"', " "), end = "")
    print(x[1].split(":", 2)[1].replace('"', " "), "\t", end = "")
    print(x[2].split(":", 2)[1].replace('"', " "), "\t", end = "")
    print(x[3].split(":", 2)[1].replace('"', " "), "\t")

OUTPUT:
name    cx      cy      r
 circle 371     2921    73
 circle 505     2951    62
 circle 619     2865    83
 circle 769     2793    82
 circle 885     2669    87

A: use below code :
csv_data=pd.read_csv(<file path>,sep=' ')
csv_data.columns=['Field1','Field2','Field3']
name=[]
cx=[]
cy=[]
r=[]
for i in csv_data['Field3']:
    list_i=i.split(',')
    name.append(list_i[0].split(':')[1])
    cx.append(list_i[1].split(':')[1])
    cy.append(list_i[2].split(':')[1])
    r.append(list_i[3].split(':')[1].replace('}',''))
df_result=pd.DataFrame({'name':name,'cx':cx,'cy':cy,'r':r})
print (df_result)

output based on input given above:
   cx    cy      name   r
0  371  2921  "circle"  73
1  505  2951  "circle"  62
2  619  2865  "circle"  83
3  769  2793  "circle"  82
4  885  2669  "circle"  87


text:
Q: WPF Thread dead lock may i find useful answer from you.
I have WPF application fetching the data from API, I have thread deadlock when i fire following code
private List<Clinic> _clinics;
        public List<Clinic> Clinics {
            get { return _clinics; }
            set { _clinics = value; OnPropertyChanged(); }
        }

        private Clinic _selectedClinic;
        public Clinic SelectedClinic {
            get { return _selectedClinic; }
            set {
                _selectedClinic = value; OnPropertyChanged();
                if (value != null)
                    OnSelectClinic(value).Wait();
            }
        }
private async Task OnSelectClinic(Clinic clinic) {
            try {
using (var request = await Client.GetAsync("URL OF API")) {
                if (request.IsSuccessStatusCode){
StaffList = await request.Content.ReadAsAsync<Staff>();
}

                var error = await request.Content.ReadAsStringAsync();
                throw new Exception(error);
            }
            } catch (Exception e) {
                Debug.WriteLine(e);
            }
        }

this is the view model, and Clinics, selectedClinic and Staff are binding to View.XAML
and here is the API Method
[HttpGet("FindAllByClinic/{clinicId}")]
        public async Task<IActionResult> FindAllByClinic(int clinicId) {
            try {
                return Ok(_mapper.Map<List<Staff>>(await _staffRepository
                    .FindAllBy(clinicId)));
            } catch (Exception e) {
                return BadRequest(e.Message);
            }
        }

Here is StaffRepository method :
public async Task<ICollection<Staff>> FindAllBy(int clinicId, int medicalPointId) {
            var persons = await Context.Persons.FromSql("EXEC HR.GetPersonsByClinicId @ClinicId = 0," +
                                                        $"@EncryptPassword = '{DecryptPassword}'").ToListAsync();

            var staffs = await Context.Staff
                .Include(e => e.StaffClinics)
                .ThenInclude(e => e.Clinic)
                .ThenInclude(e => e.ClinicMedicalPoints)
                .Where(e => e.StaffClinics.Any(c => c.ClinicId == clinicId
                                                    && c.Clinic.ClinicMedicalPoints.Any(m => m.MedicalPointId
                                                    == medicalPointId)))
                .ToListAsync();

            foreach (var staff in staffs) {
                staff.Person = persons.FirstOrDefault(e => e.Id == staff.PersonId);
            }

            return staffs;
        }

the problem is when i select a clinic from combobox the entire application freeze
Can any one give me suggestions or correct my code if I Have mistakes please

A: public Clinic SelectedClinic {
            get { return _selectedClinic; }
            set {
                _selectedClinic = value; OnPropertyChanged();
                if (value != null)
                    OnSelectClinic(value).Wait();
            }
        }

This setter is super bad, because:

*

*It raises an event with OnPropertyChanged - that's okay - but then it continues to perform a costly operation in the setters body. You're already rasing an event, maybe something should subscribe to it and perform the OnSelectClinic instead?

*You're blocking on async code, which is a sin that causes deadlocks. Normally the solution is to replace blocking waits with awaits, but in this case you need to redesign so that a property setter is not responsible for firing and awaiting this operation.


text:
Q: An arabic phrase 'not doing something to a person's likings, deficient' equivalent? The phrase in arabic is 'مقصر في شيء', it literally means 'deficient in something'. So for example, if a wife said it about her husband, it would  mean that he's doing some of what is asked and expected of him, but not enough, or not to her liking. A friend can also say it to a friend, it may mean that he hasn't asked about his health, work or even life as often as usual; he is not caring as is expected of him.
It can also mean not helping, not being there, a lack of presence, a lack of doing what you should be doing towards someone/something.
A government or a company can also be a victim of this, towards their people and employees respectively.
It's a criticism, usually said out of love.

A: fall short of might encompass what you're after.
fall short of: fail to satisfy, as of expectations. (thefreedictionary.com)
How was I supposed to know I was doing something wrong or falling short of her expectations as a friend if she didn't say a word?

A: Stubborn comes to mind.

You're so stubborn, why won't you come to the zoo with us?!
My wife is so stubborn because she refuses to finish her education.
This child is so stubborn.  He will not eat his broccoli.

http://www.merriam-webster.com/dictionary/stubborn

A: Inconsistent, Capricious, or Unreliable come to mind. But since you mentioned its done out of love, I think inconsistent would work work pretty well.

A: When it is said by the person who is not doing something enough as you expect, or not doing as s/he should be/want to, it usually means that I care about you and I'm aware that I had not been caring enough - in an apologetic tone.
However, when it is said by the person who expects the care but not getting it, it is more like reproach s/he would say: You'd been negligent

Caring: painstaking or watchful attention
negligent: failing to exercise the care expected of a reasonably
prudent person in like circumstances

A: The term "half-assed" is used in US English to suggest an work product that is inferior, lacking, or wanting in some quality or characteristic.
oxforddictionaries.com
verb
Do (something) with little effort or care:
"they half-assed the redesign"
adjective
Done with little effort or care:
"he did a half-ass job"

A: If I felt this way about someone close I might say they are neglectful or neglecting me. This implies that they have a responsibility to provide some sort of support, and are failing to do so, and it's often said of a parent or spouse who fails to provide proper support to their dependents.


text:
Q: How to do multi-face tracking with ARKit 3? I am trying to make an application that supports multi-face tracking. The project has multiple buttons to change face assets. For very first time app detects multiple faces but when I click on the buttons to change the asset it does not work for both faces but only works with a new face. I am confused about what's wrong in my code?
    override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    guard ARFaceTrackingConfiguration.isSupported else { return }
    let configuration = ARFaceTrackingConfiguration()
    if #available(iOS 13.0, *) {
        configuration.maximumNumberOfTrackedFaces = 2
    } else {
        // Fallback on earlier versions
    }
    configuration.isLightEstimationEnabled = true
    sceneView.session.run(configuration)
}

func setAsset(strItem:String)
{
    let documentsUrl:URL =  (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL?)!
    let destinationFileUrl = documentsUrl.appendingPathComponent("\(strItem)")
    referenceNode = SCNReferenceNode(url: destinationFileUrl)!
    referenceNode.load()
    let faceGeometry = ARSCNFaceGeometry(device: sceneView.device!)!
    faceGeometry.firstMaterial!.colorBufferWriteMask = []
    occlusionNode = SCNNode(geometry: faceGeometry)
    occlusionNode.renderingOrder = -1
    referenceNode.scale = SCNVector3(0.0014, 0.0014, 0.0014)
    referenceNode.position = SCNVector3(0, 0.04, 0.07)
    contentNode!.addChildNode(occlusionNode)
    contentNode!.addChildNode(referenceNode)
}

extension ViewController : ARSessionDelegate {

    func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {

        print(anchors.count)
        for anchor in anchors where anchor is ARFaceAnchor {

            let faceAnchor = anchor as! ARFaceAnchor

            print("Session didAdd", faceAnchor.identifier)
        }
    }

    func session(_ session: ARSession, didUpdate anchors: [ARAnchor]) {

        for anchor in anchors where anchor is ARFaceAnchor {

            let faceAnchor = anchor as! ARFaceAnchor

            print("Session didUpdate", faceAnchor.identifier)

        }
    }
}

extension ViewController : ARSCNViewDelegate {

    func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
        guard let faceAnchor = anchor as? ARFaceAnchor else { return }
        currentFaceAnchor = faceAnchor
        self.setAsset(strItem:"dummy1.scn" )
    }

    func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
        guard let sceneView = renderer as? ARSCNView,
            anchor is ARFaceAnchor else { return nil }
        let faceGeometry = ARSCNFaceGeometry(device: sceneView.device!)!
        faceGeometry.firstMaterial!.colorBufferWriteMask = []
        occlusionNode = SCNNode(geometry: faceGeometry)
        occlusionNode.renderingOrder = -1
        contentNode = SCNNode()
        return contentNode
    }

}


text:
Q: Discarding part of content that are outside a view boundary I am creating layout dynamically in android, in which i am adding views to relative layout.
Views are having contents.
I am having issue with contents that goes out of views boundary are overlapping with other views.How can i define boundary for my views so any PART OF CONTENT that goes out of views boundary will be discarded.


text:
Q: How to resolve unresolved external symbol when linking against dll with static constructors? I'm building a dll in D with some utils, tools, ect. I can successfully compile a basic dll and test program to use it in visual D without any issues. I am familiar with the process of creating and using dll's. Especially statically linking against them. But if a module in the dll has a static this(), or imports a module with a static this(), the dll will compile, but any program you build that uses it will fail with a foo.bar.__ModuleInfo being unresolved.
error LNK2001: unresolved external symbol "dtoolbox.dtoolboxdllmain.__ModuleInfo" (__D8dtoolbox15dtoolboxdllmain12__ModuleInfoZ)
In this case my dllmain module dtoolbox.dtoolboxdllmain imports core.runtime which has a static this() so i get this error. How do i resolve this? What are static module constructors doing to cause this? As long as there are no static constructors everything works fine.
[edit] Importing core.runtime wasn't the problem, it was the modules own static this(), not core.runtime's static this().

A: The solution is to refrain from importing a module with the dll's static this() && static ~this() into a module of a program which uses the dll. (In this case the dllmain module was being imported, for no reason at all, my mistake) Not to say that the dll can not have them though, they just need to be there in some file when compiling the dll. I found it convenient to write them in the same module as your dllmain as this file will never really need to be referenced/imported by a program using the dll.


text:
Q: Range seek bar crashing Seek bar is crashing when I'm forcing both seek thumbs to merge. There should be at least 6 days interval between seek thumbs and they shouldn't merge at all. I guess I need some kind of Exception handler, can't figure out where and how though. I appreciate any help to solve this issue.
private void moveBar(int left_start, int right_start, boolean direction) {
    if (direction) {
        // check if slider has reached maximum value
        if (realmResults.size() != right_start) {
            // move right
            seekBar.setSelectedMaxValue(right_start + 1);
            seekBar.setSelectedMinValue(left_start + 1);
        }
    } else {
        // check if slider has reached minimum value
        if (left_start != 0) {
            seekBar.setSelectedMaxValue(right_start - 1);
            seekBar.setSelectedMinValue(left_start - 1);
        }
    }
}


text:
Q: MongoDB: mongod shows that my app is not authorized I have installed mongodb and my mongodb and db folders are C:/mongoDB/bin and C:/data/db respectively. I have also setup admin user as stated on
https://docs.mongodb.com/manual/tutorial/enable-authentication/
Now i want to perform basic CRUD operations requiring both read and write on a database mApp through Express and Mongoose. I am providing code for both app and schema below.
Code is well documented so that it is easy to understand.
App.js

var express = require('express');
var app = express();

//Invoking user
var User = require('./schema.js');

//Creating an employee object by giving values to all properties
var User1 = new User({
  name: 'Anurag',
  username: 'Anurag2',
  password: 'abc',
  admin: false,
  location: 'somewhere',
  meta: {
    age: 25,
    website: 'abc.com'
  },
  createdAt: 'Jun 11 2017',
  updatedAt: 'Jun 11 2017'
}); //Remember to provide all records,otherwise document wont be saved.

//CRUD start. Creating a user document
User1.save(function(err, employ, num) {
  if (err) {
    console.log('error occurred');
  }
  console.log('saved ' + num + ' record');
  console.log('Details ' + employ);
});

/* To retrieve documents from database, you can retrieve all at
   once, or one at a time by find(), findById(), findOne() */

//To retrieve all documents
User.find({}, function(err, data) {
  if (err) {
    console.log('error occurred while retrieving all docs');
  }
  console.log(data);
});

User.findOne({
  username: 'Anurag2'
}, function(err, data) {
  if (err) {
    console.log('error in finding one document');
  }
  console.log(data);
});

User.update({
  location: 'someplace'
}, {
  location: 'anything'
}, function(err) {
  if (err) {
    console.log('error in updating');
  }
  console.log('updated');
});

//update one document
User.findOneAndUpdate({
  username: 'Anurag2'
}, {
  admin: true
}, function(err, data) {
  if (err) {
    console.log('error in finding and updating');
  }
  console.log('updated' + data);
});

//Delete a user document
User.remove({
  location: 'anywhere'
}, function(err) {
  if (err) {
    console.log('error occurred');
  }
  console.log('removed');
});

DB Schema(schema.js)

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mApp'); //myApp is the database being connected here.

//now we open a connection
var db = mongoose.connection;
db.once('open', function() {
  console.log('Connected to Database');
});
db.on('error', console.error.bind(console, 'connection error'));

//initialising a schema
var Schema = mongoose.Schema;

mongoose.Promise = require('bluebird'); //used as mpromise was showing deprecated on console.

//creating a schema
var userSchema = new Schema({
  name: String,
  username: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    Required: true
  },
  admin: Boolean,
  location: String,
  meta: {
    age: Number,
    website: String
  },
  createdAt: Date,
  updatedAt: Date
});

//creating a model that uses this schema
var User = mongoose.model('User', userSchema);

//now we export this model
module.exports = User;

Now, I login in mongo through admin and i changed the db to mApp. I run the app through node.
The mongod console shows I am not authorized to perform any actions on the app.
No query gets executed and I get all error messages. Why is this happening? Please help me with this.

A: You have been enable authentication for your database.
So, you have to provide the corresponding credentials in your connection string
Change:
mongoose.connect('mongodb://localhost/mApp');

To
mongoose.connect('mongodb://username:password@host:port/database');

More information on mongoose documentation


text:
Q: WHERE EXISTS not working in SQL Server I need to delete few records which I got from a subquery.
Let's say that the EMP table has columns EMPNAME, EMPSALARY and the primary key is a combination of EMPNAME,EMPSALARY.
DELETE FROM EMP E1
WHERE EXISTS (SELECT E2
              FROM EMP E2
              WHERE E1.EMPNAME = E2.EMPNAME
              AND E1.EMPSALARY = '100'
              AND E2.EMPSALARY = '1000');

The above query works with ORACLE but gives:

Incorrect syntax near E1.

with SQL Server. I need to write a query which is compatible with both.

A: There is one problem in aliasing which you are using. Try this
DELETE E1
FROM EMP E1
WHERE EXISTS (SELECT NULL
              FROM EMP E2
              WHERE E2.EmpName =  E1.EmpName
              AND E1.EMPSALARY = '100'
              AND E2.EMPSALARY = '1000');

In T-Sql aliasing goes like this-
Delete f from dbo.Foo as f where exists(------)

A: The outer and inner queries aren't related in any way, which is usually dangerous and can lead to the entire table being wiped out.
Besides, this syntax will not work in SQL Server, you need to change it slightly:
DELETE e1 --Here is the difference
FROM EMP E1
where E1.EMPNAME = US2.EMPNAME --WTH this alias came from?
AND E1.EMPSALARY = 100
and EXISTS (SELECT E2 FROM EMP E2 WHERE E2.EMPSALARY = 1000);

Not sure whether it will still be viable for Oracle, though.


text:
Q: Ubuntu boot too long (2.5 minutes) I installed Ubuntu 16.04 LTS as my second OS.
When I choose Ubuntu at the boot menu, it takes around 2.5 minutes, whereas Windows 10 boots in around 30 seconds.
Also, when I choose to boot into Ubuntu, GRUB seems like it's glitching up or something because it hangs for 20 seconds or so.
See systemd-analyze screenshots below:

startup.svg


text:
Q: Removing specific users with specific information in their line in bash/unix I'm trying to manipulate csv data to only delete users with specific header attributes by creating a script file and running it, then it will read data from a csv and delete the users with specific information in their line... but when I run this script, it gives errors and shows information such as all the commands to use but when I go through the list of commands it gives, it doesn't work.
mycsv.csv
username,first,last,gender,dob,countries,airports,shells,cuisines,operands,water,nfl
mb8239,maaran,batey,m,april 16 1993,japan,tpa,sh,spanish,multiplication,hint,49ers

INPUT=mycsv.csv
OLDIFS=$IFS
IFS=','
while read username first last gender dob countries airports shells cuisines operands water nfl
do
    if [ $shells == "sh" ]
    then
        userdel -r
    fi
done < $INPUT
IFS=$OLDIFS

From what I understand, if im trying to remove the users using the shell 'sh' then i would do userdel -r no?

A: Finally had a chance to get to my ubuntu machine and sort the awk system() command syntax out.  Try the following awk command:
awk -F',' '(NR>1) {if ($8 ~ /sh/) {out=system("sudo userdel -r " $1 ); print out}}' mycsv.csv

Output:
userdel: user 'mb8239' does not exist
6

The userdel: user 'mb8239' does not exist is the output generated by the attempted deletion of a user that does not exist on the host, so is appropriate output.   The 6 is the exit code of the userdel command that is also expected per the man page for userdel when a user does not exist:
EXIT VALUES
       The userdel command exits with the following values:

       0
           success

       1
           can't update password file

       2
           invalid command syntax

       6
           specified user doesn't exist

       8
           user currently logged in

       10
           can't update group file

       12
           can't remove home directory

If you do not care about the output from the userdel command then you can utilize the following to redirect the output to /dev/null:
awk -F',' '(NR>1) {if ($8 ~ /sh/) {system("sudo userdel -r " $1 " > /dev/null 2>&1")}}' mycsv.csv


text:
Q: Python split string without splitting escaped character Is there a way to split a string without splitting escaped character? For example, I have a string and want to split by ':' and not by '\:'
http\://www.example.url:ftp\://www.example.url

The result should be the following:
['http\://www.example.url' , 'ftp\://www.example.url']

A: The edited version of Henry's answer with Python3 compatibility, tests and fix some issues:
def split_unescape(s, delim, escape='\\', unescape=True):
    """
    >>> split_unescape('foo,bar', ',')
    ['foo', 'bar']
    >>> split_unescape('foo$,bar', ',', '$')
    ['foo,bar']
    >>> split_unescape('foo$$,bar', ',', '$', unescape=True)
    ['foo$', 'bar']
    >>> split_unescape('foo$$,bar', ',', '$', unescape=False)
    ['foo$$', 'bar']
    >>> split_unescape('foo$', ',', '$', unescape=True)
    ['foo$']
    """
    ret = []
    current = []
    itr = iter(s)
    for ch in itr:
        if ch == escape:
            try:
                # skip the next character; it has been escaped!
                if not unescape:
                    current.append(escape)
                current.append(next(itr))
            except StopIteration:
                if unescape:
                    current.append(escape)
        elif ch == delim:
            # split! (add current to the list and reset it)
            ret.append(''.join(current))
            current = []
        else:
            current.append(ch)
    ret.append(''.join(current))
    return ret

A: There is a much easier way using a regex with a negative lookbehind assertion:
re.split(r'(?<!\\):', str)

A: building on @user629923's suggestion, but being much simpler than other answers:
import re
DBL_ESC = "!double escape!"

s = r"Hello:World\:Goodbye\\:Cruel\\\:World"

map(lambda x: x.replace(DBL_ESC, r'\\'), re.split(r'(?<!\\):', s.replace(r'\\', DBL_ESC)))

A: Here is an efficient solution that handles double-escapes correctly, i.e. any subsequent delimiter is not escaped. It ignores an incorrect single-escape as the last character of the string.
It is very efficient because it iterates over the input string exactly once, manipulating indices instead of copying strings around. Instead of constructing a list, it returns a generator.
def split_esc(string, delimiter):
    if len(delimiter) != 1:
        raise ValueError('Invalid delimiter: ' + delimiter)
    ln = len(string)
    i = 0
    j = 0
    while j < ln:
        if string[j] == '\\':
            if j + 1 >= ln:
                yield string[i:j]
                return
            j += 1
        elif string[j] == delimiter:
            yield string[i:j]
            i = j + 1
        j += 1
    yield string[i:j]

To allow for delimiters longer than a single character, simply advance i and j by the length of the delimiter in the "elif" case. This assumes that a single escape character escapes the entire delimiter, rather than a single character.
Tested with Python 3.5.1.

A: As Ignacio says, yes, but not trivially in one go. The issue is that you need lookback to determine if you're at an escaped delimiter or not, and the basic string.split doesn't provide that functionality.
If this isn't inside a tight loop so performance isn't a significant issue, you can do it by first splitting on the escaped delimiters, then performing the split, and then merging. Ugly demo code follows:
# Bear in mind this is not rigorously tested!
def escaped_split(s, delim):
    # split by escaped, then by not-escaped
    escaped_delim = '\\'+delim
    sections = [p.split(delim) for p in s.split(escaped_delim)]
    ret = []
    prev = None
    for parts in sections: # for each list of "real" splits
        if prev is None:
            if len(parts) > 1:
                # Add first item, unless it's also the last in its section
                ret.append(parts[0])
        else:
            # Add the previous last item joined to the first item
            ret.append(escaped_delim.join([prev, parts[0]]))
        for part in parts[1:-1]:
            # Add all the items in the middle
            ret.append(part)
        prev = parts[-1]
    return ret

s = r'http\://www.example.url:ftp\://www.example.url'
print (escaped_split(s, ':'))
# >>> ['http\\://www.example.url', 'ftp\\://www.example.url']

Alternately, it might be easier to follow the logic if you just split the string by hand.
def escaped_split(s, delim):
    ret = []
    current = []
    itr = iter(s)
    for ch in itr:
        if ch == '\\':
            try:
                # skip the next character; it has been escaped!
                current.append('\\')
                current.append(next(itr))
            except StopIteration:
                pass
        elif ch == delim:
            # split! (add current to the list and reset it)
            ret.append(''.join(current))
            current = []
        else:
            current.append(ch)
    ret.append(''.join(current))
    return ret

Note that this second version behaves slightly differently when it encounters double-escapes followed by a delimiter: this function allows escaped escape characters, so that escaped_split(r'a\\:b', ':') returns ['a\\\\', 'b'], because the first \ escapes the second one, leaving the : to be interpreted as a real delimiter. So that's something to watch out for.

A: There is no builtin function for that.
Here's an efficient, general and tested function, which even supports delimiters of any length:
def escape_split(s, delim):
    i, res, buf = 0, [], ''
    while True:
        j, e = s.find(delim, i), 0
        if j < 0:  # end reached
            return res + [buf + s[i:]]  # add remainder
        while j - e and s[j - e - 1] == '\\':
            e += 1  # number of escapes
        d = e // 2  # number of double escapes
        if e != d * 2:  # odd number of escapes
            buf += s[i:j - d - 1] + s[j]  # add the escaped char
            i = j + 1  # and skip it
            continue  # add more to buf
        res.append(buf + s[i:j - d])
        i, buf = j + len(delim), ''  # start after delim

A: I think a simple C like parsing would be much more simple and robust.
def escaped_split(str, ch):
    if len(ch) > 1:
        raise ValueError('Expected split character. Found string!')
    out = []
    part = ''
    escape = False
    for i in range(len(str)):
        if not escape and str[i] == ch:
            out.append(part)
            part = ''
        else:
            part += str[i]
            escape = not escape and str[i] == '\\'
    if len(part):
        out.append(part)
    return out

A: I have created this method, which is inspired by Henry Keiter's answer, but has the following advantages:

*

*Variable escape character and delimiter

*Do not remove the escape character if it is actually not escaping something

This is the code:
def _split_string(self, string: str, delimiter: str, escape: str) -> [str]:
    result = []
    current_element = []
    iterator = iter(string)
    for character in iterator:
        if character == self.release_indicator:
            try:
                next_character = next(iterator)
                if next_character != delimiter and next_character != escape:
                    # Do not copy the escape character if it is inteded to escape either the delimiter or the
                    # escape character itself. Copy the escape character if it is not in use to escape one of these
                    # characters.
                    current_element.append(escape)
                current_element.append(next_character)
            except StopIteration:
                current_element.append(escape)
        elif character == delimiter:
            # split! (add current to the list and reset it)
            result.append(''.join(current_element))
            current_element = []
        else:
            current_element.append(character)
    result.append(''.join(current_element))
    return result

This is test code indicating the behavior:
def test_split_string(self):
    # Verify normal behavior
    self.assertListEqual(['A', 'B'], list(self.sut._split_string('A+B', '+', '?')))

    # Verify that escape character escapes the delimiter
    self.assertListEqual(['A+B'], list(self.sut._split_string('A?+B', '+', '?')))

    # Verify that the escape character escapes the escape character
    self.assertListEqual(['A?', 'B'], list(self.sut._split_string('A??+B', '+', '?')))

    # Verify that the escape character is just copied if it doesn't escape the delimiter or escape character
    self.assertListEqual(['A?+B'], list(self.sut._split_string('A?+B', '\'', '?')))

A: I really know this is an old question, but i needed recently an function like this and not found any that  was compliant with my requirements.
Rules:

*

*Escape char only works when used with escape char or delimiter. Ex. if delimiter is / and escape are \ then (\a\b\c/abc bacame ['\a\b\c', 'abc']

*Multiple escapes chars will be escaped. (\\ became \)

So, for the record and if someone look anything like, here my function proposal:
def str_escape_split(str_to_escape, delimiter=',', escape='\\'):
    """Splits an string using delimiter and escape chars

    Args:
        str_to_escape ([type]): The text to be splitted
        delimiter (str, optional): Delimiter used. Defaults to ','.
        escape (str, optional): The escape char. Defaults to '\'.

    Yields:
        [type]: a list of string to be escaped
    """
    if len(delimiter) > 1 or len(escape) > 1:
        raise ValueError("Either delimiter or escape must be an one char value")
    token = ''
    escaped = False
    for c in str_to_escape:
        if c == escape:
            if escaped:
                token += escape
                escaped = False
            else:
                escaped = True
            continue
        if c == delimiter:
            if not escaped:
                yield token
                token = ''
            else:
                token += c
                escaped = False
        else:
            if escaped:
                token += escape
                escaped = False
            token += c
    yield token

For the sake of sanity, i'm make some tests:
# The structure is:
# 'string_be_split_escaped', [list_with_result_expected]
tests_slash_escape = [
    ('r/casa\\/teste/g', ['r', 'casa/teste', 'g']),
    ('r/\\/teste/g', ['r', '/teste', 'g']),
    ('r/(([0-9])\\s+-\\s+([0-9]))/\\g<2>\\g<3>/g',
     ['r', '(([0-9])\\s+-\\s+([0-9]))', '\\g<2>\\g<3>', 'g']),
    ('r/\\s+/ /g', ['r', '\\s+', ' ', 'g']),
    ('r/\\.$//g', ['r', '\\.$', '', 'g']),
    ('u///g', ['u', '', '', 'g']),
    ('s/(/[/g', ['s', '(', '[', 'g']),
    ('s/)/]/g', ['s', ')', ']', 'g']),
    ('r/(\\.)\\1+/\\1/g', ['r', '(\\.)\\1+', '\\1', 'g']),
    ('r/(?<=\\d) +(?=\\d)/./', ['r', '(?<=\\d) +(?=\\d)', '.', '']),
    ('r/\\\\/\\\\\\/teste/g', ['r', '\\', '\\/teste', 'g'])
]

tests_bar_escape = [
    ('r/||/|||/teste/g', ['r', '|', '|/teste', 'g'])
]

def test(test_array, escape):
    """From input data, test escape functions

    Args:
        test_array ([type]): [description]
        escape ([type]): [description]
    """
    for t in test_array:
        resg = str_escape_split(t[0], '/', escape)
        res = list(resg)
        if res == t[1]:
            print(f"Test {t[0]}: {res} - Pass!")
        else:
            print(f"Test {t[0]}: {t[1]} != {res} - Failed! ")

def test_all():
    test(tests_slash_escape, '\\')
    test(tests_bar_escape, '|')

if __name__ == "__main__":
    test_all()

A: Note that : doesn't appear to be a character that needs escaping.
The simplest way that I can think of to accomplish this is to split on the character, and then add it back in when it is escaped.
Sample code (In much need of some neatening.):
def splitNoEscapes(string, char):
    sections = string.split(char)
    sections = [i + (char if i[-1] == "\\" else "") for i in sections]
    result = ["" for i in sections]
    j = 0
    for s in sections:
        result[j] += s
        j += (1 if s[-1] != char else 0)
    return [i for i in result if i != ""]


text:
Q: Git submodule is ignored When I try to add a submodule via
git submodule add git@domian:repo.git contact

I get the following message:

The following path is ignored by one of your .gitignore files:
contact
Use -f if you really want to add it.

Here is my .gitignore:
# Ignore everything
*

# But not these files:
!*.py
!*.md
!*.gitignore
!.gitmodules
!contact/

It is resolved by using the suggested -f option, but I am curious why the !contact/ entry in .gitignore does not alleviate the problem.

A: A submodule is composed of a gitlink (a special entry 160000 in the Git repository index), and a remote URL+path in the .gitmodules.
So excluding !contact/ would still ignore the gitlink "contact" (which is not a folder contact/, but a special "file")
This would work better, and allow the git submodule add to proceed:
!contact

And if any other cause would still block the git submodule add, the next Git 2.26 (Q1 2020) will provide a more helpful error message.

A: I don't hit that error in your particular case (I have git version 2.21.0.windows.1).
I do hit that error when trying to add a submodule outside the parent repository, though (which apparently isn't supported):
$ git submodule add https://github.com/user/repo ../repo
The following path is ignored by one of your .gitignore files:
../repo
Use -f if you really want to add it.

Best guess is it's a bug...so adding !contact/ to your .gitignore doesn't fix it because it's not actually the .gitignore causing the problem.
What git version do you have? You can download the source code for your particular version, search for the error message (e.g. here it is in v2.21), and trace through the code to figure out what actually goes wrong.


text:
Q: How to change a UI's color when its being hovered over I'm trying to make a UI that changes to a lighter color when its hovered over (roblox's default is darker)
MouseEnter and MouseLeave have already been tested and don't work the way I want it to. MouseEnter keeps the darkening and makes my target color darker than it should be.
Is this possible, if so, how would it be used?

A: MouseEnter and MouseLeave will work, you just need to disable your button's AutoButtonColor property.
From the docs :

The AutoButtonColor determines whether the button automatically changes color when the user's Mouse hovers over or clicks on it.
If true, the button will automatically change color when the mouse hovers over or clicks on it. If false, the button will not change.


text:
Q: Statically stored set of strings I have some string comparison logic in my program, e.g:
std::unordered_set<std::string> relational_operators{
    "==",
    "!=",
    ">",
    "<",
    ">=",
    "<="
};

bool is_relational(std::string token) {
  relational_operators.contains(token);
}

if (is_relational(token)) {
  // ...do stuff
}

All values of set are known at compile time, but checks will be done on user input.
How such strings are usually stored in c++? I don't know if storing a set like this is a good idea, probably not because it can possibly throw an error when allocation happens (IDE warnings).
So for example if i had another set of strings (supported operators):
std::unordered_set<std::string> supported_operators {
  // ...
};

Support for new operators will be added over time. So i just want to add a new operator to a set. So basically i want to avoid situation like this:
bool is_supported_op(std::string token) {
  return token == "<" || token == ">" || token == "!="; // ... many more ||
}

A: Give that you're apparently not planning to modify the set of strings at run-time, I'd probably use an std::array<std::string, N> to hold them, then use std::binary_search to do the search.
From a theoretical viewpoint, you get O(log N) lookups either way--but in reality, the array is likely to give enough better cache locality to improve performance quite a bit (especially if you're using a modern implementation of std::string that implements the short string optimization).


text:
Q: Get OS system and relative path to a folder in java I write my test on my local Windows, and I create webdriver like this:
@BeforeMethod
@Parameters("browser")
public void setUp(String browser) throws Exception {
    if (browser.equalsIgnoreCase("chrome")) {
        System.out.println("Chrome test starting ...");
        System.setProperty("webdriver.chrome.driver", "src/test/resources/drivers/chromedriver_win.exe");
        webDriver = new ChromeDriver();
    }
    else {
        throw new Exception("Browser is not supported");
    }

For the setProperty, I use a hard path to Chrome Driver, but I would like change the path to relative by checking the OS to use appropriate driver for Windows and Mac. Can someone give me a hint. Thanks

A: By using config property file you can get both browser type and chrome driver location.
you can create one folder in your work space with the name Drivers and paste your chrome driver
Below is config.properties file
browserType=Chrome
ChromeDriver = Drivers/chromedriver.exe

Below is the code to run chrome driver on different operating systems
String os = System.getProperty("os.name");
public String currentBrowser;
if(CONFIG.getProperty("browserType").contains(","))
{
  data=currentBrowser;
}
if (os.contains("Windows"))
{
    else if (data.equals("Chrome")) {
    APP_LOGS.debug("Chrome Browser Opening Method Start");
    DesiredCapabilities capability = DesiredCapabilities.chrome();
    // To Accept SSL certificate
    capability.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
    System.setProperty("webdriver.chrome.driver",
            CONFIG.getProperty("ChromeDriver"));
    Thread.sleep(10000);
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

    long
    implicitWaitTime=Long.parseLong(CONFIG.getProperty("implicitwait"));
    driver.manage().timeouts().implicitlyWait(implicitWaitTime,
    TimeUnit.SECONDS);
    driver.manage().window().maximize();
}
    return os;
}

A: Why are you putting chromedriver in src? Your jar will be needing that folders while running.
Source Code and the Binary files should not be put together in production environment.
Create a libs folder and put all types of chromedrivers in it. With slight change in name.
chromedriver_mac
chromedriver_win
chromedriver_linux

Code
@BeforeMethod
@Parameters("browser")
public void setUp(String browser) throws Exception {
    if (browser.equalsIgnoreCase("chrome")) {
        System.out.println("Chrome test starting ...");
        System.setProperty("webdriver.chrome.driver", getChromeDriverPath());
        webDriver = new ChromeDriver();
    }
    else {
        throw new Exception("Browser is not supported");
    }
}
public static String getChromeDriverPath() {
      String OS = System.getProperty("os.name");

        if (OS.contains("Window")) {
            return "libs/chromedriver_win"
        } else if (OS.contains("Mac")) {
            return "libs/chromedriver_mac"
        } else {
            return "libs/chromedriver_linux"
        }
}

A: The below code should work,
if(type.equalsIgnoreCase("CHROME"))
{
  log.info("Executing Operating System = "+System.getProperty("os.name").toLowerCase());
  String osname =System.getProperty("os.name");
  if(osname.toLowerCase().contains("windows")) System.setProperty("webdriver.chrome.driver","src/test/resources/chromedriver.exe" );
  else if(osname.toLowerCase().contains("linux"))
  {
    String filepathtoset = System.getProperty("user.dir")+"/src/test/resources/chromedriver";
    System.setProperty("webdriver.chrome.driver",filepathtoset );
  }
  else System.setProperty("webdriver.chrome.driver","src/test/resources/chromedrivermac");


text:
Q: Multiplication using divide and conquer Basic Approach to multiply 2 numbers  say x , y  $\left(binary\right)$  is   $\Theta \left ( n^{2} \right )$  but  if  we  apply  Divide and conquer approach , we split it as-:
$x=x_{L}*2^{n/2}+x_{R}$
$y=y_{L}*2^{n/2}+y_{R}$
$x_{L}$ and $x_{R}$ contains leftmost and rightmost $n/2$ bits of $x$ respct. and same for $y_{L}$ and $y_{R}$
$x*y=2^{n}*x_{L}*y_{L}+2^{n/2}*\left (\left ( x_{L}*y_{R} \right )+ \left ( x_{R}*y_{L} \right )\right )+x_{R}*y{R}$
From the equation ,it is clear that we require 4 recursive calls to multiply 4 terms.
The recursive equation is given as-:
$f\left ( n \right )=4*f\left ( n/2 \right )+\Theta \left ( n \right )$
what is this $\Theta \left(n\right)$????  isn't it  $\Theta \left(n^{2}\right)$ because it requires  $\Theta \left(n^{2}\right)$  for simple multiplication..please help me out.!!

A: There are no simple multiplications in the RHS $2^{n}*x_{L}*y_{L}+2^{n/2}*\left (\left ( x_{L}*y_{R} \right )+ \left ( x_{R}*y_{L} \right )\right )+x_{R}*y_{R}$.  As you've already noted there are four recursive multiplications: $x_{L}*y_{L}, x_{L}*y_{R}, x_{R}*y_{L}, x_{R}*y_{R}$.  The only remaining multiplications are by powers of $2$, which just requires shifting an array of digits by a fixed offset: this only takes $\Theta(n)$ operations provided the array length is $\Theta(n)$ and the offset is $O(n)$.  Besides multiplications, the only thing left are additions, which are again $\Theta(n)$.
Of course, solving this recurrence still gives $\Theta(n^2)$.  The key to Karatsuba's algorithm for doing this more efficiently is a trick that lets you compute all four recursive multiplications using only three distinct multiplications.


text:
Q: apache2 is not running but it listens at port 80 I made an image of one of my private Amazon EC2 image that runs one website, then started installing redmine. After all the installation is done, it is about to restart Apache I encountered the following issue(sorry you might have to zoom in to see the screenshot):

My understanding of what was happening is that apache2 is not running but it is listening to port 80. Then I tried:

which gives the same confusing but consistent conclusion, apache2 is not running, but I am sure it is process 18304 which is apache2 listening to port 80.
Eventually, I had to kill the process and restart apache which worked.
Could someone explain to me what might have caused this and a fix?
Update1:
Following synthesizerpatel suggestion to use lsof.

This is exactly the same problem with different process as before.

A: Sometimes when you stop apache (or any other program) the script can't properly shut down the program because it waits for something (for example IO) but deletes the pid file. So the script beleives that apache is not running because there is no pid file but apache is runs, or sometimes not really rund but stuck in and sits on the port.
In these cases you have to kill the process and you can start the program. I have seen many this kind of stuck processes from apache, slapd, cirus, ... sometimes it happens.

A: Try running
lsof -n | grep TCP

Also.. the apache2 controller isn't always the most reliable, it just checks for a PID file, not the actual process.
ps -aef | grep httpd

$1 says you've still got an httpd running.

A: As the poster says above, use
lsof -n | grep TCP

or
lsof -n | grep "*:www"

Also, in Ubuntu, it uses the process name "apache2" so you should be checking for it with
ps -ax |grep apache

Instead of grep httpd

A: Run
ps aux|grep apache

Do you see
/usr/share/apache2/ask-for-passphrase localhost:443 RSA

If so
One of the sites containes an SSL certificate with a passphrase. So when apache was trying to start at boot time it could not continue without someone manually entering the passphrase.
So you have two options to fix this problem:

*

*Add a SSLPassPhraseDialog directive to your config.

*Remove your passphrase (Less secure)


text:
Q: Does the Hölder coefficient tend to zero? A continuous fucntion $f: \Omega\rightarrow \mathbb{C}$, with $\Omega$ subset of $\mathbb{R}^n$ or $\mathbb{C}^n$, is a $\alpha$-Hölder continuous with $0< \alpha\leq 1$, if
\begin{equation}
[f]_{\alpha}:=\sup_{x,y\in \Omega, x\ne y} \frac{|f(x)-f(y)|}{|x-y|^{\alpha}}<\infty.
\end{equation}
Here is my problem. If $\{f_n\}$ is a sequence of $\alpha$-Hölder continuous function on a compact subset $\Omega$,and $f_n$ converges uniformly to $f$ on $\Omega$, that is, $\lim_n\|f_n-f\|_{\infty}=0$. If $f$ is also $\alpha$-Hölder continuous, is it true that $\lim_n[f_n-f]_{\alpha}=0$?
Here is my analysis. According to the definition, we have
\begin{align*}
[f_n-f]_{\alpha}&=\sup_{x,y\in \Omega, x\ne y}\frac{|f_n(x)-f(x)-f_n(y)+f(y)|}{|x-y|^{\alpha}}\\
&=\sup_{x,y\in \Omega, x\ne y}\frac{|f_n(x)-f(x)|+|f_n(y)-f(y)|}{|x-y|^{\alpha}}\\
&\leq \sup_{x,y\in \Omega, x\ne y}\frac{2\|f_n-f\|_{\infty}}{|x-y|^{\alpha}}\rightarrow 0.
\end{align*}
It seems to me that the analysis is okay, but I need a double check in case there is some missing points.


text:
Q: Owner can't push to organization repository today I've moved my private github repository to newly created organization (of which I'm an owner). I've changed my remote origin to git@github.com:organization/repo.git. I'm not able to push to remote because I've got an error saying

Error: Permission to organization/repo.git denied to MyGithubUsername.
fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.

I've checked that my account is owner of organization and repository exists.

A: Disable third-party application access restrictions as suggested in atom/github #1010.422882361.

A: I ran into this problem today and indeed as Ephellon Dantzler suggests, disabling 3rd-party access restrictions fixed it.
However, I did not really like that solution so I started reading the documentation. On the About OAuth App access reistrictions page, Github mentions that enabling 3rd party restrictions will block:

SSH keys created before February 2014 immediately lose access to the organization's resources (this includes user and deploy keys).

I created my key well before that so I just created a new SSH key and added to Github following their instructions.
After that, I was able to interface with my organization's private repository even when 3rd-party access restrictions was enabled.

A: I managed to find an answer. Maybe I did something wrong, or maybe it was because of github issues, but even if I was stated as an owner of Organization I had only rights to read repository. I couldn't change permission for myself because "you can't change permission for owner". I changed permissions for all members to admin, and because for now I'm the only one member of organization it's not a big deal.

A: The solution I found to this problem was creating a P.A.T (Personal Access Token) and using it in the spot of my password when pushing to the repo.
The way you can create a P.A.T is by going to:
Github.com >Login> Settings> Developer Settings> Personal Access Tokens > Generate New Token. I selected all the options for my token and then copied the token that was generated and used it as my password when I was asked to enter my credentials.
This took me a few hours to figure out and was very frustrating. I hope this info can help someone else!

A: Using GitHub Desktop..I was having a weird bug where I was owner of the organization, and admin of the repo(I had full rights) on my organization's repo. I decided to go into the command line, and push from there (Type "git push") and that fixed it!
It pushed, and I could now push from GitHub Desktop again.
Weird, but hope it helps someone!

A: For me, everything was ok in the Settings and with my key. Yet Github Desktop could not push (or even fetch) to/from the remote because it didn't trust the IP address. To find and fix I switched to the CLI and ran:
git fetch

which replied with
The authenticity of host 'github.com (140.82.114.4)' can't be established.
RSA key fingerprint is SHA256:<long string>.
Are you sure you want to continue connecting (yes/no)?

therefore revealing the issue. Either Github has changed their IP or I hadn't connected to this repo on my new machine (with the old key). Replying yes added the IP to my .ssh/known_hosts and then Github Desktop worked just fine again.
Warning: Permanently added 'github.com,140.82.114.4' (RSA) to the list of known hosts.

A: So I ran into this issue recently with an SSH key generated in 2018 and Ephellon Grey's answer pointed me in the right direction. My personal SSH key was added to GitHub by SourceTree and SourceTree was not an authorized third-party app on my organization page. Hence pushes authorized with that SSH key were being rejected. I just had to grant third-party access to SourceTree on the organization and now I can push to repos contained within.


text:
Q: How to restart StreamReader to start reading from the beginning of a file So i have to write a program that reads values (numbers) from Values.txt file and store them into array of integers (at the beginning i dont know the number of values in file so i dont know the length of array).
First i loop through the file and use counter variable to get the number of values to store into array. Then comes the problem, i dont know how to start from the beginning of file to catch values and store them into array.
When i run it i get 0 0 0 0 0 as a result.
If instead of
myReader.DiscardBufferedData();
myReader.BaseStream.Seek(0, SeekOrigin.Begin);
myReader.BaseStream.Position = 0;

I use the myReader.Close() and then myReader = new StreamReader("Values.txt), the result is correct, can somebody please explain why this is happening and howcan i fix this code :)
        string lineOfText = "";
        int counter = 0;
        int[] intArray;
        StreamReader myReader = new StreamReader("Values.txt");

        while(lineOfText != null)
        {
            lineOfText = myReader.ReadLine();
            if(lineOfText != null)
            {
                counter++;
            }
        }
        intArray = new int[counter];

        myReader.DiscardBufferedData();
        myReader.BaseStream.Seek(0, SeekOrigin.Begin);
        myReader.BaseStream.Position = 0;

        counter = 0;
        while(lineOfText != null)
        {
            lineOfText = myReader.ReadLine();
            if (lineOfText != null)
            {
                intArray[counter] = int.Parse(lineOfText);
            }
            counter++;
        }
        myReader.Close();

        for (int j = 0; j < intArray.Length; j++)
        {
            Console.WriteLine(intArray[j]);
        }

A: This explains how to reset the stream if you want to do it in one pass Return StreamReader to Beginning.
Are you required to use an array? A list would be perfect for what your doing, you can then later push that list into an array or just work directly from the list. Code example below:
List<string> ints = new List<string>();
using (StreamReader sr = new StreamReader("example.txt"))
{
    ints.Add(sr.ReadLine());
}


text:
Q: How do we authenticate users in mobile apps for Android and iPhone? We are developing a mobile app in Android and iPhone which has a server-side coding in PHP (YII). I want to perform session management on the device for authenticating users in a similar way a website (web browser) could manage. Is there any way I could do session management on the device? Please help.

A: Not sure about iphone, but android offers persisten storage in preferences - you can store there some access token and authenticate them against  your service.   Then on every request this token shall be passed together with request dat and your service can evaluate this token
to authentificate and authorise request.
But basically it is not a good idea to store sensitive security information  on device - there are nice frameworks like OAuth  which will allow you to  give access to service without
storing sensitive security credentials on device and also provide ways to revoke access to particular devices in case they are compromissed.

A: Sessions are stored in Server Buffer unlike Cookies.
You should be fine as you do it the same way you would do for any website.
Did you try doing this before asking?

A: Take a look at Authenticating Users in Mobile Apps. You can either use a web browser (through WebViews) on the mobile device, or issue an authentication token to the app.


text:
Q: Tables not created using Envers, without errors in compilation I try create the tables with following code:
    protected override void PostProcessMappings(Configuration config)
    {
        base.PostProcessMappings(config);
        var enversConf = new NHibernate.Envers.Configuration.Fluent.FluentConfiguration();

        config.Properties.Add("nhibernate.envers.audit_table_prefix", string.Empty); // default
        config.Properties.Add("nhibernate.envers.audit_table_suffix", "_REV"); // default _AUD
        config.Properties.Add("nhibernate.envers.revision_field_name", "REV"); // default
        config.Properties.Add("nhibernate.envers.revision_type_field_name", "REVTYPE"); // default

        config.IntegrateWithEnvers(enversConf);

        new SchemaExport(config).Create(false, true);
     }

But in the schema, i cant see the tables.
I try to implement the code using here (Test). Next, i debug and the nhibernate object: Cfg.NHibernate.Configuration config and in my project i cant catch the mappings, and in the test, i see the mapping that will be created.
I dont know what next i need to do.


text:
Q: Quick sort on an array I have an array A = |0.535|0.960|0.750|0.750|0.151|0.001|0.981|0.327|0.111|
I took the pivot as 0.535
I swapped A[1] = 0.960 with A[8] = 0.111 to get
A = |0.535|0.111|0.750|0.750|0.151|0.001|0.981|0.327|0.960|
Then I swapped A[2] = 0.750 with A[7] = 0.327 to get
A = |0.535|0.111|0.327|0.750|0.151|0.001|0.981|0.750|0.960|
Now I'm confused as to what to do next (0.75 is compared with 0.75) as the values 0.151 is less than pivot and 0.981 is greater than pivot. Can someone please guide me?

A: I have no idea what you are exactly looking for. However, if you want to know how quick sort works, let's go through your array. It should be mentioned that we are going to get the first most left element as pivot.

    function qsort(x, lo, hi) {
      var i, p;
      if (lo >= hi) {
          return;
      }
      p = lo;
      for (i = lo + 1; i <= hi; i++) {
        if (x[i] < x[lo]) {
            swap(x, ++p, i);

         }
      }
    swap(x, lo, p);
    qsort(x, lo, p - 1);
    qsort(x, p + 1, hi);
    }

As you said you get 0.535 as pivot in the first step it will go through your elements from the second element(from pivot) and if it was smaller than chosen pivot, it will change that element's position with second element, if it found second element smaller it will change it with the third element's position and so on. At the end, it will change the pivot's position with position=total elements it has been larger than. So after choosing 0.535 the array would be like:
[ 0.111, 0.151, 0.001, 0.327, 0.535, 0.75, 0.981, 0.75, 0.96].
And after that pivot would be 0.111 and then array will be like:
[ 0.001, 0.111, 0.151, 0.327, 0.535, 0.75, 0.981, 0.75, 0.96 ].
again pivot = 0.151 and array:
[ 0.001, 0.111, 0.151, 0.327, 0.535, 0.75, 0.981, 0.75, 0.96 ]
again pivot = 0.75 and array:
[ 0.001, 0.111, 0.151, 0.327, 0.535, 0.75, 0.981, 0.75, 0.96 ]
again pivot = 0.981 and array:
[ 0.001, 0.111, 0.151, 0.327, 0.535, 0.75, 0.96, 0.75, 0.981 ]
again pivot = 0.96 and array:
[ 0.001, 0.111, 0.151, 0.327, 0.535, 0.75, 0.75, 0.96, 0.981 ]


text:
Q: access to control from diffrent page page1.aspx
<input type="text" runat=server id="text1"/>

page2.apx
protected void btnCreateMember_Click(object sender, EventArgs e)
{
    text1.text="test";
}

How can I change Input on Page1.aspx through Page2.aspx Method btnCreateMember_Click

A: I think that you are missing some very basic concepts about ASP.NET MVC here. In ASP.NET MVC there is no such thing as runat="server", nor any callbacks. There is no ViewState nor PostBacks. Even if it is based on ASP.NET, ASP.NET MVC is a fundamentally different framework. In ASP.NET MVC you have Models, Controllers and Views. So if you want to send values from one view to another controller action you could use a form with HTML helpers:
<% using (Html.BeginForm("someAction", "someController")) { %>
    <%= Html.TextBoxFor(x => x.SomeProperty) %>
    <input type="submit" value="OK" />
<% } %>

I would recommend you going through the tutorials here: http://asp.net/mvc to familiarize yourself with the basic notions of MVC.

A: I see the MVC tags have been removed.
This isn't how webforms work.
If the user is on Page 2 and clicks the "Create Member" button, then you should perform the logic to "create a member" there and redirect as necessary.
If you redirect from Page2 to Page1.aspx, then the page_load event of Page1.aspx should load whatever data it needs and populate any necessary page controls itself.
In other words, each page should be encapsulated to pull, display, and update the data it needs.


text:
Q: Script wont show hidden element when 'hidden' class is removed I have the following function:
function submitForCorrection() {
    try {
        $("#uploadSpinner").removeClass("hidden");
        setTimeout(function() {}, 100);
        SubmitForm('BoqReviewForm',
            'boqReviewTable',
            '@Url.Action("PostBoqFlags", "ProjectAuthority")',
            '@Url.Action("GetBoqReview", "ProjectAuthority")',
            function() { showNotification('Correction requested.', 'success'); },
            null,
            'Requesting correction. Please wait',
            false);
    } finally {
        $("#uploadSpinner").addClass("hidden");
    }
}

The SubmitForm call is rather timeous, hence me wanting to show a 'spinner' while it executes. Yet it's as if my
$("#uploadSpinner").removeClass("hidden");

line of code is totally ignored.
I know the spinner is in the correct place, because if I put a breakpoint on the removeClass line and manually remove the hidden class in Chrome dev tools, the spinner shows up exactly where I want it.
I've added the setTimeout(function() {}, 100); in the vain hope that removing the hidden class may take some time, and I wanted to avoid the SubmitForm call executing before the spinner is visible.
Why is my code behaving as if the removeClass isn't even there?

A: It may appear that the class isn't removed but in reality you are removing the class then adding it back to the element instantly.
In your try catch you have
} finally {
  $("#uploadSpinner").addClass("hidden");
}

and finally will always run right after your try block has finished.
As stated on MDN:

finally_statements:
Statements that are executed after the try statement completes. These statements execute regardless of whether an exception was thrown or caught.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
So your code is running the try block which will remove the class but then it is just adding it back instantly in your finally block. This is happening because setTimeout and I assume your SubmitForm function are both asynchronous.
You will need to return a callback or a Promise from your SubmitForm function so you can then remove the loader after the form has finished submitting.
You should be able to fix this by changing your function to this
function submitForCorrection() {
  $("#uploadSpinner").removeClass("hidden");
  setTimeout(function() {
    SubmitForm('BoqReviewForm',
      'boqReviewTable',
      '@Url.Action("PostBoqFlags", "ProjectAuthority")',
      '@Url.Action("GetBoqReview", "ProjectAuthority")',
      function() {
        showNotification('Correction requested.', 'success');
        $("#uploadSpinner").addClass("hidden");
      },
      null,
      'Requesting correction. Please wait',
      false
    );
  }, 100);
}

A: instead of removing the class, perhaps you should try to change the "display" attribute of the spinner from "none" to "block"
2 ways of doing it is as follow:
$("#uploadSpinner").css("display", "block");
or
$('#uploadSpinner').show();


text:
Q: Why does Antlr think there is a missing bracket? I've created a grammar to parse simple ldap query syntax. The grammer is:
expression   :   LEFT_PAREN! ('&' | '||' | '!')^ (atom | expression)* RIGHT_PAREN! EOF ;

atom    :   LEFT_PAREN! left '='^ right RIGHT_PAREN! ;

left    :   ITEM;
right   :   ITEM;

ITEM        :   ALPHANUMERIC+;
LEFT_PAREN  :   '(';
RIGHT_PAREN :   ')';

fragment ALPHANUMERIC
    :   ('a'..'z' | 'A'..'Z' | '0'..'9');

WHITESPACE : (' ' | '\t' | '\r' | '\n') { skip(); };

Now this grammar works fine for:
(!(attr=hello2))
(&(attr=hello2)(attr2=12))
(||(attr=hello2)(attr2=12))

However, when I try and run:
(||(attr=hello2)(!(attr2=12)))

It fails with: line 1:29 extraneous input ')' expecting EOF
If I remove the EOF off the expression grammar, everything passes, but then wrong numbers of brackets are not caught as being a syntax error. (This is being parsed into a tree, hence the ^ and ! after tokens) What have I missed?

A: As already mentioned by others, your expression has to end with a EOF, but a nested expression cannot end with an EOF, of course.
Remove the EOF from expression, and create a proper "entry point" for your parser that ends with the EOF.
file: T.g
grammar T;

options {
  output=AST;
}

parse
  :  expression EOF!
  ;

expression
  :  '('! ('&' | '||' | '!')^ (atom | expression)* ')'!
  ;

atom
  :  '('! ITEM '='^ ITEM ')'!
  ;

ITEM
  :  ALPHANUMERIC+
  ;

fragment ALPHANUMERIC
  :  ('a'..'z' | 'A'..'Z' | '0'..'9')
  ;

WHITESPACE
  :  (' ' | '\t' | '\r' | '\n') { skip(); }
  ;

file: Main.java
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import org.antlr.stringtemplate.*;

public class Main {
  public static void main(String[] args) throws Exception {
    String source = "(||(attr=hello2)(!(attr2=12)))";
    TLexer lexer = new TLexer(new ANTLRStringStream(source));
    TParser parser = new TParser(new CommonTokenStream(lexer));
    CommonTree tree = (CommonTree)parser.parse().getTree();
    DOTTreeGenerator gen = new DOTTreeGenerator();
    StringTemplate st = gen.toDOT(tree);
    System.out.println(st);
  }
}

To run the demo, do:
*nix/MacOS:
java -cp antlr-3.3.jar org.antlr.Tool T.g
javac -cp antlr-3.3.jar *.java
java -cp .:antlr-3.3.jar Main
Windows:
java -cp antlr-3.3.jar org.antlr.Tool T.g
javac -cp antlr-3.3.jar *.java
java -cp .;antlr-3.3.jar Main
which produces the DOT code representing the following AST:

image created using graphviz-dev.appspot.com

A: In your definition of expression, there can be parentheses containing a nested expression, but the nested expression has to end in EOF.  In your sample input, the nested expression doesn't end in EOF.


text:
Q: Как сделать, чтобы через определённое время ожидания input() компьютер высылал ещё одно письмо? У меня есть игра с личными кабинетами, и мне бы хотелось, чтобы, когда пользователь при регистрации не вводит код из письма 1 минуту, ему отсылалось 2-е письмо.
P. S. письма знаю как отправлять

A: Вот тут есть вся нужная Вам информация. На этой веб-странице есть даже несколько вариантов решения Вашей задачи.


text:
Q: Lock a set of DB operations in Java I have a requirement in my Java application to execute a set of DB statements in an atomic & isolated fashion. For example, the application needs to read data rows from one table and update a data row in another table.
QueryRunner queryRunner = new QueryRunner(); // DBUtils query runner

Object[] params = new Object[] { param };

Connection conn = null;
try {
    conn = ...; // get connection
    conn.setAutoCommit(false);
    result = queryRunner.query(conn, "select x, y, z from table1 where column1 = ?", new BeanHandler<SomeBean>(SomeBean.class), params);

    // logic to get value for update

    queryRunner.update(conn, "update table2 set p = ? where q = ?", some_value, some_id);
    conn.commit();
} catch (SQLException e) {
    //
} finally {
    DBUtils.closeQuietly(conn);
}

The transaction management is achieved by setting auto commit to false for the connection and explicitly commit later on, as shown above. But the above code can also be executed in a multi-thread environment and I also want the two DB statements (select & update) to be run as a whole mutual exclusively.
I have some idea to use a shared Java Lock object in that method, depicted below.
In the class,
private Lock lock = new ReentrantLock(); // member variable

In the method,
lock.lock();
try {
    conn = ...; // get connection
    conn.setAutoCommit(false);

    result = queryRunner.query(conn, "select x, y, z from table1 where column1 = ?", new BeanHandler<SomeBean>(SomeBean.class), params);

    // logic to get value for update

    queryRunner.update(conn, "update table2 set p = ? where q = ?", some_value, some_id);
    conn.commit();
} finally {
    DBUtils.closeQuietly(conn);
    lock.unlock();
}

It seems sort of capable of solving the issue. However, I am wondering if this is the best practice and is there any better alternative (such as frameworks) for this?

A: My suggestion is to have the database manage those locks for you instead of your application. This handles the case where there are multiple JVM's running the code. The locking mechanims you mentioned can only be effective in a single JVM.
The way to accomplish this is to do a SELECT ... FOR UPDATE. This will place a lock on the selected rows and the lock will be released when your transaction is committed or rolled back. This is better than a table level lock because those rows can still be read by other transactions that just want to read the current value but not update them. If another transaction tries to obtain a FOR UPDATE lock, then it will block until the first one finishes.

A: The only way you will achieve the atomicy you are requiring is to use a stored procedure in the database to isolate the data and lock it all at once. The locking at the Java level can't do what the locking in the database can as easily.

A: Another way you can handle problems like this is to use the serializable transaction isolation level for all of your database transactions.  This causes any set of transactions to behave as though they were run one at a time, without actually making them run one at a time.  If you do this you should be using a framework which catches serialization failures (SQLState 40001) and retries the transactions.  The big up-side is that you don't need to worry about particular interactions among transactions -- if a transaction does the right thing when it is the only thing running, it will do the right thing in any transaction mix.
Note that all transactions must be serializable for this to work so simply.

A: From my understanding, do you just want to make that block of code containing select and update statements as Thread safe? That's what synchronized keyword is used for. Even though this question is asked long back i just want to make a note of it here. put those lines of code under synchronized block.


text:
Q: Best practice for restlet json error and validation message framework We have a restlet API, which returns error messages in JSON.  We are passing setStatus(Status.CLIENT_ERROR_BAD_REQUEST); before generating a JSON response, and if the operation is successful, we are passing back 200 OK.
My question is: Are there any validation and error message creation frameworks in restlet?  More importantly, what are some best practices for passing error message to UI which they can interpret easily?
Example error message :
Status Code: 400 Bad Request
{
   "ErrorMessage": "Unable to **: Failed to get **:Failed to connect to *"
}

A: I think the answer is no.
You can follow the twitter way
https://dev.twitter.com/docs/error-codes-responses
Personally I suggest to omit the error code id.
The message it self is part of the API contract.
It should be short, clear and in valid English.
{"error|message":"User not found"}
The client should translate "User not found".

A: You might want to have a look on the Validator class: http://restlet.com/technical-resources/restlet-framework/javadocs/snapshot/jse/api/org/restlet/routing/Validator.html

A: I guess I'm looking for this one or similar framework
http://hibernate.org/validator/


text:
Q: Update one table's row from the results of multiple rows of another table I've seen posts on how to update multiple rows (specifically using case?), but my question is the inverse.
I have a table of phone_numbers

Person_ID
Phone_number

1
102-345-6789

1
102-445-6789

2
102-545-6789

And a table of contacts:

peopleid
Phone_number_1
Phone_number_2
Name

1

Joe

2

Bob

I'd like to get the phone_numbers into the one row of the contacts table.
And all I have is a hot mess of attempts, none of which have worked, mostly because I'm doing joins? that are not explicit? so the multi-part identifiers don't work.
I wanted to make sure I was getting each row (and not just the first row of what the join decides), so I did this:
DECLARE @id int
SELECT @id = min(e1.Person_ID)
FROM out_1E e1
WHILE @id IS NOT NULL
BEGIN
  -- other stuff below

  select @id = min( Person_ID )
  from out_1E
  where Person_ID > @id
END

And then my attempt at the update statement inside, where I want it to update the first column if null, and if not, the second column (I only care about the first two).
DECLARE @phone NVARCHAR
  SELECT @phone = contacts.Phone_number_1 -- THIS DOESN'T WORK
  IF @phone IS NULL

UPDATE contacts
SET [Phone_number_1] = isnull([Phone_number_1], e1.Phone_number)
FROM out_1E e1
WHERE contacts.peopleid = e1.Person_ID

In total:
DECLARE @id int
SELECT @id = min(e1.Person_ID)
FROM out_1E e1
WHILE @id IS NOT NULL
BEGIN
  DECLARE @phone NVARCHAR
  SELECT @phone = contacts.Phone_number_1
  IF @phone IS NULL

   UPDATE contacts
SET [Phone_number_1] = isnull( [Phone_number_1], e1.Phone_Number)
FROM out_1E e1
WHERE contacts.peopleid = e1.Person_ID

  select @id = min( Person_ID )
  from out_1E
  where Person_ID > @id
END

These are not the column names, so if there are typos there, it's only on this post.
How would I go about correcting this so I iterate through each row of the phone_numbers table to populate the contacts table with phone numbers?

A: I don't think this is an elegant solution, but I just split it up and added a WHERE clause on the second iteration.
UPDATE contacts
SET [Home Phone] = ISNULL([Home Phone], e1.Phone_Number)
FROM out_1E e1
WHERE contacts.peopleid = e1.Person_ID
AND [Person_Phone_or_email_Type] = 'HOME'

UPDATE contacts
SET [Home Phone 2] = ISNULL([Home Phone 2], e1.Phone_Number)
FROM contacts
INNER JOIN out_1E e1
ON contacts.peopleid = e1.Person_ID
WHERE [Home Phone] <> e1.Phone_Number
AND Person_Phone_or_email_Type = 'HOME'

I'm sure there's a better way of doing this, to be more inclusive, but this does appear to work.


text:
Q: Path expansion for volume overlays uses root with Rancher Desktop (OSX) We're trying to use rancher desktop and nerdctl to bring up some compose stacks. The issue we've run into is that when you have a mount similar to the following, nerdctl expands either ${HOME} or ~/ to /root, despite me running the command as my normal user.
        volumes:
            - ${HOME}/.config/conf:/opt/confpath

FATA[0000] failed to create shim: OCI runtime create failed: container_linux.go:380: starting container process caused: process_linux.go:545: container init caused: rootfs_linux.go:76: mounting "/root/.config/conf" to rootfs at "/opt/confpath" caused: stat /root/.config/conf: no such file or directory: unknown
FATA[0000] error while creating container u42-docs: exit status 1

Is there a way to prevent this path expansion to the root user, and instead be my own user?
Rancher desktop was installed via brew install --cask rancher


text:
Q: Logging Operations I've made a program in c# that solves Engineering Economy problems, such as finding the present value of an investment, or the future / payment, number of periods, rate of interest, B/C analysis, Present Worth Analysis, Bonds, etc.
The issue I have right now is that I want to save the operations I've made in a Microsoft Word file, and have the formulas nicely formatted with Microsoft Word's Equation Editor.
Right now I'm just saving the information to a text file with methods like this one.
public async void LogFV(decimal i, decimal n, decimal p, decimal pmt, decimal res)
{
    using (var writer = new StreamWriter(FileName, true))
    {
        var sb = new StringBuilder();
        sb.AppendLine("Given Data: ");
        sb.AppendLine(String.Format("i = {0:P}", i));
        sb.AppendLine(String.Format("n = {0}", n));
        sb.AppendLine(String.Format("A = {0:C}", pmt));
        sb.AppendLine(String.Format("P = {0:C}", p));
        sb.AppendLine("Resolution: ");
        sb.AppendLine(String.Format("F = {0} * (F/P, {1:P}, {2}) + {3} * (F/A, {1:P}, {2})", p, i, n, pmt));
        sb.AppendLine(String.Format("F = {0:C}", res));

        await writer.WriteLineAsync(sb.ToString());
    }
}

I don't want to re-invent the wheel, this isn't homework. Right now I thought of using the Online LaTeX equation editor but I prefer Microsoft Word's editor.
A design pattern question that I also want to ask is, how should I implement the Logger? I don't want to have it mixed in with the implementation for the Formulas, so I thought about creating a Logger class that delegates to the specific formula (e.g FV, PV, etc) and performs the logging tasks with the parameters. But I think there must be a better way of doing this.


text:
Q: Report groups correctly but shows wrong header I am writing an SSRS report that will group on data depending on if the user passes a customer number or a project number. The report groups the values correctly, but the grouping header shows the opposite of what it's grouping on.
For the example below I have called the report passing in a custnumstart value. It is grouping on customer number but the column that is showing the grouping is the project number.
=IIf(IsNothing(Parameters!CustNumStart.Value)
AND (Parameters!ShowDetails.Value = 0), Fields!Proj_Num.Value,
 IIF((IsNothing(Parameters!ProjectStart.Value)
  AND Parameters!ShowDetails.Value = 0), Fields!Cust_Num.Value, ""))

A: The issue was resolved by correcting the text box value (Text box properties -> Value) to be:
=IIf(IsNothing(Parameters!CustNumStart.Value) AND Parameters!ShowDetails.Value = 0, Fields!Proj_Num.Value, Fields!Cust_Num.Value))

not changing the way the report was grouping


text:
Q: SQL Server date format handling I am running the SAME Delphi 2007 code on two different Windows 7 machines and accessing the SAME SQL server database on a remote server. On one machine a date in the database is read in the format 2013-01-25 00:00:00.000 which causes the application to crash when it tries to convert this date to a DateTime. On the other machine a date is read in the format 1/25/2013 which is correctly converted to a DateTime without any issues.  What is causing this difference?  (I verified that the Control Panel 'Region and Language' settings on the two machines are identical). The dates in the database are stored as datetime2.

A:
On one machine a date in the database is read in the format 2013-01-25 00:00:00.000 which causes the application to crash when it tries to convert this date to a DateTime. On the other machine a date is read in the format 1/25/2013 which is correctly converted to a DateTime without any issues

I don't know anything about Delphi but on the SQL Server side:
Date is a Date and does not have a format. If your column is of Date datatype, you shouldn't get any errors when converting to DateTime.
I suspect you may be storing date in a string type field in which case it would be best to use culture in-specific ISO or ISO8601 format before converting to DateTime.