text:
Q: Coffee machine simulator - removing an empty line i finished this coffee machine simulator but i have a small problem.
How can i remove the line added by the check function after i enter the 'e' or 'l' or 'c'?
Below is the code and a sample of the undesired output and the desired input.
The code:
import os
import time
menu = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee_l": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

resources = {
    "water": 300,
    "milk": 200,
    "coffee": 100,
    "money":0
}

def money():
    quarter=0.25
    dime=0.1
    nickel=0.05
    pennie=0.01
    qu=float(input("Inset quarters: "))
    di=float(input("Insert dimes: "))
    ni=float(input("Insert nickels: "))
    pen=float(input("Insert pennies: "))
    total_paid=qu*quarter+di*dime+ni*nickel+pen*pennie
    return total_paid

def check(drink):
    if drink == 'espresso':
        if resources['water'] >= 50 and resources['coffee'] >= 18:
            return ''
        elif resources['water'] <= 50:
            return "Sorry there is not enough water."
        elif resources['coffee'] <= 18:
            return "Sorry there is not enough coffee."
    elif drink=='latte':
        if resources['water'] >= 200 and resources['milk'] >= 150 and resources['coffee'] >= 24:
            return ""
        elif resources['water'] < 50:
            return "Sorry there is not enough water."
        elif resources['coffee'] < 18:
            return "Sorry there is not enough coffee."
        elif resources['milk'] < 150:
            return "Sorry there is not enough milk."

    elif drink=='cappuccino':
        if resources['water'] >= 250 and resources['milk'] >= 100 and resources['coffee'] >= 24:
            return ""
        elif resources['water'] < 250:
            return "Sorry there is not enough water."
        elif resources['coffee'] < 24:
            return "Sorry there is not enough coffee."
        elif resources['milk'] < 100:
            return "Sorry there is not enough milk."

def make_drink(drink):
    if drink == "espresso":
        resources['water']  -= 50
        resources['coffee'] -= 18
        resources['money'] += 1.5
    elif drink == "latte":
        resources['water']  -= 50
        resources['coffee'] -= 18
        resources['milk']   -= 150
        resources['money'] += 2.5
    elif drink == "cappuccino":
        resources['water']  -= 250
        resources['coffee'] -= 18
        resources['milk']   -= 100
        resources['money'] += 3
    else:
        print("Not sure what drink was made")
    return

def replenish():
    resources['water']  += 300
    resources['milk']   += 200
    resources['coffee'] += 100
    return

while True:
    print("Welcome to the coffee machine.")
    m="Espresso = 1.5$\nLatte = 2.5$\nCappuccino = 3.0$\n"
    print(m)
    choice=input("What would you like? (espresso/latte/cappuccino)(e/l/c): ")
    if choice=='report':
        print(f"Water: {resources['water']}ml\nMilk: {resources['milk']}ml\nCoffee: {resources['coffee']}ml\nMoney: {round(resources['money'],2)}$")
    elif choice=='replenish':
        replenish()
    elif choice=='e':
        chk=check('espresso')
        print(chk)
        if chk=='':
            mo=money()
            if mo == menu['espresso']['cost']:
                make_drink('espresso')
                print('Here is your coffee')
            elif mo > menu['espresso']['cost']:
                make_drink('espresso')
                print(f'Here is your coffee, and here is your change {round(mo-menu["espresso"]["cost"], 2)} $')
            elif mo < menu['espresso']['cost']:
                print(f'Sorry that\'s not enough money. Money refunded.')
    elif choice=='l':
        chk=check('latte')
        print(chk)
        if chk=='':
            mo=money()
            if mo == menu['latte']['cost']:
                print('Here is your coffee')
            elif mo > menu['latte']['cost']:
                print(f'Here is your coffee, and here is your change {mo-menu["latte"]["cost"]} $')
                resources['money']=mo+resources['money']
            elif mo < menu['latte']['cost']:
                print(f'Sorry that\'s not enough money. Money refunded.')
    elif choice=='c':
        chk=check('cappuccino')
        print(chk)
        if chk=='':
            mo=money()
            if mo == menu['cappuccino']['cost']:
                print('Here is your coffee')
            elif mo > menu['cappuccino']['cost']:
                print(f'Here is your coffee, and here is your change {mo-menu["cappuccino"]["cost"]} $')
                resources['money']=mo+resources['money']
            elif mo < menu['cappuccino']['cost']:
                print(f'Sorry that\'s not enough money. Money refunded.')

    elif choice=='off':
        break
    time.sleep(3)
    os.system('clear')

The undesired output:
Welcome to the coffee machine.
Espresso = 1.5$
Latte = 2.5$
Cappuccino = 3.0$

What would you like? (espresso/latte/cappuccino)(e/l/c): e

Inset quarters:

The desired output:
Welcome to the coffee machine.
Espresso = 1.5$
Latte = 2.5$
Cappuccino = 3.0$

What would you like? (espresso/latte/cappuccino)(e/l/c): e
Inset quarters:

How can I do that without ruining the code?
Thanks

A: change the line
print(chk)

to
if chk:
    print(chk)

The empty line comes from calling check("expresso") and returning an empty line (no failure message to display)
So you only print chk if it has a message, but you don't print it if it's empty.

A: when check('espresso') exceuted, chk value became empty string. To solve it, you should validate if chk value is not an empty string and then print, else don't do anything. You can change the line :
print(chk)

with this:
print(chk) if chk else ''


text:
Q: Is a smooth function characterized up to translation by its discrete pieces? Let $f, g : \mathbb{R} \to \mathbb{R}$ be smooth, bounded functions, and suppose that for any finite set $X \subset \mathbb{R}$, there is some $t \in \mathbb{R}$ such that for each $x \in X$, $f(x) = g(x + t)$. (I.e., $f$ and $g$ have the same finite restrictions up to translation.) Does it follow that $f$ and $g$ are identical up to some translation?
(For my application I really want the answer to be "yes", so if there are other nice conditions I can impose on $f$ and $g$ to get that answer, that would also be great to know.)

A: The answer is no.
Let $g(x)=\begin{cases}0&x\le 0\\ e^{-1/x^2} & x>0\end{cases}$, and let $f(x)=0$.  Any $X$ you like for $f$, has a translate into the negative reals where $f,g$ agree.  $g(x)$ is constructed to be $C^\infty$ everywhere; it is also bounded above by $1$ (and below by $0$).
A condition you need to impose is that $f,g$ are equal to their Taylor series everywhere.  I'm not sure if that's enough, but it's a start.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calculation of rolling speed in a PandasDataframe I have the following challenge: I have a PandasDataframe with information about a unique ArucoID, a unique frameID and associated coordinates in a coordinate system. For example like this:
# import pandas library
import pandas as pd
# lst_of_dfs = []
# dictionary with list object of values
data1 = {
     'frameID' : [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
     'xPos' : [10.0, 10.5, 11.0, 12.0, 13, 4.0, 5.0, 6.0, 7.0, 9.0, 1.5, 2.0, 2.5, 3.0, 4.0 ],
     'yPos' : [-0.2, -0.1, -0.1, 0.0, 0.0, 0.2, 0.2, -0.1, 0.0, 0.05, -0.2, -0.1, 0.0, 0.1, 0.05],
     'ArucoID' : [910, 910, 910, 910, 910, 898, 898, 898, 898, 898, 912, 912, 912, 912, 912],
     'Subtrial' : ['01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01']
     }
df1 = pd.DataFrame(data1)

data2 = {
     'frameID' : [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
     'xPos' : [9.4, 9.5, 9.0, 9.0, 10, 3.0, 4.0, 5.0, 6.0, 7.0, 2.5, 3.0, 3.5, 3.5, 5.0 ],
     'yPos' : [-0.2, -0.1, -0.1, 0.0, 0.0, 0.2, 0.2, -0.1, 0.0, 0.05, -0.2, -0.1, 0.0, 0.1, 0.05],
     'ArucoID' : [910, 910, 910, 910, 910, 898, 898, 898, 898, 898, 912, 912, 912, 912, 912],
     'Subtrial' : ['02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02']
     }
df2 = pd.DataFrame(data2)

lst_of_dfs = [df1,df2]

# creating a Dataframe object
df_TrajData = pd.concat(lst_of_dfs)

#print(df_TrajData)

Now I calculate the distance between the xPos as rolling mean for the DataFrame grouped by ArucoID:
#calculation of current distance of each ArucoID as rolling mean over a window of n frames (n is set as 2 frames for testing)

all_data = []
df_grouped = df_TrajData.groupby('ArucoID')
for key, data in df_grouped:
    #calc distance covered in window
    dX = data['xPos'] - data['xPos'].shift(2)
    #print(dX)

    data['dX'] = dX

    all_data.append(data)

df = pd.concat(all_data)
#print(df)

And now I get into trouble: I want to calculate the speed [s]. That would be v = dX / (time[-1] - time[0] / framerate), where time[-1] is last frameID of the rolling window, t[0] current frameID and framerate is 30 frames/per/second.
I was starting with (rolling_window=3, min_periods=1):
df['speed'] = df.groupby('ArucoID')['dX'].transform(lambda x: x.rolling(3, 1).mean())

which is the calculation of the rolling distance. What I would actually like to do would be something like that:
df['speed'] = df.groupby('ArucoID')['dX'].transform(lambda s: s.rolling(3, min_periods=1).mean() / (t[-1] - t[0] /framerate))

#print(df)

Any suggestions would be appreciated. Many thanks in advance!

A: I'll assume you want to compute specific mechanical speeds for each device and trial.
Preparing dataset
Let's start with your raw data:
import numpy as np
import pandas as pd

data1 = {
    'ArucoID' : [910, 910, 910, 910, 910, 898, 898, 898, 898, 898, 912, 912, 912, 912, 912],
    'Subtrial' : ['01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01', '01'],
    'frameID' : [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
    'xPos' : [10.0, 10.5, 11.0, 12.0, 13, 4.0, 5.0, 6.0, 7.0, 9.0, 1.5, 2.0, 2.5, 3.0, 4.0 ],
    'yPos' : [-0.2, -0.1, -0.1, 0.0, 0.0, 0.2, 0.2, -0.1, 0.0, 0.05, -0.2, -0.1, 0.0, 0.1, 0.05],
}

data2 = {
    'ArucoID' : [910, 910, 910, 910, 910, 898, 898, 898, 898, 898, 912, 912, 912, 912, 912],
    'Subtrial' : ['02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02', '02'],
    'frameID' : [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
    'xPos' : [9.4, 9.5, 9.0, 9.0, 10, 3.0, 4.0, 5.0, 6.0, 7.0, 2.5, 3.0, 3.5, 3.5, 5.0 ],
    'yPos' : [-0.2, -0.1, -0.1, 0.0, 0.0, 0.2, 0.2, -0.1, 0.0, 0.05, -0.2, -0.1, 0.0, 0.1, 0.05],
}

df = pd.concat([
    pd.DataFrame(data1),
    pd.DataFrame(data2)
])

The key is to shift your position records in order to be able to compute distance.
To do so, we sort records in natural order for this operation and then lag them by device and trial:
df = df.sort_values(["ArucoID", "Subtrial", "frameID"])
shifted = df.groupby(["ArucoID", "Subtrial"]).shift(-1)
shifted = shifted.drop("frameID", axis=1).rename(columns=lambda x: x + "_")
data = pd.concat([df, shifted], axis=1)

Now your data are properly aligned:
#     ArucoID Subtrial  frameID  xPos  yPos  xPos_  yPos_
# 5       898       01        1   4.0  0.20    5.0   0.20
# 6       898       01        2   5.0  0.20    6.0  -0.10
# 7       898       01        3   6.0 -0.10    7.0   0.00
# 8       898       01        4   7.0  0.00    9.0   0.05
# 9       898       01        5   9.0  0.05    NaN    NaN
# 5       898       02        1   3.0  0.20    4.0   0.20
# ...

Speed computations
Distance
Then we can compute the euclidean distance easily:
def distance(x):
    return np.sqrt(np.power(x["xPos"] - x["xPos_"], 2) + np.power(x["yPos"] - x["yPos_"], 2))

data["dist"] = data.apply(distance, axis=1)

Point estimates for speed
And at the same time point estimate and moving averaged speeds:
data["point_speed"] = data["dist"]/(1/30)
data["mov_speed"] = data.groupby(["ArucoID", "Subtrial"]).rolling(3, min_periods=1).mean()["point_speed"].values

    # ArucoID Subtrial  frameID  xPos  yPos  xPos_  yPos_      dist point_speed  mov_speed
# 5       898       01        1   4.0  0.20    5.0   0.20  1.000000   30.000000  30.000000
# 6       898       01        2   5.0  0.20    6.0  -0.10  1.044031   31.320920  30.660460
# 7       898       01        3   6.0 -0.10    7.0   0.00  1.004988   30.149627  30.490182
# 8       898       01        4   7.0  0.00    9.0   0.05  2.000625   60.018747  40.496431
# 9       898       01        5   9.0  0.05    NaN    NaN       NaN         NaN  45.084187
# 5       898       02        1   3.0  0.20    4.0   0.20  1.000000   30.000000  30.000000

Average speed
After that we can aggregate by device and trial to get the total distance and the number of frames:
final = data.groupby(["ArucoID", "Subtrial"]).agg({"dist": "sum", "frameID": "count"}).rename(columns={"frameID": "count"})

#                       dist  count
# ArucoID Subtrial
# 898     01        5.049643      5
#         02        4.050267      5
# 910     01        3.014890      5
#         02        1.741421      5
# 912     01        2.530955      5
#         02        2.620637      5

We can also compute average mechanical speed of each device and trial:
def speed(x, frame_time=1.):
    return x["dist"]/((x["count"] - 1)*frame_time)

final["speed"] = final.apply(speed, axis=1, frame_time=1/30)

#                       dist  count      speed
# ArucoID Subtrial
# 898     01        5.049643      5  37.872323
#         02        4.050267      5  30.377006
# 910     01        3.014890      5  22.611671
#         02        1.741421      5  13.060660
# 912     01        2.530955      5  18.982163
#         02        2.620637      5  19.654778

And merge together all information:
final = data.merge(final["avg_speed"], left_on=["ArucoID", "Subtrial"], right_index=True)
final["speed_ratio"] = final["mov_speed"]/final["avg_speed"]
final["speed_excess"] = 1. - final["speed_ratio"]

To get average speeds aligned with all records.
Post processing
Finally we can pivot those records to easily navigate and render them:
cross = final.pivot_table(index="frameID", columns=["ArucoID", "Subtrial"], values=["point_speed", "mov_speed", "avg_speed", "speed_ratio", "speed_excess"])

For the specific dataset you provided we have the following moving averages:

And how it compares with average speed:


text:
Q: Ubuntu does not boot in Oracle VirtualBox I am using Oracle VirtualBox 5.1.22 on macOS 10.12.5. I configured a Ubuntu 64 bit VM and installed Ubuntu Server 16.04 LTS without any issues. When I reboot the VM to start the Ubuntu instance, I get a blank console window with a non-blinking cursor. I have let it sit there for over an hour and no change (See Image Below).

I have checked the VirtualBox log and the last few lines show the following.
00:00:03.969706 Display::handleDisplayResize: uScreenId=0 pvVRAM=0000000000000000 w=720 h=400 bpp=0 cbLine=0x0 flags=0x0
00:00:03.969749 GUI: UIFrameBufferPrivate::NotifyChange: Screen=0, Origin=0x0, Size=720x400, Sending to async-handler
00:00:03.971483 VMMDev: Guest Log: BIOS: Booting from Hard Disk...
00:00:03.996305 GUI: UIMachineView::sltHandleNotifyChange: Screen=0, Size=720x400
00:00:03.996325 GUI: UIFrameBufferPrivate::handleNotifyChange: Size=720x400
00:00:03.996340 GUI: UIFrameBufferPrivate::performResize: Size=720x400, Directly using source bitmap content

The log shows it hanging on this and never changing. I have tried different VM configuration settings (ex. increased video memory, change chipset, etc) but have had no success. I also tried this on another Mac computer and got the same results.
Note, other VM installations work fine. Example CentOS.
Any ideas what might be going on?
Thank you

A: This is embarrassing but I had not installed Ubuntu with Grub. When I started over and installed it with Grub, the ubuntu VM booted with no issues.
Thanks


text:
Q: Subset of a normal subgroup is a subgroup? I am studying Dummit & Foote abstract algebra. This question is what I have a problem.

Let $G$ be a finite group, $H$ be a subgroup of $G$, $N$ be a normal subgroup of $G$. If $|H|$ and $|G:N|$ are relatively prime, prove that $H$ is a subgroup of $N$.

I founded that $H$ is a subset of $N$. But I can't find how to prove about subgroup. Does normality implies that subset becomes a subgroup? If not, how can I prove it?

A: Your hypothesis includes that H is a subgroup of G, to prove that it is a subgroup of N, you only need to prove that it is a subset of N which you just did.


text:
Q: Create multiple select depending on previous choices with values from DB Can anybody help me how to obtain this with (php/js or jquery)? I'm still beginner.
I have table in mysql which contains beyond other (and I don't know it before checking the DB)

*

*name of company (for ex. Abc, Def...)

*year

*month

*and some data for each month different ones

I need to create a form which in first select field I load available name of company. When user select one of them (Abc) it should display only appropriate year - filled for that company (2000, 2008, 2012) and etc. for (selected year just filled month).
I've done working the first part (bellow) but how to handle with different selects for different companies if I don't know possible combinations without checking DB.
<?php
echo "Select company: <select name=\"company\">";
    $con=connect();
    $result = mysqli_query($con,"SELECT * FROM Company");
    while($row = mysqli_fetch_array($result)) {
        echo "<option value=\"".$row['Name']."\">".$row['Name']."</option>";
    }
    mysqli_close($con);
    echo "</select><br>";
?>

A:     in order to do that you need to use Ajax , suppose the ajax file is relatedYears.php
    in relatedYears.php, write the following code

    <?php
    $con=connect();
    $result="";

    //this is the company name sent by url using ajax in the main page
    $company_name= $_GET['company_name'];

    $query= "SELECT years FROM COMPANY WHERE company = $company_name";
    $x=mysql_query($query) or die('error query');
    $years=array();
    while($row=mysql_fetch_row($x))
      $years[]= $row[0];

    foreach($years as $year)
      $results .= "<option value='".$year."'>".$year."</option>";

    echo $results;
    ?>


text:
Q: This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery' SELECT MAX(issue) AS issue_one FROM issue_list
WHERE issue NOT IN (SELECT issue FROM issue_list ORDER BY id ASC LIMIT 46);

what is wrong with this query. it says. This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
The thing I want to do here is get the maximum value of issue from issue_list table neglecting first 46 rows.
How to do that?

A: As Mihai mentions in his comment: try wrapping the sub-select in another sub-select. Looks dirty but is as close to your original query as you're going to get. Hence:
SELECT MAX(issue) AS issue_one
FROM issue_list
WHERE issue NOT IN
(SELECT issue from
 (SELECT issue FROM issue_list ORDER BY id ASC LIMIT 46) x
);

A: I never get Limit to work in Subquery, in either form. So what works for me...

*

*Create View of Sub query with such limit or other limitation in your case it is limit keyword
Create View viewIssue46 as SELECT issue FROM issue_list ORDER BY id ASC LIMIT 46;

*Write query like
SELECT MAX(issue) AS issue_one FROM issue_list WHERE issue NOT IN (select * from viewIssue46)
this usually solve such issue with ease even more complex queries, plus you can use index in views and main queries.


text:
Q: Finding the max and min in a tuple of tuples I'm new to python and having some problems finding the minimum and maximum values for a tuple of tuples. I need them to normalise my data. So, basically, I have a list that is a row of 13 numbers, each representing something. Each number makes a column in a list, and I need the max and min for each column. I tried indexing/iterating through but keep getting an error of
max_j = max(j)

TypeError: 'float' object is not iterable

any help would be appreciated!
The code is (assuming data_set_tup is a tuple of tuples, eg ((1,3,4,5,6,7,...),(5,6,7,3,6,73,2...)...(3,4,5,6,3,2,2...)) I also want to make a new list using the normalised values.
normal_list = []

for i in data_set_tup:

    for j in i[1:]: # first column doesn't need to be normalised
        max_j = max(j)
        min_j = min(j)
        normal_j = (j-min_j)/(max_j-min_j)
        normal_list.append(normal_j)
    normal_tup = tuple(normal_list)

A: You can transpose rows to columns and vice versa with zip(*...). (Use list(zip(*...)) in Python 3)
cols = zip(*data_set_tup)
normal_cols = [cols[0]] # first column doesn't need to be normalised
for j in cols[1:]:
    max_j = max(j)
    min_j = min(j)
    normal_cols.append(tuple((k-min_j)/(max_j-min_j) for k in j)

normal_list = zip(*normal_cols)

A: This really sounds like a job for the non-builtin numpy module, or maybe the pandas module, depending on your needs.
Adding an extra dependency on your application should not be done lightly, but if you do a lot of work on matrix-like data, then your code will likely be both faster and more readable if you use one of the above modules throughout your application.
I do not recommend converting a list of lists to a numpy array and back again just to get this single result -- it's better to use the pure python method of Jannes answer. Also, seeing that you're a python beginner, numpy may be overkill right now. But I think your question deserves an answer pointing out that this is an option.
Here's a step-by-step console illustration of how this would work in numpy:
>>> import numpy as np
>>> a = np.array([[1,3,4,5,6],[5,6,7,3,6],[3,4,5,6,3]], dtype=float)
>>> a
array([[ 1.,  3.,  4.,  5.,  6.],
       [ 5.,  6.,  7.,  3.,  6.],
       [ 3.,  4.,  5.,  6.,  3.]])
>>> min = np.min(a, axis=0)
>>> min
array([1, 3, 4, 3, 3])
>>> max = np.max(a, axis=0)
>>> max
array([5, 6, 7, 6, 6])
>>> normalized = (a - min) / (max - min)
>>> normalized
array([[ 0.        ,  0.        ,  0.        ,  0.66666667,  1.        ],
       [ 1.        ,  1.        ,  1.        ,  0.        ,  1.        ],
       [ 0.5       ,  0.33333333,  0.33333333,  1.        ,  0.        ]])

So in actual code:
import numpy as np

def normalize_by_column(a):
    min = np.min(a, axis=0)
    max = np.max(a, axis=0)
    return (a - min) / (max - min)

A: We have nested_tuple = ((1, 2, 3), (4, 5, 6), (7, 8, 9)).
First of all we need to normalize it. Pythonic way:
flat_tuple = [x for row in nested_tuple for x in row]

Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] # it's a list
Move it to tuple: tuple(flat_tuple), get max value: max(flat_tuple), get min value: min(flat_tuple)


text:
Q: Getting error:'Image' does not contain a definition for 'DetectHaarCascade' and no accessible extension method 'DetectHaarCascade' I'm a doing a project on face detection using EmguCV in C#.My goal is to detect faces from a webcam. Meanwhile I am getting some errors.
I included all EmguCV dependencies and OpenCV dependencies.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;

namespace demo
{
    public partial class Form1 : Form
    {
        private VideoCapture cap;
        private CascadeClassifier haar;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // passing 0 gets zeroth webcam
            cap = new VideoCapture(0);
            // adjust path to find your xml
            haar = new CascadeClassifier("haarcascade_frontalface_alt2.xml");
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            using (Image<Bgr, byte> nextFrame = cap.QueryFrame().ToImage<Bgr, Byte>())
            {
                if (nextFrame != null)
                {
                    // there's only one channel (greyscale), hence the zero index
                    //var faces = nextFrame.DetectHaarCascade(haar)[0];
                    Image<Gray, byte> grayframe = nextFrame.Convert<Gray, byte>();
                    var faces =
                            grayframe.DetectHaarCascade(haar, 1.4, 4,HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,new Size(nextFrame.Width / 8, nextFrame.Height / 8))[0];
                    foreach (var face in faces)
                    {
                        nextFrame.Draw(face.rect, new Bgr(0, double.MaxValue, 0), 3);
                    }
                    pictureBox1.Image = nextFrame.ToBitmap();
                }
            }
        }
    }
}

I tried replacing DetectHaarcascade with Detectmultiscale.

ErrorCS1061:'Image' does not contain a definition for 'DetectHaarCascade' and no accessible extension method 'DetectHaarCascade' accepting a first argument of type 'Image' could be found (are you missing a using directive or an assembly reference?)
ErrorCS0103:The name 'HAAR_DETECTION_TYPE' does not exist in the current context
ErrorCS1579:foreach statement cannot operate on variables of type '?' because '?' does not contain a public instance definition for 'GetEnumerator'

A: Try adding these librarirs:
using Emgu.CV.UI;
using System.Drawing;
using System.Diagnostics;


text:
Q: Single Source of Truth (DRY) to validate AngularJS Forms on client- and server-side I am planning a new project based on AngularJS on the client and let's say Java or PHP on the server.
The AngularJS application provides a simple form for registration, e.g. username, first and last name, e-mail, password and confirm password.
I am currently searching for the best way to define the validation for the form's input data.
On the one hand, the definition should impact the client application. For example, the validation defines that the username must have 4 to 14 characters and AngularJS should display an error on invalid input without sending a validation request to the server first. I imagine that AngularJS reads the definition file (maybe JSON or XML) on start up and enforces those requirements on the client-side.
On the other hand, the server-side code, which receives the submitted form data, should also rely on the same definition file in order to validate the passed form data.
Of course, there are some validations the client cannot perform without the server, for instance, whether an unique username was entered.
My question is, whether there is a framework, extension, best practice, or recipe how to implement such a Single Source of Truth for form input validation when using AngularJS on the client-side and for example Java or PHP on the server-side?

A: I've used Spring on the back-end, Angular on the front, and I have wondered the same thing while doing validation, but there isn't any type of framework for this. Your best bet is to use HTTP standards to communicate errors from the back end.
For example, if you complete client-side validation (username and password are long enough, not null, etc) and then send that data to the back end to make sure the username isn't already taken, you would then want to respond with an appropriate HTTP status code along with whatever else is in your response. In this case, a 200 status if everything was okay on the back-end, or something like a 409 for conflict. HTTP is likely the standard you are looking for, and it still allows you incredible flexibility.
Then, you can handle these status codes within Angular and do different things client-side after handling the logic.

A: I found http://json-schema.org/ and will stick to the implementations https://github.com/everit-org/json-schema for the server-side Java validation and https://github.com/zaggino/z-schema for the client-side JavaScript validation.


text:
Q: PEAP WiFi authentication issues I've looked at similar posts on this topic but nothing so far is working.
Unfortunately I can connect to my Colleges Guest WIFI but not the actual WiFi. The school is running security: WPA & WPA2 Enterprise and PEAP authentication.
Some of the things I've tried is:

*

*changing the config file inside /etc/NetworkManager/system-connections. My config file does not have
system-ca-cert=true

*Attaching the schools CA Certificate (From the IT Deparment)

*Changing the user name schema to Domain\Username

*Trying to install drivers (however that's a rabbit hole inside a rabbit hole) etc.


text:
Q: Image missing in RSS/ATOM with Django I'm trying to attach an image to my ATOM and RSS syndication feed thanks to the Django's documentation : https://docs.djangoproject.com/fr/1.11/ref/contrib/syndication/
I have to kind of feed : http://example.com/rss and http://mywebsite.com/atom
rss.py
class LatestEntriesFeed(Feed):
title = "MyWebsite"
link = "/"
description = "Latest news"

def items(self):
    return Articles.objects.filter(published=True).order_by('-date')[:5]

def item_description(self, item):
    return '<![CDATA[  ]]>'

def item_title(self, item):
    return item.title

def item_pubdate(self, item):
    return item.date

def item_updateddate(self, item):
    return item.update

def item_author_name(self, item):
    return item.author

def item_author_link(self, item):
    item_author_link = Site_URL + reverse('team', kwargs={'username': item.author})
    return item_author_link

def item_author_email(self):
    return EMAIL_HOST_USER

class LatestEntriesFeedAtom(LatestEntriesFeed):
    feed_type = Atom1Feed
    subtitle = LatestEntriesFeed.description

So I think I have to use CDATA into the description html tag. However, in Django (version 1.11), item_description doesn't return <description> tag in the XML, but a  tag.
Is it fine or is it the source of the issue ?
Otherwise, I tried to scan with W3C validator and I get 2 errors (or just warnings ?)
1) Self reference doesn't match document location
2) Invalid HTML: Expected '--' or 'DOCTYPE'. Not found. (5 occurrences)

A: I found the solution.
I gave up the CDATA tag to follow this kind of structure :
def item_description(self, item):
  return '

My Image description

Some text
'

I was helped by the Google manual : https://support.google.com/news/publisher-center/answer/9545420?hl=fr


text:
Q: How to handle a Docker RUN apt install command that wants to install systemd service What is the proper way to go about using an Aptitude package that wants to install a systemd service on Linux within a Docker container?
Here is the output:
krzysztof@pop-devx:~/docker2_edgeiq$ docker compose build
[+] Building 3.8s (21/22)
 => [internal] load build definition from Dockerfile                                                                                0.0s
 => => transferring dockerfile: 604B                                                                                0.0s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 2B                                                                                0.0s
 => resolve image config for docker.io/docker/dockerfile:1                                                                                0.2s
 => CACHED docker-image://docker.io/docker/dockerfile:1@sha256:39b85bbfa7536a5feceb7372a0817649ecb2724562a38360f4d6a7782a409b14                                  0.0s
 => [internal] load metadata for docker.io/library/ubuntu:latest                                                                                0.2s
 => [internal] load build context                                                                                0.0s
 => => transferring context: 186B                                                                                0.0s
 => [ 1/16] FROM docker.io/library/ubuntu:latest@sha256:9a0bdde4188b896a372804be2384015e90e3f84906b750c1a53539b585fbbe7f                                         0.0s
 => CACHED [ 2/16] WORKDIR /edgeiq                                                                                0.0s
 => CACHED [ 3/16] RUN apt-get update                                                                                0.0s
 => CACHED [ 4/16] RUN apt-get install -y sudo                                                                                0.0s
 => CACHED [ 5/16] RUN sudo apt-get upgrade -y                                                                                0.0s
 => CACHED [ 6/16] RUN sudo apt-get install -y ca-certificates                                                                                0.0s
 => CACHED [ 7/16] RUN sudo apt-get install -y zip                                                                                0.0s
 => CACHED [ 8/16] RUN sudo su && echo "deb [trusted=yes] https://apt.fury.io/edgeiq/ /" > /etc/apt/sources.list.d/edgeiq.list                                   0.0s
 => CACHED [ 9/16] RUN sudo apt-get update                                                                                0.0s
 => CACHED [10/16] RUN sudo apt-get install edgeiq-edgectl                                                                                0.0s
 => CACHED [11/16] COPY edgeiq_bootstrap.json .                                                                                0.0s
 => CACHED [12/16] COPY edgeiq_identifier.json .                                                                                0.0s
 => CACHED [13/16] RUN pwd                                                                                0.0s
 => CACHED [14/16] RUN ls -lash                                                                                0.0s
 => ERROR [15/16] RUN sudo edgectl install -b ./edgeiq_bootstrap.json                                                                                3.1s
------
 > [15/16] RUN sudo edgectl install -b ./edgeiq_bootstrap.json:
#0 0.272 Installing edge to '/opt/edge/'...
#0 1.051 Downloading edge from https://api.edgeiq.io/api/v1/platform/releases/latest/edge-linux-amd64-latest...
#0 3.058 Issue installing Edge: Issue enabling edge.service: sh: 1: systemctl: not found
#0 3.058
#0 3.058 exit status 127
#0 3.058
------
failed to solve: process "/bin/sh -c sudo edgectl install -b ./edgeiq_bootstrap.json" did not complete successfully: exit code: 1
krzysztof@pop-devx:~/docker2_edgeiq$

The Dockerfile is the following:
# syntax=docker/dockerfile:1
FROM ubuntu:latest
WORKDIR /edgeiq
RUN apt-get update
RUN apt-get install -y sudo
RUN sudo apt-get upgrade -y
#RUN sudo apt-get install -y systemd
RUN sudo apt-get install -y ca-certificates
RUN sudo apt-get install -y zip
RUN sudo su && echo "deb [trusted=yes] https://apt.fury.io/edgeiq/ /" > /etc/apt/sources.list.d/edgeiq.list
RUN sudo apt-get update
RUN sudo apt-get install edgeiq-edgectl
COPY edgeiq_bootstrap.json .
COPY edgeiq_identifier.json .
RUN pwd
RUN ls -lash
RUN sudo edgectl install -b ./edgeiq_bootstrap.json
COPY . .

Someone must have though of this because there is a lot of packages in apt that install as a service.  What is the best way to do this?

A: You can tell edgectl not to start the service by providing the --no-start option:
RUN edgectl install -b ./edgeiq_bootstrap.json --no-start

You will of course need to figure out how to start the service without using systemd. It looks like a systemd unit file is available in /opt/edge/init/systemd/edge.service; you should be able to inspect that and extract the appropriate command from the ExecStart directive.

Unrelated to your question, but you can drop all those sudo calls in your Dockerfile. The fact that you're able to install sudo in the first place means you're already running as root. You could simplify things down to:
# syntax=docker/dockerfile:1
FROM ubuntu:latest
WORKDIR /edgeiq

RUN apt-get update
RUN apt-get upgrade -y
RUN apt-get install -y ca-certificates sudo zip
RUN echo "deb [trusted=yes] https://apt.fury.io/edgeiq/ /" > /etc/apt/sources.list.d/edgeiq.list
RUN apt-get update && apt-get -y install edgeiq-edgectl
COPY edgeiq_bootstrap.json .
COPY edgeiq_identifier.json .
RUN pwd; ls -lash
RUN edgectl install -b ./edgeiq_bootstrap.json --no-start


text:
Q: Dagger 2: NoClassDefFoundError: dagger/producers/ProducerModule I am trying to integrate Dagger 2 with eclipse and the libs that I have used are as follows:
dagger-2.0.jar
dagger-compiler-2.0.jar
guava-13.0.1.jar
javawriter-1.0.5.jar
javax.annotation-api-1.2.jar
javax.inject-1.jar

Java Compiler -> Annotation processing has been enabled
All the above have been added to the Factory Path
But I get the following error when I build the project:
Description Resource    Path    Location    Type
Internal compiler error: java.lang.NoClassDefFoundError: dagger/producers/ProducerModule at dagger.internal.codegen.ComponentProcessor.initSteps(ComponentProcessor.java:90)    BuildConfig.java    /DIDemo/gen/com/example/didemo  line 0  Java Problem

Could someone please help?

A: In addition to dagger-2.0 and so forth, you'll need a separate dagger-producers artifact, available from the Maven Central Repository search linked from the Dagger 2 GitHub page.
As of right now (October 2015), the latest file is named dagger-producers-2.0-beta.jar.


text:
Q: Wicket - how to refresh single row in a table with ajax In my wicket application I have a table where each column of a row described by one bean. One of the column contains an ajax component that can change the values in the bean and therefore the values displayed in other columns.
How can I update these columns without reloading the whole table?
Now I use the following code:
public static <T> void refreshTableRow(AjaxRequestTarget target, Item<ICellPopulator<T>> columnItem) {
    for (Component component : columnItem.getParent()) {
        if (component instanceof Item) {
            ((Item<?>) component).stream()
                    .filter(Component::getOutputMarkupId)
                    .forEach(target::add);
        }
    }
}

But for the proper work of this code I have to set outputMarkupId(true) for the root component of each column, created in IColumn#populateItem.
Is there any other way to do this?

A: Override DataTable#newRowItem() and return some custom Item implementation that has outputMarkupId = true.
public class MyRow<T> extends Item<T> {
   public MyRow<T>(String id, int index, IModel<T> model) {
     super(id, index, model);

     setOutputMarkupId(true);
   }
}

Then in your Ajax callback method do:
ajaxRequestTarget.add(findParent(MyRow.class));


text:
Q: Parse: Do users created with 'enableAutomaticUser' get discarded every time the app is terminated? Parse version 1.7.1 as built by Cocoapods
I have a completely bare project where I set up an anonymous user through [PFUser enableAutomaticuser]. Judging by the _Users table in Parse, it looks like the ID's are discarded when I terminate the app, and regenerated on the subsequent app launch.
At no point do I log out or do anything that should nil out the user.
Is this the intended behavior or a bug?
My code, if it matters:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
    // Initialize Parse.
    Parse.setApplicationId(APP_ID,
        clientKey: CLIENT_KEY)

    // Create or authenticate anonymous user
    PFUser.enableAutomaticUser()
    PFUser.currentUser()!.saveEventually { (success:Bool, error:NSError?) -> Void in
        if (success)
        {
             // Setup push notifications
        }
    }

    // Track statistics around application opens.
    PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)

    return true
}

If it helps...
Looks like the user exists at the last moment of the app's lifetime in applicationWillTerminate:, but it is nil in the next launch's applicationDidFinishLauchingWithOptions: before the call to enable the automatic user.


text:
Q: How to get LaTeX math into Legend of R plot I'm trying to add a latex math expression to the legend and labels of a chart made in R but haven't found any examples where this has worked.  For example, my y-axis label should be like "Availability, $\hat{A}_o$".  My legend should be text <- c("Linear, m=1", "Square Root, m=1/2", "Cube Root, m=1/3"), where the m-expresions should be in latex math.   My code is ...
    rm(list = setdiff(ls(), lsf.str()))
require(graphics)
library(latex2exp)
Linear<-c(  1,0.983666667,0.967333333,0.951,0.934666667,0.918333333,0.902,0.885666667,
           0.869333333,0.853,0.836666667,0.820333333,0.804,0.787666667,0.771333333,
           0.755,0.738666667,0.722333333,0.706,0.689666667,0.673333333,0.657,0.640666667,
           0.624333333,0.608,0.591666667,0.575333333,0.559,0.542666667,0.526333333,0.51)
SqRt<-c(    1   ,   0.910538649 ,   0.873482544 ,   0.845048395 ,   0.821077298 ,
         0.799958338    ,   0.780865338 ,   0.763307513 ,   0.746965088 ,   0.731615947 ,
         0.717098368    ,   0.703290265 ,   0.690096789 ,   0.677442512 ,   0.665266275 ,
         0.653517677    ,   0.642154596 ,   0.6311414   ,   0.620447632 ,   0.610047011 ,
         0.599916675    ,   0.590036587 ,   0.580389069 ,   0.570958432 ,   0.561730676 ,
         0.552693245    ,   0.543834825 ,   0.535145184 ,   0.526615026 ,   0.518235881 ,   0.51    )
CubeRt<-c(  1   ,   0.842124513 ,   0.801135304 ,   0.772387515 ,   0.749504067 ,   0.730181506 ,
           0.71329249   ,   0.698190887 ,   0.684467813 ,   0.671846185 ,   0.660128536 ,
           0.649168592  ,   0.638854625 ,   0.629099142 ,   0.619832193 ,   0.610996874 ,
           0.602546197  ,   0.59444086  ,   0.586647616 ,   0.579138061 ,   0.571887715 ,
           0.56487531   ,   0.558082241 ,   0.551492126 ,   0.545090459 ,   0.538864322 ,
           0.532802159  ,   0.526893586 ,   0.521129232 ,   0.515500609 ,   0.51    )

g_range <- range(0, Linear, SqRt,CubeRt,na.rm = TRUE)
plot(Linear, type="l",lwd=2, col="blue", ylim=g_range,
     axes=FALSE, ann=FALSE,lty=1)
axis(1, at=c(0,5,10,15,20,25,30))

axis(2, las=1)

box()
lines(SqRt, type="l", pch=22, lty=1,lwd=2, col="red")
lines(CubeRt, type="l", pch=24, lty=1,lwd=2, col="black")

title(xlab="mmh/RH", col.lab=rgb(0,0,0))
title(ylab="Availability, $\hat{A}_o$", col.lab=rgb(0,0,0))

plot_colors <- c("blue","red", "black")
text <- c("Linear", "Square Root", "Cube Root")
#legend(x=14, y=1.0, legend=text, fill=plot_colors, ncol=3, xpd=NA)
legend('topright', legend=TeX("Linear, m=1","Square Root", "Cube Root"),
       fill=plot_colors, ncol=3, xpd=NA)

A: I don't know anything about latex2exp, but the tikzDevice package can handle TeX fairly straightforwardly.  Here's a version of your code using that package:
The only downside of this is that the package is not being actively maintained, and so this might not work at some point.
library(tikzDevice)
options(tikzMetricPackages = c("\\usepackage{amsmath}",
                               "\\usepackage{xcolor}",
                               "\\usepackage{tikz}",
                               "\\usetikzlibrary{calc}"))
Linear<-c(  1,0.983666667,0.967333333,0.951,0.934666667,0.918333333,0.902,0.885666667,
            0.869333333,0.853,0.836666667,0.820333333,0.804,0.787666667,0.771333333,
            0.755,0.738666667,0.722333333,0.706,0.689666667,0.673333333,0.657,0.640666667,
            0.624333333,0.608,0.591666667,0.575333333,0.559,0.542666667,0.526333333,0.51)
SqRt<-c(    1   ,   0.910538649 ,   0.873482544 ,   0.845048395 ,   0.821077298 ,
            0.799958338    ,   0.780865338 ,   0.763307513 ,   0.746965088 ,   0.731615947 ,
            0.717098368    ,   0.703290265 ,   0.690096789 ,   0.677442512 ,   0.665266275 ,
            0.653517677    ,   0.642154596 ,   0.6311414   ,   0.620447632 ,   0.610047011 ,
            0.599916675    ,   0.590036587 ,   0.580389069 ,   0.570958432 ,   0.561730676 ,
            0.552693245    ,   0.543834825 ,   0.535145184 ,   0.526615026 ,   0.518235881 ,   0.51    )
CubeRt<-c(  1   ,   0.842124513 ,   0.801135304 ,   0.772387515 ,   0.749504067 ,   0.730181506 ,
            0.71329249   ,   0.698190887 ,   0.684467813 ,   0.671846185 ,   0.660128536 ,
            0.649168592  ,   0.638854625 ,   0.629099142 ,   0.619832193 ,   0.610996874 ,
            0.602546197  ,   0.59444086  ,   0.586647616 ,   0.579138061 ,   0.571887715 ,
            0.56487531   ,   0.558082241 ,   0.551492126 ,   0.545090459 ,   0.538864322 ,
            0.532802159  ,   0.526893586 ,   0.521129232 ,   0.515500609 ,   0.51    )

tikz("test-tikz.tex",standAlone = TRUE,packages=c("\\usepackage{amsmath}",
                                                "\\usepackage{tikz}",
                                                "\\usepackage{xcolor}",
                                                "\\usetikzlibrary{calc}",
                                                "\\usepackage[active,tightpage,psfixbb]{preview}",
                                                "\\PreviewEnvironment{pgfpicture}"))
g_range <- range(0, Linear, SqRt,CubeRt,na.rm = TRUE)
plot(Linear, type="l",lwd=2, col="blue", ylim=g_range,
     axes=FALSE, ann=FALSE,lty=1)
axis(1, at=c(0,5,10,15,20,25,30))

axis(2, las=1)

box()
lines(SqRt, type="l", pch=22, lty=1,lwd=2, col="red")
lines(CubeRt, type="l", pch=24, lty=1,lwd=2, col="black")

title(xlab="$mmh/RH$", col.lab=rgb(0,0,0))
title(ylab="Availability, $\\hat{A}_o$", col.lab=rgb(0,0,0))

plot_colors <- c("blue","red", "black")
text <- c("Linear, $m=1$", "Square Root, $m=1/2$", "Cube Root, $m=1/3$")
#legend(x=14, y=1.0, legend=text, fill=plot_colors, ncol=3, xpd=NA)
legend('topright', legend=text,
       fill=plot_colors, ncol=3, xpd=NA)
dev.off()
tools::texi2pdf("test-tikz.tex")
system(paste(getOption("pdfviewer"), "test-tikz.pdf"))


text:
Q: Search bar in TableView Controller is too short I've got a tableview controller and I've added a search bar programatically.  It shows up when I scroll up in the tableview and I can see the preview text if I keep pulling on the table.
However, when I let go - the table scrolls up a few pixels and I end up with a search bar that is too short for the preview text and looks like the below. It is missing the placeholder text and it is shorter than it should be.  Help!

If I tap in the field, it expands and shifts up to this:

And if I then hit cancel, then it goes to how I expect it to look in the first step. But the only way I can it to this 'correct' state is to tap into the squished field with no placeholder text, then it expands, then I hit cancel and have what I want until I scroll again....

But as soon as I scroll at all, it reverts back to this squished state in the first image.
I'm adding it programmatically in viewDidLoad() with:
let search = UISearchController(searchResultsController: nil)
search.searchResultsUpdater = self
search.obscuresBackgroundDuringPresentation = false
search.searchBar.placeholder = "Type something here to search"
navigationItem.searchController = search

Suggestions??

A: Turns out it was unrelated to the search bar, but some legacy code that was in the controller that was there to scroll section headers with the table rather than locking them when they hit the top of the view.
Removed that and changed the table style to grouped and that fixed the header scroll while also addressing the unintended impact to my search bar.
Now all behaving as it should.  Leaving here in case useful to others.


text:
Q: React - setState doesn't refresh component as expected I might be experiencing either a bug, or I misunderstand something about general javascript syntax.
Using ServiceNow UI Builder, I'm trying to refresh the datasource of a specific data visualization component. Which requires me to use setState and send in an entire JSON blob.
The following works as expected:
api.setState('intAssignedDonut', {
        "header": "Interactions assigned to one of my groups",
        "datasource": [{
            "isDatabaseView": false,
            "allowRealTime": true,
            "sourceType": "table",
            "label": {
                "message": "Interaction"
            },
            "tableOrViewName": "interaction",
            "filterQuery": "active=true^assignment_groupDYNAMICd6435e965f510100a9ad2572f2b47744",
            "id": "intAssigned",
            "elm": {}
        }],
        "metric": [{
            "dataSource": "intAssigned",
            "id": "intAssignedMetric",
            "aggregateFunction": "COUNT",
            "numberFormat": {
                "customFormat": false
            },
            "axisId": "primary"
        }],
        "groupBy": [{
            "maxNumberOfGroups": "ALL",
            "numberOfGroupsBasedOn": "NO_OF_GROUP_BASED_ON_PER_METRIC",
            "showOthers": false,
            "groupBy": [{
                "dataSource": "intAssigned",
                "groupByField": "state",
                "isRange": false,
                "isPaBucket": false
            }]
        }]
    });

However, I only need to alter a few properties, not the whole thing.
So I thought I'd just clone the thing into a temp object, change what I need, then pass the cloned object back.
let clientState_intAssignedDonut = api.state.intAssignedDonut;
clientState_intAssignedDonut.header = 'Interactions assigned to one of my groups';
clientState_intAssignedDonut.datasource[0].filterQuery = 'active=true^assignment_groupDYNAMICd6435e965f510100a9ad2572f2b47744';

api.setState("intAssignedDonut", clientState_intAssignedDonut);

This seems to update the header properly, but the component doesn't refresh the datasource.
Even if I console.log api.state.intAssignedDonut it looks identical to the whole JSON blob.
EDIT: I also tried using spread operators, but I can't figure out how to target the datasource[0]
api.setState("intAssignedDonut", {
        ...api.state.intAssignedDonut,
        header: "Interactions assigned to one of my groups",
        datasource[0].filterQuery: "active=true^assignment_groupDYNAMICd6435e965f510100a9ad2572f2b47744"
    });

A: Javascript objects are passed by reference values, and react state is immutable:
let clientState_intAssignedDonut = api.state.intAssignedDonut;
api.setState("intAssignedDonut", clientState_intAssignedDonut);

This is mutating the state directly, and React will ignore your update if the next state is equal to the previous state, which is determined by an Object.is comparison to check if both objects are of the same value, see docs
Your second attempt is heading to the right direction using spread operator:
Update method one: first copy the nested object using: JSON.parse(JSON.stringify(object)), or you can find other method in this question: What is the most efficient way to deep clone an object in JavaScript?
let copied = JSON.parse(JSON.stringify(api.state.intAssignedDonut)); // copy a nested object
copied.header = "Interactions assigned to one of my groups";
copied.datasource[0].filterQuery = "active=true^assignment_groupDYNAMICd6435e965f510100a9ad2572f2b47744";
setState("intAssignedDonut",copied);

Update method two:
setState("intAssignedDonut",{
  ...api.state.intAssignedDonut,
  header: "Interactions assigned to one of my groups",
  datasource: [{ ...state.datasource[0], filterQuery: "active=true^assignment_groupDYNAMICd6435e965f510100a9ad2572f2b47744" }]
});

Check out sandbox


text:
Q: "SparkException: Job aborted" when Koalas writes to Azure blob storage I am using Koalas (pandas API on Apache Spark) to write a dataframe out to a mounted Azure blob storage.  When calling the df.to_csv API, Spark throws an exception and aborts the job.
Only a few of the stages seem to fail with the following error:
This request is not authorized to perform this operation using this
permission.

I am handling the data with Databricks on Azure using PySpark.  The data products reside in a mounted Azure Blob storage.  A service principle for databricks was made and is set as "contributer" to the Azure storage account.
When looking into the storage account, I notice that some of the first blobs were already prepared in the directory.  Moreover, I am able to place the output in the blob storage using a "pure Python" approach with pandas.  Therefore, I doubt that it has to do with authorization issues for Databricks.
This is the minimal coding example of what I used to create the error.
<Test to see if the blob storage is mounted>
# Import koalas
import databricks.koalas as ks
# Load the flatfile
df = ks.read_csv('/dbfs/spam/eggs.csv')
# Apply transformations
# Write out the dataframe
df.to_csv('/dbfs/bacon/eggs.csv')

Since there are many facets to this issue, I am uncertain where to start:

*

*Authorization issue between the blob storage and Databricks

*Incorrect setup of the Databricks cluster

*Applying the wrong API method

*Issue with the file content
Any leads on where to look?


text:
Q: Solving mutually recursive constraints in Prolog I am attempting to solve some mutually recursive constraints with SWI-Prolog. These constraints are relatively simple, but querying any of these predicates leads to infinite recursion:
%If X is an animal, then X is a bird or a mammal, and vice-versa.
animal(X) :-
    (mammal(X);bird(X)),
    (male(X);female(X)).

male(X) :- animal(X).
female(X) :- animal(X).

bird(X) :- (X='parrot';X='pigeon'),animal(X).

mammal(X) :- (X='cat';X='dog'),animal(X).

Would it be possible to solve these constraints in Prolog without making them non-recursive?
I wrote a similar program with several base cases, but the query mammal(X),bird(X) still leads to infinite recursion instead of returning false:
%If X is an animal, then X is a bird or a mammal, and vice-versa.
animal(X) :-
    (mammal(X);bird(X)).

bird('parrot').
bird('pigeon').
bird(X) :- (X='parrot';X='pigeon'),animal(X).

mammal('cat').
mammal('dog').
mammal(X) :- (X='cat';X='dog'),animal(X).

A: Solving a recursive constraint requires one or more base cases; you have not provided any.  The problem isn't with Prolog; its with the problem definition.

A: It is possible to find solutions for mutually recursive constraints using constraint handling rules.
This is a set of mutually recursive constraints:
%If X is an animal, then X is a bird or a mammal, and vice-versa.
:- use_module(library(chr)).

:- chr_constraint mammal/2,bird/2,animal/1,male/1,female/1,species/2.

animal(X) <=>
    (mammal(X,Species);bird(X,Species)),
    (male(X);female(X)).

male(X),female(X) ==> false.

bird(X,Species) <=> member(Species,[parrot,pigeon,crow]),species(X,Species).
bird(X,Species) ==> animal(X).

mammal(X,Species) <=> member(Species,[cat,dog,bull]),species(X,Species).
mammal(X,Species) ==> animal(X).

species(X,bull) ==> male(X).

...and this is the output of a query for this program:
?- male(X),mammal(X,Species).
male(_G67406)
species(_G67406,cat)
Species = cat

A: I think what you're trying to get at is that you have birds and you have mammals. And you are further trying to establish that a creature is an animal if it is either a bird or a mammal.
The code currently over-specifies, and has circular logic.
Walking through the code...
animal(X) :-
    (mammal(X); bird(X)).

This says that X is an animal if X is a mammal or X is a bird. So far, so good.
The description of bird reads:
bird('parrot').
bird('pigeon').

These are facts that indicate that a parrot is a bird and a pigeon is a bird. But then there's this rule:
bird(X) :- (X='parrot';X='pigeon'),animal(X).

Which says that X is a bird if X is either a parrot or pigeon, AND if X is an animal. The prior two facts already establish that parrot and pigeon are birds. Why is this rule necessary? And it further adds the condition that X is an animal, which is, in turn, defined in terms of bird and mammal, so is circular.
Similar holds true for the mammal definition. It has the needed facts for mammals:
mammal('cat').
mammal('dog').

And then overspecifies with circular logic:
mammal(X) :- (X='cat';X='dog'), animal(X).

The essence of what you need is simply:
bird('parrot').
bird('pigeon').

mammal('cat').
mammal('dog').

animal(X) :-
    mammal(X); bird(X).

This logic defines what creatures are birds or mammals using facts, then provides a rule that says if a creature is known to be a bird or a mammal, then it's an animal.

A: One solution to such problems is to simply enable your Prolog system's tabling mechanism.
For example, in SWI-Prolog (latest development version), if I simply add the following directives at the start of your program:
:- use_module(library(tabling)).

:- table animal/1.

Then I get for example:

?- animal(X).
false.

?- male(X).
false.

?- bird(X).
false.

So, in these cases, we still do not find any solution, but at least we get answers.


text:
Q: What is the advantage of multiple constructors in typescript? Let's say I have something like:
class MyClass {
    constructor(s: number);
    constructor(s: string);
    constructor(s: any) {

    }
}

What do those first 2 declarations buy me since the third one now allows anything to be passed in. Can the third (actual) one be made private? It looks like private is ignored on a constructor.

A: The implementation signature, as it's called, is already not visible. You don't have to do anything to make it 'private'. Whenever a function or constructor is overloaded, only the overloads are seen by callers.
var x = new MyClass({n: 3}); // This is an error.


text:
Q: How to count as week request to fill in at my order history Red column is the result I wanted to get which based on the quantity get the date I wanted.

A: Put it in B2:
=ARRAYFORMULA(IF(A2:A="",,SUMIF(H:H,A2:A,G:G)))

Alternative:
Put it in A2:
=QUERY(G:H,"select H,sum(G) where H is not null group by H label H '',sum(G) ''",1)

Reference:

*

*SUMIF

*QUERY function


text:
Q: SQL - Grouping by Last Day of Quarter I currently have a query running to average survey scores for agents. We use the date range of the LastDayOfTheQuarter and 180 days back to calculate these scores. I ran into an issue for this current quarter.
One of my agents hasn't received any surveys in 2020 which is causing the query to not pull the current lastdayofquarter and 180 days back of results.
The code I am using:
SELECT
Agent,
U.Position,
U.BranchDescription,
(ADDDATE(LastDayOfQuarter, -180)) AS MinDate,
(LastDayOfQuarter) AS MaxDate,
COUNT(DISTINCT Response ID) as SurveyCount,
AVG(CASE WHEN Question ID = Q1_2 THEN Answer Value END) AS EngagedScore,
AVG(CASE WHEN Question ID = Q1_3 THEN Answer Value END) AS KnowledgableScore,
AVG(CASE WHEN Question ID = Q1_6 THEN Answer Value END) AS ValuedScore
FROM qualtrics_responses
LEFT JOIN date D
ON (D.`Date`) = (DATE(`End Date`))
LEFT JOIN `users` U
ON U.`UserID` = `Agent ID`
WHERE `Agent` IS NOT NULL
AND DATE(`End Date`) <= (`LastDayOfQuarter`)
AND DATE(`End Date`) >= (ADDDATE(`LastDayOfQuarter`, -180))
GROUP BY  `Agent`,  (ADDDATE(`LastDayOfQuarter`, -180))

i know the issue is due to the way I am joining the dates and since he doesn't have a result in this current year, the end date to date join isn't grabbing the desired date range. I can't seem to come up with any alternatives. Any help is appreciated.

A: I make the assumption that table date in your query is a calendar table, that stores the starts and ends of the quarters (most likely with one row per date in the quarter).
If so, you can solve this problem by rearranging the joins: first cross join the users and the calendar table to generate all possible combinations, then bring in the surveys table with a left join:
SELECT
    U.UserID,
    U.Position,
    U.BranchDescription,
    D.LastDayOfQuarter - interval 180 day AS MinDate,
    D.LastDayOfQuarter AS MaxDate,
    COUNT(DISTINCT Q.ResponseID) as SurveyCount,
    AVG(CASE WHEN Q.QuestionID = 'Q1_2' THEN Q.Answer Value END) AS EngagedScore,
    AVG(CASE WHEN Q.QuestionID = 'Q1_3' THEN Q.Answer Value END) AS KnowledgableScore,
    AVG(CASE WHEN Q.QuestionID = 'Q1_6' THEN Q.Answer Value END) AS ValuedScore
FROM date D
CROSS JOIN users U
LEFT JOIN qualtrics_responses Q
    ON  Q.EndDate >= D.Date
    AND Q.EndDate < D.Date + interval 1 day
    AND U.UserID = Q.AgentID
    AND Q.Agent IS NOT NULL
GROUP BY
    U.UserID,
    U.Position,
    U.BranchDescription,
    D.LastDayOfQuarter

Notes:

*

*I adapted the date arithmetics - this assumes that you are using MySQL, as the syntax of the query suggests

*You should really qualify all the columns in the query, by prefixing them with the alias of the table they belong to; this makes the query so much easier to understand. I gave a tried at it, you might need to review that.

*All non-aggregated columns should appear in the group by clause (also see the comment from Eric); this is a a requirement in most databaseses, and good practice anywhere


text:
Q: When using requests.session to login www.researchgate.net, I got a "403 Forbidden", warning that "Your browser doesn't accept cookies. " I'm coding a web crawler for https://www.reseachgate.net with python. When I try to login using requests.Session, I got a "403 Forbidden" page, warning that "Your browser doesn't accept cookies. Cookies are required to use this site." How to solve this problem?
Here's my code:
import requests
from bs4 import BeautifulSoupter

headers = {
            'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0'
        }
session = requests.Session()

params = {'login': '######@std.uestc.edu.cn', 'password': '#######'}
s = session.post("https://www.researchgate.net/application.Login.html", data = params, headers = headers)
print s.cookies.get_dict()
print s.text
s = session.get("https://www.researchgate.net/home")
print BeautifulSoup(s.text).title

Here's what I got:

         403 Forbidden

Your browser doesn't accept cookies. Cookies are required to use this site.

A: It turns out that I missed some fields in my login form.
Here's my updated code:
import requests
from bs4 import BeautifulSoup

session = requests.Session()
loginpage = session.get("https://www.researchgate.net/application.Login.html")
request_token = BeautifulSoup(loginpage.text).form.find("input",{"name":"request_token"}).attrs["value"]
print request_token
params = {"request_token":request_token,
          "invalidPasswordCount":"0",
          'login': 'my_email',
          'password': 'my_password',
          "setLoginCookie":"yes"
          }
session.post("https://www.researchgate.net/application.Login.html", data = params)
s = session.get("https://www.researchgate.net/search.Search.html?type=researcher&query=zhang")
print BeautifulSoup(s.text).title

A: I would suggest you to use Scrapy.
Ref: http://doc.scrapy.org/en/latest/index.html
Here is a simple example,
from scrapy.contrib.spiders.init import InitSpider
from scrapy.http import Request, FormRequest

class MySpider(InitSpider):
    name = 'researchgatespider'
    allowed_domains = ['researchgate.net']
    login_page = 'http://www.researchgate.net/login'   # replace the valid URL

        def init_request(self):
         #This function is called before crawling starts.
        return Request(url=self.login_page, callback=self.login)

    def login(self, response):
        return FormRequest.from_response(response,
                    formdata={'name': 'userrname', 'password': 'password'},
                    callback=self.isValid_login)

    def isValid_login(self, response):
        if "XXXXXXX - term to check" in response.body:
            self.log("Successfully logged in")
            self.initialized()
        else:
            self.log("Wrong credentials")

    def parse_item(self, response):
           # write XPATH / any type of extraction here.

A: If You use Scrapy 1.0.4 you get the error:
ScrapyDeprecationWarning: Module scrapy.contrib.spiders.init is deprecated, use scrapy.spiders.init instead
  from scrapy.contrib.spiders.init import InitSpider
It can be corrected changing the first line
"from scrapy.contrib.spiders.init import InitSpider"
in
from scrapy.spiders.init import InitSpider
ResearchGate has changed the Login Page: now the correct url is
https://www.researchgate.net/application.Login.html
and has changed "login" with "e-mail" and any other thing in login page.
In any case I always get the usual error:
** [researchgatespider] DEBUG: Wrong credentials **
Can anyone help me ?


text:
Q: AS3: int used where a boolean value was expected I have three different buttons. When you click one of the buttons, it is supposed to activate the stageSelect function, which should then output the button's number.
But when I do that, I get the error in the title. What am I doing wrong here?
package {
    import flash.display.MovieClip;
    import flash.display.SimpleButton;
    import flash.events.MouseEvent;
    import flash.ui.Mouse;

    public class MenuScreen extends MovieClip {
        public function MenuScreen() {
            Mouse.show();
            selectGrass.addEventListener(MouseEvent.CLICK, stageSelect, 1);
            selectDirt.addEventListener(MouseEvent.CLICK, stageSelect, 2);
            selectGravel.addEventListener(MouseEvent.CLICK, stageSelect, 3);
        }

        public function stageSelect(stageID:Number) {
            trace(stageID);
        }
    }
}

A: this is because the third param for the method addEventListener is useCapture which requires a boolean saying that you wish to grab the event during the capture phase before bubbling.  You are calling
selectGrass.addEventListener( MouseEvent.CLICK, StageSelect, 1);

What you need to do instead is
selectGrass.addEventListener( MouseEvent.CLICK, grassSelected);
selectDirt.addEventListener( MouseEvent.CLICK, dirtSelected);

private function grassSelected(event:MouseEvent):void{
    // do grass stuff
}

private function dirtSelected(event:MouseEvent):void{
    // do dirt stuff
}


text:
Q: Put text and numbers in boxes Using FastReport , how can I put Text and Numbers from database in boxes like :
|_|_|_|_|_|_|_|_|_|_|

So "Sami" it becomes :

and the same for numbers too, I try to do it with TfrxLineView but I fail.

A: Take the easy way :

*

*Drop 4 TfrxMemoView component in your report (or as you need) like :

*

*In OnPreview event of your report, set your code for example:
procedure TForm1.frxReport1Preview(Sender: TObject);
var Str : WideString;   I : Integer;  Mem : TfrxMemoView;
begin
   Str := 'Sami';   // Or get it from query/table (database)

   // Find the TFrxMemoView Component and set in it the String you want
   for I := 1 to 4 do
     begin
       Mem := frxReport1.FindObject('M'+IntToStr(I)) as TfrxMemoView;
       Mem.Text := Str[I];
     end;
  end;

*The result will be :

Update :
You can also do it programmatically as :
var RT : TfrxBand;
    Mem : array [1..100] of TfrxMemoView ;
    i : Byte;
    Name : WideString;
begin
  // Find the band
  RT := frxReport1.FindObject('RT') as TfrxBand;
  // Set the String
  Name := 'DELPHI FAST REPORT';
  for I := 1 to Length(Name) do
    begin
      Mem[i] := TfrxMemoView.Create(RT);
      Mem[i].Text :=  Name[i];
      Mem[i].Font.Style := [fsBold];
      Mem[i].Frame.Width := 2;
      Mem[i].Height := 20;
      Mem[i].AutoWidth := False;
      Mem[i].HAlign := haCenter;
      Mem[i].Frame.Typ := [ftLeft , ftBottom , ftRight];
      Mem[i].Width := 20;
      if i =1 then
        Mem[i].Left := 0
          else
            Mem[i].Left := Mem[i-1].Left + 5 + 15;
    end;
  frxReport1.ShowReport();
end;

The result is :

A: There is no ready made control for displaying characters in boxes as you ask for. Therefore you need to paint this yourself on the canvas you choose.
Here's an example of how to do it in a TPaintBox, pbText is here a string field of the demo form, and holds the text to be displayed in the paint box:
procedure TForm17.PaintBox1Paint(Sender: TObject);var
  i, n, x, y: integer;
  siz: TSize;
  pb: TPaintBox;
begin
  n := 10;  // character cells
  pb := Sender as TPaintBox;
  siz := pb.Canvas.TextExtent('Wp');

  // draw character cells
  x := 4; y := siz.cy+2;
  for i := 0 to n do
  begin
    pb.Canvas.MoveTo(i * siz.cx + x, 0);
    pb.Canvas.LineTo(i * siz.cx + x, y);
  end;
  pb.Canvas.MoveTo(x, y);
  pb.Canvas.LineTo(n * siz.cx + 4, y);

  // draw characters horizontally in center of box
  for i := 1 to Length(pbText) do
  begin
    x := (4 + (i-1)*siz.cx + (siz.cx - pb.Canvas.TextWidth(pbText[i])) div 2);
    y := 0;
    pb.Canvas.TextOut(x, y, UpperCase(pbText[i])); // force upcase
//    pb.Canvas.TextOut(x, y, pbText[i]);            // or don't
  end;
end;

And to use it
procedure TForm17.Button1Click(Sender: TObject);
begin
  pbText := 'Sami Wiim';
  PaintBox1.Invalidate;
end;

A: Very simple and and a little ugly method to do this.

*

*In Fast Report:

-place a Text object like this : [TEST_STR];
-set text style to Underline;
2.In Delphi
-make function to convert a string to formated string.
For example :
input: SAMI
output:  | S | A | M | I |
-in OnGetValue event of FastReport call this function:
procedure TMainForm.frxReport1GetValue(const VarName: string;
  var Value: Variant);
begin
  if VarName = 'TEST_STR' then Value :=  MyFunctionToFormatStr('SAMI');

end;

That's all.
The result look like :


text:
Q: Neural networks: No solutions for test data possible? So there are two ways of teaching a neural network as far as I am aware of.

*

*You supply the AI with test data and the correct solution to the problem. After some time the network will be able to get the answers right.
Example: Hand-writing recognition. You supply the network with images and tell it what numbers they represent.

*You let the network figure solutions out by itself. The AI performs an action and gets a score. The AI will try to get a higher score every time.
Example: Path finding. You make the AI go and tell it how well it did after it crashes into a wall.
But is there a third way?
For example if you want to make a Chess AI, the second approach is the more suitable one, but how do you rate the actions of the AI? It is really hard to tell if a player does well early in the game and the outcome heavily depends on the action of its opponent.
What I thought about was maybe putting the AI in certain situations of the game, for example an uneven trade and repeating it until the AI understands that it's chess figure is worth more.
Are there other solutions or are Chess AIs not even built on neural networks?

A: The first approach is called supervised learning, and the second is called reinforcement learning. There are two ways you can use a neural network with reinforcement learning for chess: as a policy network or as a value network:

*

*a policy network would decide which move to play,

*whereas a value network would just evaluate the utility of a board position and could be used with minimax or MCTS (Monte-Carlo tree search).

Training a neural network using reinforcement learning is straight-forward (if slow) — if a move comes from a winning game, it's good, if it comes from a losing game, it's bad.
Read up on AlphaGo if you are interested. It recently defeated the best human player at a more difficult game than chess. It uses both kinds of neural networks, policy and value, as well as MCTS.

A: Neural Networks are good at solving a particular sort of problem.  They are basically mechanisms that map particular source patters to particular target patterns.  When given an input set of nodes that are either "on" or "off" they return an output set of nodes that are either "on" or "off".  (Usually using some sort of threshold value that is specified as "on".
This maps very well towards tasks like text recognition.  You give the neural network in input pattern (a bitmap) and it gives an output (some sort of binary representation of the letter.)
To train a network, you generally give it a set of source patterns and the expected targets.  The training methods generally start at the target and push backwards, modifying links to make the network more likely to generate the expected target.
After training, you can send the network inputs it wasn't trained for and it will produce an output.  If everything goes well, this should be meaningful.  For example, if you've trained it to output 'A' when given bitmaps with the letter rendered in a number of fonts, it should output 'A' when shown something in a font that it has not been trained on.
So there aren't really two ways of training networks.  The whole point of using a neural network is that it can respond to stuff you haven't trained it on.  If you know all the mappings of inputs to outputs beforehand, a neural network is not the best option.
In regards to chess, the game is just not a task suitable for neural networks.  Given a source board, you don't really have an end pattern that you can train it on.  You can't really give it the "best" target as for a given chess position, what move is "best" is almost always a matter of debate.  You might be able to use a neural network to score boards (i.e. mapping a board position to a numeric score), but you'd still use the traditional minimax to play the actual game.


text:
Q: How to use a matrix with a circle as a mask? I'm new in MATLAB and using it for some medical analysis. I have a matrix which contains a circular shape in it. Here is a sample:
   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   1   0   0   0   0   0
   0   0   0   1   0   1   1   0   0   0
   0   0   1   0   0   0   0   1   0   0
   0   1   0   0   0   0   0   1   0   0
   0   0   0   0   0   0   0   0   0   0
   0   0   1   1   0   1   1   0   0   0
   0   0   0   0   1   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0
   0   0   0   0   0   0   0   0   0   0

This matrix has been computed by this line:
egslbr= edge(slbr,'log');

Where slbr is my image. By merging the egslbr with my slbr I get the image bellow.

I want to cancel all the color pixel outside the greenish circle. Is there any way to do this?

A: You should be able to create a mask from your circle (assuming it's a complete circle -- the sample matrix you gave has a gap in it which makes this much more difficult, but I'm going to assume that was a mistake). Here's a simple way of doing it:
mask = ~cumsum(egslbr) | ~cumsum(egslbr,'reverse');
slbr(mask) = 0;

This should set every pixel outside the circle (not including the edge of the circle though) to zero.


text:
Q: Replacing Ubuntu with Kubuntu I had used Ubuntu for several years, and lately I got an error I wasn't able to access the OS at all, tried all solutions given here to solve the problem, but I wasn't lucky at all.
So I had to make the drive as external one, and tried to get the info, but also it wasn't accessible. Now I end up by formatting it, and Install Kubuntu (they mentioned it's light weight than Ubuntu), and what I have now is a laptop with hard disk partitioned into Kubuntu and something else, that didn't get the point behind shown in the image:

So my questions now:

*

*what I have to do with this red error give( Could not enter folder /boot/efi)

*Is there anyway to get back my info after I formatted it! (I checked testdesk) but badly I wasn't able to realized how to continue with it (if I may get a full guidance or something better)

*My hard drive Is 1TB, and when installing Kubuntu it was recommended that I don't use it full, so now, my data are in the 462 GB Hard Drive, in what I may use the New Volume, and does it affect if I add files in it, would they be accessed normally?

Sorry if my questions are weird or silly.
Thanks for helping and assisting.
Edit:

A: If I do understand correctly, your Kubuntu installation works; you can open terminal, file manager, and firefox. If that is the case:
Right click on all of the choices under Devices section and see where they are mounted.
Use sudo apt install krusader to install a file manager named krusader. Type sudo krusader or
[Desktop Entry]
Comment[en_US]=
Comment=
Comment[en_US]=
Exec=sudo krusader
GenericName[en_US]=
GenericName=
GenericName[en_US]=
Icon=krusader_blue
MimeType=
Name=krusaderasroot
Path=
StartupNotify=true
Terminal=true
TerminalOptions=
Type=Application
X-DBUS-ServiceName=
X-DBUS-StartupType=
X-KDE-SubstituteUID=false
X-KDE-Username=

save what is above (Change the language options as you wish) as a file (with any name, here it is krusaderasroot, no extension) on desktop. Right-click on it and select 'Is an executable'. Click on it, and when it asks, enter your password.
Go to where all the partitions in the devices section are mounted, you will be able to perform any operation you want, including changing owner if necessary (Right click-Permissions -- if necessary, advanced permissions).
If you do not need it, do not change owners; most linux directories needs to be only owned by root. This just helps you, to see what is in a folder or partition, owned by root.
EFI is your boot partition. If you are booting in successfully, you do not need to mess with it. If you want to hide it, right click on it, and choose 'Hide' or any option you desire.
I suggest you do not install krusader to see what is in EFI partition, it is a boot partition you do not need to mess with (in your case). What you are seeing is not an error. You are not root when you are in dolphin file manager.
462 is your Kubuntu partition.
And I cannot see from here of course, but New Volume is probably an empty data partition.
If you want to save any data from it, do not write anything on any partition, use a recovery program on another computer by putting your disk as an external disk, or boot from a recovery ISO from USB and see what you can recover and what you want to recover, and of course save what you want to recover on another disk, not onto this one.
For recovery program options, there is not a single answer, a small research and trying 2-3 different ones will help.
Some of recovery programs have their ISOs to boot from, if they do not; you can boot from Kubuntu Install ISO, select try Kubuntu Option, and install the program to there.
For booting from ISOs, you can use a single or multiboot USB Option.
Reminding you that, trying to see what you can recover, and depends on how much data you are going to save can take many hours.

A: I don't know, if this helps you as an answer, but I will give it a try.

*

*Switch to command line, if you try these things. It gives you a lot more information. Just start the terminal application. In case you are not familiar with it, the most important commands are: cd <path> = change directory, cd . = change to current directory (you don't need it, just for understanding), cd .. change to parent directory, absolute paths start with /, relative ones with <child directory> or ./<child directory>, ls lists all files in a folder, ll all files with details.

*Start clonezilla from a live-cd and make a backup of your system. It is rather self-explaining, just follow the instructions without understanding too much. Alternatively, you can use rsync to backup your data (see below).

*This looks like a access rights problem. To display the access rights, type ll. You need to be sure that all files have to correct owner. Look up, what it has to be and change it with chown [-R] <user>:<group> <file/folder>, if needed. If it is part of the system, it should be root:root (user root : group root). Most files have the access rights drwxr-xr-x. owner can read, write, execute; group members read and execute; all others read and execute; Accessing a directory counts as execution. You can edit these with chmod 755 <file>. 755 sets rwxr-xr-x, 644 sets rw-r--r--, it is binary. You can use it differently, just look it up.

*Start ubuntu in recovery mode. When the blue screen with the prompt is coming, start the network drivers. Then switch to root shell. There you should be able to access everything and repair everything. Here you can backup your data via rsync to an external device. i.e. # rsync -ravutz /home /media/yourName/backupDirectory. You can try to repair your installation in the root shell by

i.e.
sudo apt update
sudo apt reinstall ubuntu-desktop


text:
Q: Plotly: How to add dropdown menu for every subplot? I need to create two subplots with a dropdown menu and title for each graph. (side-by-side comparison). In addition, I 'd like to have a shared y-axis.
As for now, I have only one dropdown menu that change both graphs.
The code is following: (note that a df consists of 2 columns and datetimeindex).

    import plotly.offline as py
    import plotly.graph_objs as go
    from plotly.offline import init_notebook_mode, iplot, plot
    from plotly import tools

    labels = ["Vol", "R"]

    fig = tools.make_subplots(rows=1, cols=2)

    trace1 = go.Scatter(x=df.index,
                             y=df['Stock1'].rolling(window=12).std(),
                             mode='lines'
                            )
    trace2 = go.Scatter(x=df.index,
                             y=df['Stock1'],
                             mode='lines'
                            )

    fig.append_trace(trace1, 1, 1)
    fig.append_trace(trace2, 1, 1)

    trace1 = go.Scatter(x=df.index,
                             y=df['Stock2'].rolling(window=12).std(),
                             mode='lines'
                            )
    trace2 = go.Scatter(x=df.index,
                             y=df['Stock2'],
                             mode='lines'
                            )
    fig.append_trace(trace1, 1, 2)
    fig.append_trace(trace2, 1, 2)

    # Create buttons for drop down menu
    buttons = []
    for i, label in enumerate(labels):
        visibility = [i==j for j in range(len(labels))]
        button = dict(
                     label =  label,
                     method = 'update',
                     args = [{'visible': visibility},
                         {'title': label}])
        buttons.append(button)

    updatemenus = list([
        dict(active=-1,
             x=-0.15,
             buttons=buttons
        )
    ])

    fig['layout']['title'] = 'Title'
    fig['layout']['showlegend'] = False
    fig['layout']['updatemenus'] = updatemenus

    iplot(fig, filename='dropdown')

A: According to empet's helpful answer in the Plotly forum, the important thing to know is that the visible key has length equal to the total number of traces in fig.data.
In your case, you have four traces that correspond to Stock 1 (Vol), Stock 1 (R), Stock 2 (Vol) and Stock 2 (R) which is the order in which you added these traces. So we can create 4 buttons to toggle the visibility feature of each trace and pass them as a list to the updatemenus dictionary.
import numpy as np
import pandas as pd

import plotly.offline as py
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, iplot, plot
from plotly import tools

## recreate some random data
np.random.seed(42)
df = pd.DataFrame(data=np.random.randint(0,100,(365,2)), columns=['Stock1','Stock2'], index=pd.date_range(start='1/1/2019', end='12/31/2019'))

labels = ["Vol", "R"]

fig = tools.make_subplots(rows=1, cols=2)

trace1 = go.Scatter(x=df.index,
                         y=df['Stock1'].rolling(window=12).std(),
                         mode='lines'
                        )
trace2 = go.Scatter(x=df.index,
                         y=df['Stock1'],
                         mode='lines'
                        )

fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 1, 1)

trace1 = go.Scatter(x=df.index,
                         y=df['Stock2'].rolling(window=12).std(),
                         mode='lines'
                        )
trace2 = go.Scatter(x=df.index,
                         y=df['Stock2'],
                         mode='lines'
                        )
fig.append_trace(trace1, 1, 2)
fig.append_trace(trace2, 1, 2)

## visible key for traces are in the order you append them

button1 = dict(method='update',
               args=[{"visible": [True, False, False, False] }],
               label="Stock 1, Vol" )
button2 = dict(method='update',
               args=[{"visible": [False, True, False, False] }],
               label="Stock 1, R" )
button3 = dict(method='update',
               args=[{"visible": [False, False, True, False] }],
               label="Stock 2, Vol" )
button4 = dict(method='update',
               args=[{"visible": [False, False, False, True] }],
               label="Stock 2, R" )

updatemenus = list([
    dict(active=-1,
         x=-0.15,
         buttons=[button1, button2, button3, button4]
    )
])

fig['layout']['title'] = 'Title'
fig['layout']['showlegend'] = False
fig['layout']['updatemenus'] = updatemenus

iplot(fig, filename='dropdown')


text:
Q: Reinstalling Windows 10, now getting "An operating system wasn't found. Try disconnecting any drives that don't contain an operating system" Today I decided to add another SSD to my system and reinstall Windows 10 on that drive. I created the Windows 10 installation media (disc) and then inserted it, restarted my computer and then went through the setup. I formatted the other two drives that I had in there as well. So it was a clean install. I had an issue with the format, but I solved that. Then I began the installation process, and it got to 93% of the 2nd stage of the installation process. It stayed like that for three hours, so I turned the computer off. Then when I rebooted to try again, I was greeted with the message "An operating system wasn't found. Try disconnecting any drives that don't contain an operating system. Press Ctrl+Alt+Delete to restart"
I disconnected the drives and then went to press Ctrl+Alt+Delete... my keyboard doesn't work. I have a Corsair K95 RGB, the lights on the keyboard are on, but nothing happens when I type.
I'm currently stuck with a paperweight. Please can someone give me some ideas.
Thank you.

A: Since Windows only got to 93 percent thats why the operating system wasn't found I would press and hold the power to shut down the computer reinsert the
W10 disk and start the installation over ... if that doesn't work I recommend killdisk or Dban to wipe your drives bits to 0's and restarting the installation process... Your keyboard might not work due to lack of drivers... during the installation process it might have never installed the generic io drivers
hope this helps... test your keyboard in BIOS this should work :)


text:
Q: Javascript reset loop i have a little problem with my javascript code,
i build a function that add filed by a qty that the user choose,
here is the function
$(document).ready(function() {
  $('.qty').change(function(){
     for (var i=0;i<$('.qty').val();i++){
       $('.append').append('<select name="data[]"><option value="one">1</option></select>');
     }
  });
});

AND the html code is:
<select name="qty" class="qty">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
</select>
<div class="append">

</div>

when i pick a value in the qty, lets say 3, it open me up 3 select fields, but when i change the selection to 2, it adds me 2, so i have 5 select fileds, how do i reset? if i pick 1 it will open me 1 and if i change it to 2 it will change and open me 2 not 3 like it is now.

A: Try:
$(document).ready(function() {
  $('.qty').change(function(){
    var html=''
     for (var i=0;i< parseInt($('.qty').val());i++){
       html += '<select name="data[]"><option value="one">1</option></select>';
     }
     $('.append').html(html);
  });
});

A: Just clear the .append div contents prior to appending, you can clear it with .html(''), so you just need to replace your following line:
$('.append').append('<select name="data[]"><option value="one">1</option></select>');

for this one:
$('.append').html('').append('<select name="data[]"><option value="one">1</option></select>');

A: Use .html
$(document).ready(function() {
  $('.qty').change(function(){
      var k=""
      for (var i=0;i<$('.qty').val();i++){
          k += '<select name="data[]"><option value="one">1</option></select>';
     }
     $('.append').html(k);
  });
});

here is a working jsfiddle http://jsfiddle.net/P2F9x/

A: You could add one line to empty the append div before the loop
$('.append').empty();

so it would be:
$(document).ready(function() {
  $('.qty').change(function(){
     $('.append').empty();
     for (var i=0;i<$('.qty').val();i++){
       $('.append').append('<select name="data[]"><option value="one">1</option></select>');
     }
  });
});

Fiddle:
http://jsfiddle.net/

A: Instead of:
$('.append').append('<select name="data[]"><option value="one">1</option></select>');

Use
$('.append').html('<select name="data[]"><option value="one">1</option></select>');

I think that is what is causing it to append the additional fields.

A: Use this to reset html:
$('.append').html('');

like:
$(document).ready(function() {
  $('.qty').change(function(){
    $('.append').html('');
     for (var i=0;i<$('.qty').val();i++){
       $('.append').append('<select name="data[]"><option value="one">1</option></select>');
     }
  });
});

A: To preserve any selections the user have already made you could change the structue somewhat
$(document).ready(function() {
  $('.qty').change(function(){
     var count = $(.append).find("select").length,
         qty = $('.qty').val(),
         i,
         html = $('.append').html();
     //append any needed elements
     if(count < qty) {
       for (i=count;i < qty; i += 1){
         html += '<select name="data[]"><option value="one">1</option></select>';
       }
       $('.append').html(html);
     }
     //remove any excess elements
     for(;count<$(.append).find("select").length;
          $(.append).find("select:last").remove()){}
  });
});


text:
Q: odoo 11, How to generate report in xls format? I would like to create a report in xls format in odoo11. I have a set of results in python,I want to print the report in excel sheet.

A: *

*TRY BELOW CODE

*Python code:-
from odoo import models
class PartnerXlsx(models.AbstractModel):
    _name = 'report.report_xlsx.partner_xlsx'
    _inherit = 'report.report_xlsx.abstract'

def generate_xlsx_report(self, workbook, data, partners):
    for obj in partners:
        sheet = workbook.add_worksheet('Report')
        bold = workbook.add_format({'bold': True})
        sheet.write(0, 0, obj.name, bold)

*XML code:-
<report
    id="partner_xlsx"
    model="res.partner"
    string="Print to XLSX"
    report_type="xlsx"
    name="report_xlsx.partner_xlsx"
    file="res_partner"
    attachment_use="False"
/>


text:
Q: Passing the atrribute information along to LLVM I've created a new attribute in clang using the steps detailed in
http://clang.llvm.org/docs/InternalsManual.html
What's the best way
of passing the atrribute information along to LLVM?


text:
Q: HelloRestAPI showing 404 (created with IntelliJ Spring Initializr) I am totally frustrated about that beginnerproblem
Simply startet a fresh SpringBoot Project with JDK18 and UpToDate IntelliJ.
Inserted no more Code that this Controller:
package com.example.springboot;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }

}

calling: curl localhost:8080
and get an unusual 404:
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

Searching for that response pointing me to very old threads talking about views jsp and web.xml
But I dont want to have nasty renderings. I want pure REST-Controller.
Any suggestion to point me to the correct issue or even better to a solution?

A: The spring-boot-starter-web dependency is required in your pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

When you create a new project with IntelliJ it asks for the dependencies you want to include. Here you need to select "Spring Web":


text:
Q: How to get notified about imageWithContentsOfFile: completion? I load a huge-huge image with imageWithContentsOfFile:, so I have to set up an activityIndicator during the process.
Is there any way/any delegate callback I can use to be informed about the end of this loading process?

A: imageWithContentsOfFile is synchronous.
You could start an activity indicator, load your big image into memory in a background thread and then go back to the main thread and stop the indicator.
- (void)loadBigImage {
    [activityIndicator startAnimating];
    [self performSelectorInBackground:@selector(loadBigImageInBackground) withObject:nil];
}

- (void)loadBigImageInBackground {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    UIImage *img = [UIImage imageWithContentsOfFile:@"..."];
    [self performSelectorOnMainThread:@selector(bigImageLoaded:) withObject:img waitUntilDone:NO];
    [pool release];
}

- (void)bigImageLoaded:(UIImage *)img {
    [activityIndicator stopAnimating];
    // do stuff
}

A: Short answer: Nope. sorry!
Long answer :
You could open the file in a background process (an NSOperation?) bit by bit using C style methods i.e. fopen, fread etc) and fire notifications back to the main thread during the load. Then create the image and fire a notification that the image is ready?

A: If you want to have a delegate & be informed of the progress of the load, you can use an NSURLConnection instead of the synchronous imageWithContentsOfFile.
There's an example of this in the Apple URL Loading System Programming Guide
Your NSURLConnection delegate didReceiveData: method could append the incoming data to an NSData object, then you would use UIImage imageWithData: to create them image once everything's downloaded.
This gives you the most flexibility/control over monitoring the progress of the load; although if all you're trying to do is avoid hanging the UI while the image downloads, simply using imageWithContentsOfFile in a background thread may be easier.