text:
Q: Finding values using .text() in separate tr's in table using jQuery What I am trying to do is separate the three table rows in this table, and have jQuery treat them individually to find the separate values (like price and SKU - you'll see in the fiddle link below).
Because the table is generated dynamically and all the classes are the same for each product, I am trying to define each tr as a separate variant, and then search through them to get the values using .text().
Here's a bit of code (jsfiddle link below):
jQuery:
var firstprice = $('#checkout .orderitems table.wizrtable tbody tr td.priceeach').text().replace(/\u00A3/g, '');
//price of a single product in checkout

var amountofproducts = $('#checkout .wizrtable tbody tr').length;
//amount of table rows in the actual checkout table structure

$(document).ready(function () {
    if (+amountofproducts >= 4 && +amountofproducts <= 8) {
        // Define unit price
        var firstrow = $('.wizrtable').closest('table').children('tr:first');
        var firstprice = $(firstrow()('#checkout .orderitems table.wizrtable tbody tr td.priceeach')).text().replace(/\u00A3/g, '');
        var secondrow = $('.wizrtable').closest('table').children('tr:second');
        var secondprice = $(secondrow()('#checkout .orderitems table.wizrtable tbody tr td.priceeach')).text().replace(/\u00A3/g, '');
        var thirdrow = $('.wizrtable').closest('table').children('tr:third');
        var thirdprice = $(thirdrow()('#checkout .orderitems table.wizrtable tbody tr td.priceeach')).text().replace(/\u00A3/g, '');
        // END: Define unit price

        // Define item IDs for each product
        var firstSKU = $(firstrow()('#checkout .orderitems table.wizrtable tbody .name .sku')).text().replace("Product Code: ", "");
        var secondSKU = $(secondrow()('#checkout .orderitems table.wizrtable tbody .name .sku')).text().replace("Product Code: ", "");
        var thirdSKU = $(thirdrow()('#checkout .orderitems table.wizrtable tbody .name .sku')).text().replace("Product Code: ", "");
        // END: Define item IDs for each product

        // Inject html div with result
        var Firstprodprice = jQuery("FirstprodPrice").text(firstprice);
    }
});

JS Fiddle Link:
http://jsfiddle.net/hslincoln/7HXBQ/10/
Any pointers?

A: There appear some useful divs in your HTML that avoid the need for regexs.
This isn't tested, but something like ...
$('#wizrtable tr').each( function( index,element)  {
   var sku = $(element).find( 'div[title="pid"]').text();
   var qty = $(element).find( 'div[title="qty"]').text();
   var price = $(element).find( 'div[title="tv"]').text();
});

A: Your jsfiddle was more or less correct. I've updated it: http://jsfiddle.net/Ht5nm/2/.
Some corrections:
var secondrow = $('.wizrtable').children('tr:second');

The second pseudo selector does not exist. use :nth-child(n). Also .children() only works on immediate children, so you still new the tbody in there... My bad.
var secondrow = $('.wizrtable tbody').children('tr:nth-child(2)');

Here I have no idea what the + in front of the variables was for.
if(+amountofproducts >= 4 && +amountofproducts <= 8) however the variable depends on how many table rows you have, therefore the code inside the if statement would not run in your jsfiddle.
Also the code in your jsfiddle needed a #checkout to get some expected code to run, which I added into my jsfiddle.
The way you are going about this is not really going to be scalable to many table rows. For example you want to dynamically deal with rows instead of using firstrow secondrow thirdrow etc.
var Firstprodprice = jQuery("FirstprodPrice").text(firstprice);

This does not need to be assigned to a variable, as well the element with the class 'Firstprodprice' does not have a capital P in price. Therefore this line would not do anything.

A: Apart from the output, this removes the need to work out how many products there are in the table and scrapes the data for the entire table....
$(document).ready(function () {
// Define unit price
var tbody = $('.wizrtable tbody');
var prices = $(tbody).find('.priceeach');
var skus = $(tbody).find('.sku');
var quants = $(tbody).find('.quantity');
var product = [];

$(prices).each(function (idx) {
    product[idx] = {
        price: $(this).text().replace(/\u00A3/g, '')
    }
});
// END: Define unit price

// Define item IDs for each product
$(skus).each(function (idx) {
    product[idx].sku = $(this).text().replace("Product Code:", "");
});

$(quants).each(function (idx) {
    product[idx].qty = $(this).text();
});
// END: Define item IDs for each product

// Inject html div with result
// 1
$(".Firstprodprice").text(product[0].price);
$(".FirstSKU").text(product[0].sku);
$(".FirstQTY").text(product[0].qty);
// 2
$(".Secondprodprice").text(product[1].price);
$(".SecondSKU").text(product[1].sku);
$(".SecondQTY").text(product[1].qty);
// 3
$(".Thirdprodprice").text(product[2].price);
$(".ThirdSKU").text(product[2].sku);
$(".ThirdQTY").text(product[2].price);
});


text:
Q: Finding nested array objects with mongoose I have a user collection like this
{
  "_id": {
    "$oid": "62fe22f5d37c317701922d66"
  },
  "name": "Fahim Faisal",
  "email": "fahim.faisal.abir@gmail.cc",
  "password": "$2a$12$bkjeD.GesX4f7BNVF7C0CuKkkTyQA19kv6SAWuhObmPlAB11Tz9dy",
  "notes": [],
  "folders": [
    {
      "_id": {
        "$oid": "62fe22f5d37c317701922d67"
      },
      "name": "My Notes",
      "notes": []
    },
    {
      "_id": {
        "$oid": "62fe22f5d37c317701922d68"
      },
      "name": "Todos",
      "notes": []
    },
  ],
  "__v": 0
}

I want to check if an exact item in folders exists or not.
What I have tried so far
User.findOne(
    { _id: req.userId },
    {
        folders: {
            $elemMatch: {
                _id,
            },
        },
    },
    (err, system) => {
        if (err) {
            console.log(err);
        } else {
            console.log(system);
        }
    }
);

It doesn't return the exact item. It returns this
{
  _id: new ObjectId("62faf0c424411076eb9b80e6"),
  folders: [
    {
      _id: new ObjectId("6302110a230f9123c1110273"),
      name: 'My Notes',
      notes: []
    },
    {
      _id: new ObjectId("6302110a230f9123c1110274"),
      name: 'Todos',
      notes: []
    },
    {
      _id: new ObjectId("6302110a230f9123c1110275"),
      name: 'Projects',
      notes: []
    },
    {
      _id: new ObjectId("6302110a230f9123c1110276"),
      name: 'Journals',
      notes: []
    },
    {
      _id: new ObjectId("6302110a230f9123c1110277"),
      name: 'Reading list',
      notes: []
    }
  ]
}

What should I do to get the exact item in the folders array exists or not?

A: You should specify an Id in the elemMatch. For example something like this
User.findOne(
    { _id: req.userId },
    {
        folders: {
            $elemMatch: {
                _id:ObjectId('String Id'),
            },
        },
    },
    (err, system) => {
        if (err) {
            console.log(err);
        } else {
            console.log(system);
        }
    }
);

A: Add the $elemMatch filter for folders in the first object parameter, and with $ (projection) to limit and return the first (matched) item of folders array.
Assume that i_d is ObjectId type.
User.findOne(
    {
        _id: req.userId,
        folders: {
            $elemMatch: {
                _id: _id
            }
       }
    },
    {
        "folders.$": 1
    },
    (err, system) => {
        if (err) {
            console.log(err);
        } else {
            console.log(system);
        }
    }
);

Demo @ MongoPlayground

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как можно модифицировать код (Пайтон) Изучала Пайтон (я новичок, буквально неделю назад начала изучение) и наткнулась на такую интересную задачку:
У нас есть торговый автомат с фруктами, у каждого фрукта свой номер начиная с 0.
Нужно написать программу, которая возьмет число n в качестве ввода от покупателя и выдаст фрукт, который соответствует данному числу
Вот список : fruits = ["apple", "cherry", "banana", "kiwi", "lemon", "pear", "peach", "avocado"]
Написала я в общем такой код:
fruits = ["apple", "cherry", "banana", "kiwi", "lemon", "pear", "peach", "avocado"]
num = str((input)("ВВедите номер продукта: "))
if int(num) > 7 and int(num) < 20:
    a = int(num) % 10
    print(fruits[1])
    print(fruits[a])
elif len((num)) > 1 and int(num) < 10:
    a = int(num)
    print(fruits[0])
    print(fruits[a])
else:
    print(fruits[int(num)])

Итог: Код работает исправно, на пример если я впишу "02", то он мне выдаст apple и banana, как и должно быть. И так двухзначные цифры работаю вплоть до того момента, пока они не станут больше 20
Вопрос: Можно ли как-то модифицировать данный код? Просто по моему, он получился больно длинным, да мне и самой интересно послушать мнение сенпаев)

A: fruits = ["apple", "cherry", "banana", "kiwi", "lemon", "pear", "peach", "avocado"]

for i in input('Enter code:'):
    try:
        print(fruits[int(i)])
    except:
        print('Wrong code!!!')

В переменной i в цикле будет по одной букве из пользовательского ввода.
В блоке try питон пытается преобразовать букву к целому числу и выдать фрукт по номеру.
Если выпадает исключение - выполняется блок except


text:
Q: How to generate logs or print something during model fit in python3 I am scheduling my Jupyter Lab notebook which has cluster algorithm.. The job fails if I do not print or log something. ( This is how it is designed).
Code:
import hdbscan
from sklearn.datasets import make_blobs

data, _ = make_blobs(1000000)

clusterer = hdbscan.HDBSCAN(min_cluster_size=100)
cluster_model = clusterer.fit(data)

The line clusterer.fit(data) takes around 7-8 hrs for big data-set.
How can I print or log something at the time of fitting so that Kernel doesn't become ideal?

A: I'm not sure if I understand this correctly, but if you mean that the job gets killed by some "supervisor" if it doesn't print anything for too long, you could just start a separate threading.Thread or multiprocessing.Process that does nothing but print stuff until the fit is complete:
from time import sleep
from multiprocessing import Process

def print_target():
  while True:
    print("fit still running...")
    sleep(60)

# your code before fit...

proc = Process(target=print_target)
proc.start()

cluster_model = clusterer.fit(data)
proc.kill()

The example uses a Process instead of a Thread because the former are easier to kill (Thread doesn't have a kill() method like Process has, so you'd have to use a threading.Queue or threading.Event to communicate to the thread that you want it to stop running).


text:
Q: Updating and Resolving Comments in Google Sheet I would like to update/resolve comments on google spreadsheets using a service account. Currently following the GDrive V3 API guide;
The API explorer on the page works well but I am unable to replicate it on Python.
GET and LIST methods work fine but PATCH keeps returning the old content and wouldn't update.
Heres my code:
from googleapiclient.discovery import build
from google.oauth2 import service_account

credentials_file = './.config/gspread/service_account.json'
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive.appdata']
credentials = service_account.Credentials.from_service_account_file(credentials_file, scopes=scope)
service = build('drive', 'v3', credentials = credentials)
service.comments().update(commentId=<<commentId>>, fileId=<<fileId>>, fields='content', body={'content': 'new comment', 'resolved': True}).execute()

>>> returns {'content': 'old comment'}

Any idea what's wrong? Appreciate your help!

A: As suggested by Mateo, patching of comments works when using the OAuth 2.0 Client Credentials (Secret key file)


text:
Q: String concatenation of two pandas columns I have a following DataFrame:
from pandas import *
df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})

It looks like this:
    bar foo
0    1   a
1    2   b
2    3   c

Now I want to have something like:
     bar
0    1 is a
1    2 is b
2    3 is c

How can I achieve this?
I tried the following:
df['foo'] = '%s is %s' % (df['bar'], df['foo'])

but it gives me a wrong result:
>>>print df.ix[0]

bar                                                    a
foo    0    a
1    b
2    c
Name: bar is 0    1
1    2
2
Name: 0

Sorry for a dumb question, but this one pandas: combine two columns in a DataFrame wasn't helpful for me.

A: series.str.cat is the most flexible way to approach this problem:
For  df = pd.DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})
df.foo.str.cat(df.bar.astype(str), sep=' is ')

>>>  0    a is 1
     1    b is 2
     2    c is 3
     Name: foo, dtype: object

OR
df.bar.astype(str).str.cat(df.foo, sep=' is ')

>>>  0    1 is a
     1    2 is b
     2    3 is c
     Name: bar, dtype: object

Unlike .join() (which is for joining list contained in a single Series), this method is for joining 2 Series together. It also allows you to ignore or replace NaN values as desired.

A: The problem in your code is that you want to apply the operation on every row. The way you've written it though takes the whole 'bar' and 'foo' columns, converts them to strings and gives you back one big string. You can write it like:
df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)

It's longer than the other answer but is more generic (can be used with values that are not strings).

A: @DanielVelkov answer is the proper one BUT
using string literals is faster:
# Daniel's
%timeit df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
## 963 µs ± 157 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

# String literals - python 3
%timeit df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
## 849 µs ± 4.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

A: df['bar'] = df.bar.map(str) + " is " + df.foo

A: This question has already been answered, but I believe it would be good to throw some useful methods not previously discussed into the mix, and compare all methods proposed thus far in terms of performance.
Here are some useful solutions to this problem, in increasing order of performance.

DataFrame.agg
This is a simple str.format-based approach.
df['baz'] = df.agg('{0[bar]} is {0[foo]}'.format, axis=1)
df
  foo  bar     baz
0   a    1  1 is a
1   b    2  2 is b
2   c    3  3 is c

You can also use f-string formatting here:
df['baz'] = df.agg(lambda x: f"{x['bar']} is {x['foo']}", axis=1)
df
  foo  bar     baz
0   a    1  1 is a
1   b    2  2 is b
2   c    3  3 is c

char.array-based Concatenation
Convert the columns to concatenate as chararrays, then add them together.
a = np.char.array(df['bar'].values)
b = np.char.array(df['foo'].values)

df['baz'] = (a + b' is ' + b).astype(str)
df
  foo  bar     baz
0   a    1  1 is a
1   b    2  2 is b
2   c    3  3 is c

List Comprehension with zip
I cannot overstate how underrated list comprehensions are in pandas.
df['baz'] = [str(x) + ' is ' + y for x, y in zip(df['bar'], df['foo'])]

Alternatively, using str.join to concat (will also scale better):
df['baz'] = [
    ' '.join([str(x), 'is', y]) for x, y in zip(df['bar'], df['foo'])]

df
  foo  bar     baz
0   a    1  1 is a
1   b    2  2 is b
2   c    3  3 is c

List comprehensions excel in string manipulation, because string operations are inherently hard to vectorize, and most pandas "vectorised" functions are basically wrappers around loops. I have written extensively about this topic in For loops with pandas - When should I care?. In general, if you don't have to worry about index alignment, use a list comprehension when dealing with string and regex operations.
The list comp above by default does not handle NaNs. However, you could always write a function wrapping a try-except if you needed to handle it.
def try_concat(x, y):
    try:
        return str(x) + ' is ' + y
    except (ValueError, TypeError):
        return np.nan

df['baz'] = [try_concat(x, y) for x, y in zip(df['bar'], df['foo'])]

perfplot Performance Measurements

Graph generated using perfplot. Here's the complete code listing.
Functions

def brenbarn(df):
    return df.assign(baz=df.bar.map(str) + " is " + df.foo)

def danielvelkov(df):
    return df.assign(baz=df.apply(
        lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1))

def chrimuelle(df):
    return df.assign(
        baz=df['bar'].astype(str).str.cat(df['foo'].values, sep=' is '))

def vladimiryashin(df):
    return df.assign(baz=df.astype(str).apply(lambda x: ' is '.join(x), axis=1))

def erickfis(df):
    return df.assign(
        baz=df.apply(lambda x: f"{x['bar']} is {x['foo']}", axis=1))

def cs1_format(df):
    return df.assign(baz=df.agg('{0[bar]} is {0[foo]}'.format, axis=1))

def cs1_fstrings(df):
    return df.assign(baz=df.agg(lambda x: f"{x['bar']} is {x['foo']}", axis=1))

def cs2(df):
    a = np.char.array(df['bar'].values)
    b = np.char.array(df['foo'].values)

    return df.assign(baz=(a + b' is ' + b).astype(str))

def cs3(df):
    return df.assign(
        baz=[str(x) + ' is ' + y for x, y in zip(df['bar'], df['foo'])])

A: You could also use
df['bar'] = df['bar'].str.cat(df['foo'].values.astype(str), sep=' is ')

A: df.astype(str).apply(lambda x: ' is '.join(x), axis=1)

0    1 is a
1    2 is b
2    3 is c
dtype: object

A: I think the most concise solution for arbitrary numbers of columns is a short-form version of this answer:
df.astype(str).apply(' is '.join, axis=1)
You can shave off two more characters with df.agg(), but it's slower:
df.astype(str).agg(' is '.join, axis=1)

A: It's been 10 years and no one proposed the most simple and intuitive way which is 50% faster than all examples proposed on these 10 years.
df.bar.astype(str) + ' is ' + df.foo

A: I have encountered a specific case from my side with 10^11 rows in my dataframe, and in this case none of the proposed solution is appropriate. I have used categories, and this should work fine in all cases when the number of unique string is not too large. This is easily done in the R software with XxY with factors but I could not find any other way to do it in python (I'm new to python). If anyone knows a place where this is implemented I'd be glad to know.
def Create_Interaction_var(df,Varnames):
    '''
    :df data frame
    :list of 2 column names, say "X" and "Y".
    The two columns should be strings or categories
    convert strings columns to categories
    Add a column with the "interaction of X and Y" : X x Y, with name
    "Interaction-X_Y"
    '''
    df.loc[:, Varnames[0]] = df.loc[:, Varnames[0]].astype("category")
    df.loc[:, Varnames[1]] = df.loc[:, Varnames[1]].astype("category")
    CatVar = "Interaction-" + "-".join(Varnames)
    Var0Levels = pd.DataFrame(enumerate(df.loc[:,Varnames[0]].cat.categories)).rename(columns={0 : "code0",1 : "name0"})
    Var1Levels = pd.DataFrame(enumerate(df.loc[:,Varnames[1]].cat.categories)).rename(columns={0 : "code1",1 : "name1"})
    NbLevels=len(Var0Levels)

    names = pd.DataFrame(list(itertools.product(dict(enumerate(df.loc[:,Varnames[0]].cat.categories)),
                                                dict(enumerate(df.loc[:,Varnames[1]].cat.categories)))),
                         columns=['code0', 'code1']).merge(Var0Levels,on="code0").merge(Var1Levels,on="code1")
    names=names.assign(Interaction=[str(x) + '_' + y for x, y in zip(names["name0"], names["name1"])])
    names["code01"]=names["code0"] + NbLevels*names["code1"]
    df.loc[:,CatVar]=df.loc[:,Varnames[0]].cat.codes+NbLevels*df.loc[:,Varnames[1]].cat.codes
    df.loc[:, CatVar]=  df[[CatVar]].replace(names.set_index("code01")[["Interaction"]].to_dict()['Interaction'])[CatVar]
    df.loc[:, CatVar] = df.loc[:, CatVar].astype("category")
    return df

A: from pandas import *
x = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})
x

 x['bar'] = x.bar.astype("str") + " " + "is" + " " + x.foo
x.drop(['foo'], axis=1)


text:
Q: Android ViewBadger not showing I am trying to use a badge in android by exploiting https://github.com/jgilfelt/android-viewbadger
To this end I am inflating a TextView like
        TextView target = (TextView) rowView.findViewById(R.id.menu_item_badge);
        BadgeView badge = new BadgeView(this.getContext(), target);
        badge.setText("1");
        int droidGreen = Color.parseColor("#A4C639");
        badge.setBadgeBackgroundColor(droidGreen);
        badge.show();

The problem is I can't see the badge


text:
Q: Creating experimental database This question is about databases but I prefer to post it here and not in dba.stackexchange. The reason is that I have concerns with the application as well as database design. Programmers can better assist in this regard.
My four year old .NET application is using MySQL 5.1 database server as back-end. The database is running well. There are no performance issues to make us worry about. But I want to try out advanced database features like Partitioning, Replication and Clusters. I have never used these concepts before and I can definitely give these features a try on existing database, but I have some other plans.
I want to use IBM DB2 express-C as an experimental database. Records from MySQL need to be synchronized into DB2 database and I want to use the DB2 database for reports in my application.
Is there any free tool to synchronize the two databases? Do I need to use two connection strings, the first one involving MySQL for Inserts/Updates/Deletes and the second one involving DB2 for Reporting?
Is this type of foolish approach used in real world in certain scenarios?

A: Well, you not only need two different connection strings, you also need completely different database connectors. And then the fun starts for real.
Most likely DB2 uses a different SQL syntax, so you would need to check all your select queries whether they actually produce the same output. Plus: each database manufacturer has a few custom features built into their dialect of SQL. Things that work under MySQL are not automatically guaranteed to work with DB2. Which means that just transferring or replicating the data into the DB2 database could be a major job on its own.
I have not come across this approach in any real world scenarios, but then, I don't know every real world scenario that exists out there.
From experience I would advise to steer well clear of this sort of thing unless you have a really strong reason to go down that road. You are most likely in for a world of pain for very little gain.

A: This is a common scenario in the database world. Nice to see someone who wants to learn it. Companies send data back and forth to different systems all the time (both their systems and their clients systems and their vendors systems). I can't speak to free tools to do this because I live in SQL Server world and SSIS is the tool we use which comes with SQL Server. But what you want to search for is ETL tools. Tools for this are out there, I just don't know which ones are the best. ETL stands for Extract, Transform, Load which are the steps in the process of moving data from one database to another.
Let me describe some of the issues you need to think about when sending data back and forth between two systems. The first and most important is that it is highly unlikely that the two databases will be simliar in structure. Fields that are reuired in one may not exist in the other. Data types will be different. Business rules will be different. Lookup values will be different.
You will have to handle things like the States table which will exist in one db and all addresses must use a valid 2 digit US state code in the required State field, but the data is coming from a table that allows any value (or even no value) to be put in a state field in the address table, therefore it has things like Virginia, Ohoi (instead of Ohio), CA, ON (Canadian state fo Ontario), and Unknown as well as null values. You have to figure out waht to do with records that have data that won't fit in the receiving database.
You need to think about how will you match up existing records to the ones already in your database.
Another thing you have to think about is how to handle data that is merged by one database due to finding and fixing duplicates. Do you need to have way to make sure it gets merged in the other database?
You have to think of performance. This can be an intense process that takes a lot of the resources of both databases. You need to think in terms of how can I minmize the impact to other users of the database.
Most ETL tools will let you send directly to the other database (generally if they are in the same network) and other times you need to create one or more files to send to a clinet in another location. Then you need to think about what the structure of the data sent should be. Should you have one denormalized file or several files that refelect the way your own database is normalized. Should the sender clean the data to the receiovers specs or vice versa or should both be doing some scrubbing.  Are there legal requirements (think about sending patient data from a docotprs office to a hospital for instance).
There's a lot more, ETL is a complex specialty, but I think that is enough to get you started on thinking about the planning you have to do once you find your tool.


text:
Q: Display key value array in javascript alert I have a key value pair array:
    var myKeyVals = {make: "a", model: "2"};

Is there any easy way to format this array so that it is displayed meaningful in an alert?
    alert(myKeyVals);

Here I get only:
[Object object]

But with console.log I get:
Object {make: "a", model: "2"}

A: To get formatted output.
alert( JSON.stringify(myKeyVals,null,4) )

I do recommend using console.log instead of alert.


text:
Q: Approximating $100!$ I participated in an Estimathon (a speed contest of Fermi problems) not long ago. It works as follows. Contestants are given questions and they must give a closed range $[a,b]$ which should contain the correct answer. The scoring guidelines are such that you want to minimize your "number of points" where the points depends on $\left\lfloor\frac{b}{a}\right\rfloor$. If your range does not contain the correct answer, your number of points doubles which is bad. So the top priority is to make sure your range contains the correct answer. After that, it is important to make sure your range is not too big.
One of the questions was:

Estimate $100!$.

I was the only person among 40 people to get this correct, since I had memorized $100! \approx 9.33 \times 10^{157} $, so I just put $\left[9 \times 10^{157}, 10^{158}\right]$. However, is there a way to get this correct to one order of magnitude? Note that two orders of magnitude is too imprecise for this contest.
I was thinking of using Stirling's approximation but even that is quite tedious to do by hand (no calculators were allowed)!

A: If you are good in memoralization, then it is very elegant to use one of Ramanujan's factorial approximations. In Ramanujan's lost notebook you can find this one:
$$ n! \sim \sqrt{\pi}n^{n}e^{-n}\sqrt[6]{8n^3+4n^2+n+\frac{1}{30}} $$
This is a very strong, and also famous approximation. Using it for approximate $100!$ you get $9.3326215444826261629 \cdot 10^{157}$. The first $10$ digit is correct! If you are intrested in factorial approximation you can get some result here.
Edit. This might be interesting.

A: What's wrong with Stirling's approximation?
$$100!\approx \sqrt{2\pi 100}(100/e)^{100}\approx\sqrt{628}(100/e)^{100}$$
Since $628\approx 625$, the square root gives $\approx25$, and now:
$$(100/e)^{100}=100^{100} e^{-100}= 100^{100} 10^{-100 /\ln 10}$$
Now if you memorized $100!$, surely you memorized $\ln 10 \approx 2.3$, so:
$$100!\approx 2.5 \cdot 10^{157}$$
Which is correct to within an order of magnitude, without using a calculator.
Addendum: If you note that $100/2.3$ is around $43.5$, and use $\sqrt{10}\approx 3.2$, you get $8 \cdot 10^{157}$, which is even closer.

A: I am not at all familiar with this type of contest, so forgive me if this is stupid.
Assuming that you have a programmable calculator, you could first compute in a loop $$A=\log_{10}(100!)=\sum_{i=1}^{i=100}\log_{10}(i)\simeq 157.9700037\simeq158-0.03$$ So, $$10^A=100!\simeq10^{158}10^{-0.03}=e^{-0.03 log (10)}10^{158}\simeq e^{-0.069} 10^{158}$$ Now, use one term of the Taylor expansion of $e^x$ around $x=0$ to get $e^{-0.069}\simeq 0.931$ which corresponds to an underestimate. Then $$0.931 \times 10^{158} \lt 100! \lt 10^{158}$$


text:
Q: Memory Error while convert string to list in python I am using operating system MacOS Sierra(version 10.12.5) and log in as the root user.
The length of the string is 38405.
I am using eval to convert string to list
I have added following in my python file:
1.
resource.setrlimit(resource.RLIMIT_STACK, [0x10000000, resource.RLIM_INFINITY])
sys.setrecursionlimit(0x100000)

But get the following error
resource.setrlimit(resource.RLIMIT_STACK, [0x10000000, resource.RLIM_INFINITY])
ValueError: current limit exceeds maximum limit

*If I use os.system('ulimit -s 65532') getting following error

Same Error
s_push: parser stack overflow MemoryError

How to resolve this issue?
The string, I tried to convert can be found the following link
https://drive.google.com/open?id=0B_JtQtd0sA4nMlJ0RGNRU3JZVGM
Definition of the function present in the string is as follows
def expres(functor,args=[]):
    return [functor]+args


text:
Q: How to Set the link for "Home" button for CHM file? I create a CHM help document with HTML Workshop. However, when click the "Home" button in the navigator bar, I will see this:

Our homepage will be distorted completely.
I try to find a way to set the "Home" button link but cannot a way. Finally I open .hhp file and edit the following line:
[WINDOWS]
main="DataNumen Outlook Repair","DOLKR.hhc","DOLKR.hhk","introduction.htm","https://www.datanumen.com/",,,,,0x62520,,0x3046,[0,0,780,660],,,,,,,0

But after that, when I click the "Home" page, I will get the following error:

So how to solve the problem?
The chm file(version 1) can be downloaded from https://www.datanumen.com/temp/20210113/DOLKR.chm

A: The short story - AFAIK it's not possible linking to a domain or an exact location from the CHM's home button by full path URL.
CHM files offer the preferred option of the "Default Topic file" (e.g. "introduction.htm"). The "Home" button can also be suppressed by special settings, but is useful for returning to "Home" if you have previously navigated different topics. In the sense of a homepage of the HTML help file "web" this can be a "home.htm" or even the "introduction.htm".
My suggestion as a simple workaround is to create a nice home.htm and link from there to your own company page in a new browser window.
[WINDOWS]
main="DataNumen Outlook Repair","DOLKR.hhc","DOLKR.hhk","introduction.htm","home.htm",,,,,0x62520,0,0x3046,[0,0,780,660],0xB0000,,,,,0,

As mentioned by others CHM files were developed over 20 years ago and are usually only used as a local help file. The system requires Internet Explorer. You can't access complex web pages because of the outdated Internet Explorer browser.
It is possible to link to simple HTML pages on the internet via the table of contents file (.hhc) as shown below. Please keep in mind that a customer using a local CHM help file requires an internet connection.
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">

<meta name="GENERATOR" content="Microsoft® HTML Help Workshop 4.1">

<OBJECT type="text/sitemap">
          <param name="Name" value="Jump directly from here (help-info.de)">
          <param name="Local" value="https://www.help-info.de/index.htm">
          <param name="ImageNumber" value="13">
        </OBJECT>

 <OBJECT type="text/sitemap">
        <param name="Name" value="Introduction">
        <param name="Local" value="introduction.htm">
        </OBJECT>

 <OBJECT type="text/sitemap">
        <param name="Name" value="System requirements">
        <param name="Local" value="requirements.htm">
        </OBJECT>

 <OBJECT type="text/sitemap">
        <param name="Name" value="Usages">
        </OBJECT>

 <OBJECT type="text/sitemap">
            <param name="Name" value="Repair file">
            <param name="Local" value="repairfile.htm">
            </OBJECT>
...

A: The Microsoft HTML help viewer used to display CHM help files is very old and not maintained by Microsoft anymore: it is using an older version of Internet Explorer to display topic content and external URLs which might break modern web-sites, and I suspect that this is the cause of your problem.
Some possible solutions include:

*

*You can create a specific page for your web-site which work on older versions of Internet Explorer and link to that page instead

*You can create a link to a _blank target which will open that page in your standard web-browser instead of the Microsoft HTML help viewer


text:
Q: Dynamic project-wide variable in Emacs I'd like to have a project-wide variable which I can change during looking at that project. In other words, I'd like to get it affected whenever opening a file. Yes, I know .dir-locals.el exist in Emacs world. But I think it would be reset to the value set in .dir-locals.el whenever opening a file under that project.
Could I get some hints from you, please?

A: For this kind of thing you might want to use a function instead of a variable (directly).  Specifically, use a getter and setter function.
All of your project code can invoke the getter function to get the value (which can be cached in a variable).  And all of your code can invoke the setter function to change the value (which, again, can be cached in a variable).
These functions can be visible globally to your project.  The cache variable would be accessed only by the getter and setter functions.

But as for code everywhere in your project being informed when the value gets updated and do what's appropriate with the new value whenever that happens, see @Phil's comment about the use of a variable - the same considerations apply.
You can have a hook in the setter function (or advise it), so that it does something additional (e.g. informs interested/subscribed code) whenever it updates the value.

For a variable you can do something similar using, as @Phils said in a comment, using add-variable-watcher.
For a user-option variable you can do something similar using :set and :get functions in the defcustom.  (But those take effect only if changes are made using appropriate Customize functions or the Customize UI.)

A: You can eval in the dir-locals.el  So, if you have a variable my-var that you want to be able to change with setq you could do something like
((nil . ((eval . (or (boundp 'my-var) (setq my-var 'default))))))

There are warnings about using eval in a dir-local though, since any code could be run there.


text:
Q: Color Change in Area Chart i have a Java-Class that extends the AreaChart. There i would like to implement a method that makes more or less something like this:
public void addNewColorToData(xCoordinate, yCoordinate, redColor, greenColor, blueColor);

-> The Function should get the parameters of the Data for the xCoordinate, yCoordinate and then for the RGB Value of the representes Line.
Is it possible to create with Inline-Styles a new Color for this ?

Here you can see a Sample. There are a lot of Color-Fills for the Area Chart!
Is it possible to add there some new colors?
I need to add a Inline Style stuff like this in CSS:
.default-color0.chart-series-area-fill { -fx-fill: #007Fc350; }

Thank you for your help

A: Based on this answer, to create an inline style based on r,g,b parameters (given these are integers from 0 to 255) you just need to override the CHART_COLOR_1 (up to CHART_COLOR_8) value to modify the line color and CHART_COLOR_1_TRANS_20 (up to CHART_COLOR_8_TRANS_20) to modify the area color:
private AreaChart<String, Number> areaChart;

private void changeColor(int redColor, int greenColor, int blueColor, double opacity){
    /* int redColor=0, greenColor=127, blueColor=195;
       double opacity=0.4;
    */
    areaChart.setStyle("CHART_COLOR_1: rgb("+redColor+","+greenColor+","+blueColor+");" +
           "CHART_COLOR_1_TRANS_20: rgba("+redColor+","+greenColor+","+blueColor+");");
}

EDIT
I'm adding this short MVCE for the sake of clarity:
@Override
public void start(Stage primaryStage) {
    AreaChart<String, Number> areaChart=new AreaChart<>(new CategoryAxis(),new NumberAxis());

    ObservableList<XYChart.Data<String,Integer>> xyList
            = FXCollections.observableArrayList(
                    new XYChart.Data<>("P1", 30),
                    new XYChart.Data<>("P2", 40),
                    new XYChart.Data<>("P3", 30));
    XYChart.Series series = new XYChart.Series(xyList);
    areaChart.getData().addAll(series);

    Button button = new Button("Change style");
    button.setOnAction(e->{
        int redColor=0, greenColor=127, blueColor=195;
        double opacity=0.3;
        areaChart.setStyle("CHART_COLOR_1: rgb("+redColor+","+greenColor+","+blueColor+"); "
                + "CHART_COLOR_1_TRANS_20: rgba("+redColor+","+greenColor+","+blueColor+","+opacity+");");
    });

    VBox root = new VBox(5, button, areaChart);
    Scene scene = new Scene(root, 400, 300);
    primaryStage.setScene(scene);
    primaryStage.show();
}

This would be the result:


text:
Q: SQL - Retrieve field from sub-query I am writing a script using Oracle database 11g.
I currently have several nested sub-queries. I need to retrieve a field from one of these sub-queries, but having some difficulty.
My script currently is:
SELECT  a.PARTY_ID, a.PARTY_NAME, a.STATUS
        ,a.OBJECT_VERSION_NUMBER, a.PARTY_NUMBER
FROM    HZ_PARTIES a
WHERE   a.PARTY_TYPE = 'ORGANIZATION'
AND     a.STATUS = 'A' and a.party_id = 4402
AND     a.CREATED_BY_MODULE IN ('HZ_CPUI','TCA_V1_API','TCA_FORM_WRAPPER')
AND     (a.PARTY_ID IN (SELECT b.PARTY_ID FROM HZ_CUST_ACCOUNTS b
           WHERE b.CUSTOMER_TYPE = 'R'
           AND b.CUST_ACCOUNT_ID IN (SELECT c.BILL_TO_CUSTOMER_ID FROM RA_CUSTOMER_TRX_ALL c
                    WHERE c.BILL_TO_CUSTOMER_ID IS NOT NULL
                    AND c.LAST_UPDATE_DATE < SYSDATE-100)))

I am trying to select a field 'LAST_UPDATE_DATE' from the last of the nested sub-queries (the RA_CUSTOMER_TRX_ALL table).
I've tried to include a select sub-query in the SELECT section. and the FROM section, but cannot link it into the last part of the sub-query.
Can anyone assist?
Cheers,
RussH.

A: An untested swag at it. You may have to remove duplicates depending on your data:
SELECT  a.PARTY_ID, a.PARTY_NAME, a.STATUS
        ,a.OBJECT_VERSION_NUMBER, a.PARTY_NUMBER, c.last_update_date
FROM    HZ_PARTIES a JOIN hz_cust_accounts b
                       ON b.customer_type = 'R'
                          AND a.party_id = b.party_id
                     JOIN ra_customer_trx_all c
                       ON b.cust_account_id = c.bill_to_customer_id
                          AND c.last_update_date < SYSDATE-100
WHERE   a.PARTY_TYPE = 'ORGANIZATION'
AND     a.STATUS = 'A' and a.party_id = 4402
AND     a.CREATED_BY_MODULE IN ('HZ_CPUI','TCA_V1_API','TCA_FORM_WRAPPER')


text:
Q: How to create a post using REST API with sending data as a JSON body? I am able to create posts on my WordPress website using it's REST API with the below curl request format. Website uses basic auth plugin for the authentication process.
curl --user "username:password" -X POST -i https://mywebsite.com/wp-json/wp/v2/posts?title=myTitle&content=MyContent
However, my problem is I need to set custom fields of the post when creating a post using  REST API. I tried to send data as a JSON body using the below command and it didn't work. It just returns all the posts without creating a new post and also without giving any error.
curl --user "username:password" -X POST -i https://mywebsite.com/wp-json/wp/v2/posts -d '{"title":"NEw tiitle"}'
I have tried sending post creation requests to my website using the Postman service also and the same thing happened. Could anyone please help me to solve this problem? Thanks in advance!

A: That's strange, but nonetheless, you should know that whether you use cURL, PHP, JS, etc., if you're sending a JSON data, then you should set the Content-Type header to application/json.
And via the cURL command line, you can use the -H option:
curl --user "username:password" -X POST \
-H "Content-Type: application/json" \
-i https://example.com/wp-json/wp/v2/posts \
-d '{"title": "foo bar", "content": "test"}'

Also, if you're using Windows, you may need to use the double quotes instead of single quotes with the -d option. So the above would be: ( note I used the caret (^) symbol and not backslash )
curl --user "username:password" -X POST ^
-H "Content-Type: application/json" ^
-i https://example.com/wp-json/wp/v2/posts ^
-d "{\"title\": \"Windows test\", \"content\": \"test\"}"


text:
Q: jython - why '==' return true but 'is' return false I am start use jython2.7.0 now, but there has little different between python2.7.15.
for example, In python
a = "hello", b = "hello", "a is b" and "a == b" will return True.
but In jython2.7.0 "a is b" return False, "a == b" return True, does anyone knows why ??
>>>jython
>>>
>>>a = "hello"
>>>b = "hello"
>>>
>>>a is b
>>>False
>>>
>>>a == b
>>>True
>>>
>>>a = 1
>>>b = 1
>>> a is b
>>>True


text:
Q: Extracting complete paired values (non-NA) from a matrix in R I apologize if this is elementary or has been answered before, but I haven't found an answer to my question despite extensive searching. I'm also very new to programming so please bear with me here.
I have a bunch of 25 by 2 matrices of data, however some of the cells have NA values. I'm looking to extract a subset of the matrix consisting of only the complete paired values (so no NA values).
So say I have:
3.6    4.2
9.2    8.4
4.8    NA
1.1    8.2
NA     11.6
NA     NA
2.7    3.5

I want:
3.6    4.2
9.2    8.4
1.1    8.2
2.7    3.5

Is there some function that would do this easily?
Thanks!

A: Try this
df <- read.table(text = "3.6    4.2
9.2    8.4
4.8    NA
1.1    8.2
NA     11.6
NA     NA
2.7    3.5")
df[complete.cases(df), ]
#    V1  V2
# 1 3.6 4.2
# 2 9.2 8.4
# 4 1.1 8.2
# 7 2.7 3.5

A: df[ apply(!is.na(df), 1, all) , ]

df <- data.frame(V1 = c(3.6,9.2,4.8,1.1,NA,NA,2.7),
                 V2 = c(4.2,8.4,NA,8.2,11.6,NA,3.5))

EDIT: I forgot na.omit or complete.cases Doh.


text:
Q: If input contains at least one character Sorry guys that i am asking a question that has long been answered. But I could not find the answer I needed.
The question is that i want to check value of input. If input after unfocus has one text or more (do something)
 var inputLength = $('input').val();
 if (inputLength.length > 1) {
     $('span.input--madoka').addClass('myclass')
 }
 else  {

 }

A: Use blur() event to call your function when element loses focus
Here is example

$('#filter').blur(function() {

  var inputLength = $(this).val();

  if (inputLength.length > 1) {

    console.log('has something');

    // here you add whatever class you want to add to other element

  } else {

    console.log('has nothing');

    // here some other action
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="filter" value="" />

A: You can do like this.

var empty = true;
$('#test').on('change', function(){
   if($(this).val()!=""){
      console.log('not empty');
    } else {
      console.log('empty');
    }
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Text : <input type="text" id="test" >


text:
Q: Where to report a bug on Ubuntu's Launchpad? I'm trying to file a bug report for Ubuntu's bug reporting system. The bug reporter is Launchpad.
Launchpad is not a package, so I can't file the bug report against anything. From the past, I know that selecting "I don't know" for the package means its sits somewhere and nothing gets done with it.
How does one file a bug report against Ubuntu's Launchpad?

A: You file it against the launchpad project rather than a package in the ubuntu project: https://bugs.launchpad.net/launchpad


text:
Q: Low count of data frames in wifi monitor mode I am using scapy to gather stats about wifi traffic for a given MAC. I log the date, type, subtype, and rssi of packets I capture in monitor mode with scapy.
And I see a very low count of data frames (type 2, subtype 0). Why ?
For example, I initiated the download of a 8MB file and the count increased by one or two.
As data frames are approx. 2k in size, I would except a fair amount of data frames being seen for such a download.
The wifi connexion is on a 802.11n with WPA2 on channel 1 captured with a TP-Link TL-WN722N on a rpi3 running archlinux-arm.
Edit:
I tried by setting the channel bandwidth to HT40+  (with iw dev wlan1mon set channel 1 HT40+) but I did not see more Data frames either.
Does it have to do with the number of antennas ? the TL-WN722N has only one antenna while the AP has 2, and I guess the latpop too.
But why would I see the other frames, then ?
Edit2:
So using tshark -i wlan1mon -Y 'wlan.fc.type_subtype == 0x20' -n -t a -T tabs, I discovered that I am seeing only packet to broadcast or multicast mac like ff:ff:ff:ff:ff:ff, 33:33:00:00:00:01, 01:00:5e:7f:ff:fa
Even if I set the interface in promiscious mode, it is still the same...

A: Both 802.11n and 802.11ac require QOS (WMM, 802.11e), so all data is sent as Data/QOS-Data (type 2 subtype 8) frames nowadays.
Data/Data (type 2 subtype 0) is a vanishing relic of the bygone a/b/g era.


text:
Q: incrementing the digit by 1 in python using isdigit() i understand that by using the following syntax i can remove all the digit appearing in my sentence. How can i modify this to increment the digit or as matter of fact do any operation on it....
no_integers = [x for x in list_add_one_city if not (x.isdigit() or x[0] == '-' and x[1:].isdigit())]

for example...
given stmt
You would like to eat salad as meal 1 and fruits as meal 2 and pizza as meal 3 in your diet.
need to be translated to (using ISDIGIT()):
You would like to eat salad as meal 2 and fruits as meal 3 and pizza as meal 4 in your diet.

A: I would use regex, the .sub() method and a lambda function.
The regex can easily detects digits, and you can then replace them with the incremented value.
import re
s = "You would like to eat salad as meal 1 and fruits as meal 2 and pizza as meal 3 in your diet."

s = re.sub(r'(\d+)', lambda match: str(int(match.group()) + 1), s)
print(s)
# You would like to eat salad as meal 2 and fruits as meal 3 and pizza as meal 4 in your diet.

If you really need to use .isdigt(), you should first .split(), the sentence, then iterate through the words list and incremente the value if the element is an actual int. Finally, do not forget to .join() the results to get your string back. Somethink like this:
words = [str(int(w) + 1) if w.isdigit() else w for w in s.split()]
s = " ".join(words)

A: The answer from @Delgan is great and words perfectly. I just thought I would add to it as I noticed you are making some mistakes using list comprehension, and I believe this might be the source to your problem.
List comprehension is a great feature to use. But there are a couple parts you should realize. See the picture below to see the parts of list comprehension broken up.

So when you create a list using another collection. The end part, where you are using an if statement is used for filtering, but you actually want everything in the previous list (all the words in the previous sentence) to be in the new list. You only want to increment all numbers in that sentence.
This means you should perform a function on certain elements.  I see in your problem the part of list comprehension  to perform a function on certain elements in the list (specifically, elements that are positive or negative integers) is what you want. This should be done in the list result field. Here is my example code:
# Function acting on all elements, increase integer values otherwise return original string
def increment_if_digit(word):
    if x.isdigit():
        value = int(x)
        value += 1
        return str(value)
    elif x[0] is '-' and x[1:].isdigit():
        value = int(x)
        value += 1
        return str(value)
    else:
        return word

# Example usage
sentence = "You would like to eat salad as meal 1 and fruits as meal 2 and pizza as meal 3 in your diet."
no_integers = [increment_if_digit(x) for x in sentence.split()]
print " ".join(no_integers)

which outputs:
You would like to eat salad as meal 2 and fruits as meal 3 and pizza as meal 4 in your diet.

A: The example is much easier with try and except to catch errors vs trying to build a small parser.
>>> stmt='You would like to eat salad as meal 1 and fruits as meal 2 and pizza as meal 3 in your diet'

def incs(word, n):
    try:
        return str(int(word)+n)
    except ValueError:
        return word

>>> ' '.join([incs(w, 1) for w in stmt.split()])
You would like to eat salad as meal 2 and fruits as meal 3 and pizza as meal 4 in your diet


text:
Q: umask отдельно для файлов Сейчас разбираюсь с linux и возник такой вопрос по поводу umask.
Можно ли каким-либо образом сделать по умолчанию права  для папок 777, а для файлов 664. На сколько понял, что стандартными средствами это сделать  нельзя.
Есть еще dmask и fmask, но такие настройки не поддерживаются в /etc/login.defs.
Или  такого не предусмотрено и выставляются права сразу для папок и файлов (002, 022, 077).


text:
Q: Compiler-enforced semantic types Say I have a class representing automata, whose states are numbered (using state_t = unsigned) and whose transitons are also numbered (using transition_t = unsigned).  Of course at some point I end up messing some calls because transition_t and state_t are the same type, so the compiler does not enforce the (semantic) type safety.  That's easy to workaround by using a small class templated by a tag (struct transition_tag {}; struct state_tag {};), so now transition_t and state_t are incompatible, good!
/// Lightweight state/transition handle (or index).
template <typename Tag>
struct index_t_impl
{
  using index_t = unsigned;

  constexpr index_t_impl(index_t i)
    : s{i}
  {}

  // Disallow index1_t i{index2_t{42}};
  template <typename T>
  index_t_impl(index_t_impl<T> t) = delete;

  bool operator==(index_t_impl t) const
  {
    return s == t.s;
  }

  // Disallow index1_t{42} ==  index2_t{42};
  template <typename T>
  bool operator==(index_t_impl<T> t) const = delete;

  /// Default ctor to please containers.
  index_t_impl() = default;
  constexpr operator index_t() const { return s; }
  /// Be compliant with Boost integer ranges.
  index_t_impl& operator++() { ++s; return *this; }
  /// Be compliant with Boost integer ranges.
  index_t_impl& operator--() { --s; return *this; }

private:
  index_t s;
};

Further, I have two structures which are very much alike:

*

*predecessors_t maps from a transition to its predecessor transition (in the shortest path).  For efficiency, it's a std::vector<transition_t>.

*path_t is a list of transition indexes.  For efficiency it's a std::vector<transition_t>.

And then again I have this issue that I use std::vector<transition_t> for two completely different purposes.  Of course, I could again introduce a wrapper templated by a tag, but then things become messy again.  Public inheritance is very tempting (Thou shalt not inherit from std::vector)!
But really, I'm tired of ad-hoc solutions each time I want to introduce new types that are exactly like the base type, but just incompatible.  Are there any recommendations on this regard?  The public inheritance is really attractive, but wouldn't it introduce code bloat with tons on extra instantiations?  Maybe the public composition (struct predecessors_t { std::vector<transition_t> v; };) as recommended by Crashworks (https://stackoverflow.com/a/4353276/1353549) is a better option that scales better?
Is there anything in sight in the future of C++ to address this new?

A: This issue of getting compiler-enforced semantic types can crop up in all sorts of situations, from your situation to co-ordinate systems with different origins (where the values are all the same type (eg. int), but semantically, the types must not be mixed, because they represent offsets from different origins (x,y,z=0,0,0)--this occurs frequently in mathematics, where, when graphing the quadrant with positive x and y, the origin is in the lower left, and computer science where it is very common to place the origin upper left) to spaceship navigation (more on this last below).
In 2012, Bjarne Stroustrup gave an interesting talk on what he called type-rich programming introducing compiler-enforced semantic type safety with C++11 using templates, user-defined literals, a claimed no run-time overhead implementation and even tales of lessons learned from the Mars Climate Observer snafu ($350M spacecraft + mission lost because of lack of enforced semantic type safety).  You can see the part of the talk where he covers semantic types here: https://youtu.be/0iWb_qi2-uI?t=19m6s
I've written up a sample code excerpt based on Stroustrup's demo code, updated to current standards and with the required operator overloads implemented).  Unlike Bjarne's example, this one actually compiles. ;)
Gist of this code can be found here: https://gist.github.com/u-007d/361221df5f8c7f3466f0f09dc96fb1ba
//Compiled with clang -std=c++14 -Weverything -Wno-c++98-compat main.cpp -o main

#include <iostream>
#include <string>

template<int M, int K, int S>  //Meters, Kilograms, Seconds (MKS)
struct Unit
{
    enum { m=M, kg=K, s=S };
};

template<typename Unit> //a magnitude with a unit
struct Value
{
    double val; //the magnitude
    constexpr explicit Value(double d) : val(d) {} //construct a Value from a double
};

//Basic Semantic Units for MKS domain
using Meter = Unit<1, 0, 0>;
using Kilogram = Unit<0, 1, 0>;
using Second = Unit<0, 0, 1>;
using Second2 = Unit<0, 0, 2>;

//Semantic Value Types for MKS domain
using Time = Value<Second>;
using Distance = Value<Meter>;
using Mass = Value<Kilogram>;
using Speed = Value<Unit<1, 0, -1>>; //Speed is meters/second
using Acceleration = Value<Unit<1, 0, -2>>; //Acceleration is meters/second^2

//Operator overloads to properly calculate units (incomplete; for demo purposes)
Speed operator/(const Distance& lhs, const Time& rhs)
{
    return Speed(lhs.val / rhs.val);
}

Acceleration operator/(const Speed& lhs, const Time& rhs)
{
    return Acceleration(lhs.val / rhs.val);
}

//Define literals
constexpr Distance operator"" _m(long double ld)
{
    return Distance(static_cast<double>(ld));
}

constexpr Mass operator"" _kg(long double ld)
{
    return Mass(static_cast<double>(ld));
}

constexpr Time operator"" _s(long double ld)
{
    return Time(static_cast<double>(ld));
}

constexpr Acceleration operator"" _s2(long double ld)
{
    return Acceleration(static_cast<double>(ld));
}

int main()
{
    Speed sp = Distance(100)/Time(9.58); //Not bad, but units could be more convenient...
    Distance d1 = 100.0_m; //A good distance to run a race
    Speed sp1 = 100.0_m/9.58_s; //A human can run this fast
//    Speed sp2 = 100.0_m/9.8_s2; //Error: speed is m/s, not m/s^2
//    Speed sp3 = 100.0/9.8_s; //Error: 100 has no unit
    Acceleration ac1 = sp1/0.5_s; //Faster than any human

    return EXIT_SUCCESS;
}


text:
Q: Node.Js error Can not set headers after they are sent to client i am beginner in node.js and i noticed that after i execute my request the first time it works but node.js launch an error after it that says:
Can not set headers after they are sent to client

Here what i have tried
questions service:
module.exports={
 create:(data,callback)=>{
  var myArray = new Array();
 /* for(let item of data.players) {
    console.log(item.firstname);
}*/

console.log(data);
data.players.forEach((player) => {
  console.log(player.id);
  console.log(player);
  var playerModel ={
    id : player.id,
    firstname : player.firstname,
    lastname : player.lastname,
    position : player.position,
    price : player.price,
    appearences : player.appearences,
    goals : player.goals,
    assists : player.assists,
    cleansheets : player.cleansheets,
    redcards : player.redcards,
    yellowcards : player.yellowcards,
    image : player.image
  };
  console.log("model"+playerModel.position);
  myArray.push(playerModel);
});
var id;

 pool.query(
      'insert into club(userid,email,password,name,price) values(?,?,?,?,?)',
   [
        data.userid,
        data.email,
        data.password,
        data.name,
        data.price
      ],

      (error,result) => {
        if(error){
          callback(error);

        }

        for(var item of myArray){
          pool.query(

            'insert into players(id,firstname,lastname,position,price,appearences,goals,assists,cleansheets,redcards,yellowcards,image,clubid) values (?,?,?,?,?,?,?,?,?,?,?,?, ( SELECT id from club where id > ? ORDER BY id DESC limit 1  ) )',
             [
             item.id,
             item.firstname,
             item.lastname,
             item.position,
             item.price,
             item.appearences,
             item.goals,
             item.assists,
             item.cleansheets,
             item.redcards,
             item.yellowcards,
             item.image,
             0
             ],

           (error,results,fields)=>{
             if(error){
               callback(error);
             }
             return callback(null,results);
           },
          );
          }
        return callback(null,result.insertId);
      },

    );

  },

Questions Controller:
const pool = require("../../config/database");
const{create,
  getQuestionsById,
  getQuestionsByCategory,
  getQuestions,
  getValidAnswer,
  setValide,
  CompareAnswers,
  updateQuestions,
  deleteQuestions
}=require("./questions.service");
module.exports={
  createQuestions:(req,res)=>{
    const body = req.body;
      create(body,(err,results)=>{
      if(err){
        console.log(err);
        return res.status(500).json({
          success:0,
          message:"database connexion error"
        });
      }
      return res.status(200).json({
        success:1,
        data:results
      });
    });
  },

Questions router:
const{
  createQuestions,
  getQuestionsById,
  getQuestions,
  getQuestionsByCategory,
  getValidAnswer,
  CompareAnswers,
  setValide,
  updateQuestions,
  deleteQuestions,

}=require("./questions.controller");
const router = require("express").Router();

router.post("/addQuestion",createQuestions);

router.get("/:id",getQuestionsById);
router.patch("/updateQuestion",updateQuestions);
router.delete("/",deleteQuestions);
router.get("/",getQuestions);
router.get("/VerifyAnswer/:id",getValidAnswer);
router.post("/getByCategory",getQuestionsByCategory);
router.post("/setValide", setValide);
router.post("/CompareAnswers", CompareAnswers);

module.exports=router;

My goal is to stop this error and find a solution for it, What is wrong with my code ? and why i have to run again the server after every execute of the request?? why the request works but it launch this error in the end?
A screen capture that shows the error:

A: I think in your question service in line:
 (error,results,fields)=>{
             if(error){
               callback(error);
             }

you should write
return callback(error)
This error generally occurs when your code tries to send 2 or more responses for a request. Let me know if it helps.


text:
Q: How to insert a long text in a multicolumn setting? I would like to create a table with my some rows being multicolumns, one of them to be filled with a long text, followed by a 2 column's row. I don't have any issue to create the multicolumns or insert the long text in the typical columns but when I use the \multicolumn function my text overflows and messes up my table.
I used the following code :
\documentclass{article}
\usepackage{booktabs}
\usepackage{tabu}
\usepackage[utf8]{inputenc}
\usepackage[autostyle]{csquotes}
\usepackage{graphicx}
\usepackage{longtable}
\usepackage{float}
\usepackage{graphicx}
\usepackage{lscape}
\usepackage[margin=1in]{geometry}
 \usepackage{authblk}
\usepackage{times}
\usepackage{url}
\usepackage{hyperref}
\usepackage[utf8]{inputenc}
\usepackage[autostyle]{csquotes}
\usepackage{caption}
\usepackage{amsmath}
\usepackage{ltablex,booktabs}
\usepackage[title]{appendix}

\newcolumntype{C}{>{\arraybackslash}X}
\newlength{\twocolwidth}
\setlength\twocolwidth{\dimexpr1\hsize+\tabcolsep+\arrayrulewidth}

\newcommand{\source}[1]{\vspace{-1pt}{\hfill \footnotesize{Source: {#1}} } }

\newcolumntype{b}{X}
\newcolumntype{s}{>{\hsize=.2\hsize}X}
\newcolumntype{m}{>{\hsize=.4\hsize}X}

\usepackage{xcolor}
\hypersetup{
    colorlinks,
    linkcolor={red!50!black},
    citecolor={blue!50!black},
    urlcolor={blue!80!black}
}

\topmargin 0.0cm
\oddsidemargin 0.2cm
\textwidth 16cm
\textheight 21cm
\footskip 1.0cm

\counterwithin{figure}{section}
\counterwithin{table}{section}
\renewcommand\thefigure{\thesection\arabic{figure}}
\renewcommand\thetable{\thesection\arabic{table}}

{\footnotesize
 \begin{tabularx}{\textwidth}[h!]{| X | X |}
 \caption{Description of the selected algorithms\label{TABLEA}}\\

 \hline
 \multicolumn{2}{| c |}{Begin of Table}\\
 \hline
Algorithm & General Operation \\
 \hline
 \endfirsthead

 \hline
 \multicolumn{2}{| c |}{Continuation of Table \ref{TABLEA}}\\
 \hline
Algorithm & General Operation \\
 \hline
 \endhead

 \hline
 \endfoot

 \hline
 \multicolumn{2}{| c |}{End of Table}\\
 \hline
 \endlastfoot

\multicolumn{2}{| c |}{\textbf{Agglomerative methods}} \\
\hline
\multicolumn{2}{|>{\hsize=\twocolwidth}C c |}{The notion of distance in this family makes it possible to identify cliques through relational proximities } \\
   \hline

 \hline
           \textbf{Hierarchical algorithm} with 4 different settings:  Euclidean distance / Complete linkage; Euclidean distance / Ward; Manhattan distance / Complete linkage; Manhattan distance / Ward.
           & The basic idea is to construct the hierarchical relationship among data in order to cluster. Each data point stands for an individual cluster in the beginning, and then, the most neighboring two clusters are merged into a new one until there is only one cluster left. The concept of "neighborhood" depends on the distance between nodes which is computed by squaring the Euclidean or Manhattan distances and grouping them into a symmetric matrix. The clustering method (here, complete linkage and Ward's algorithm) identifies the closest nodes to agglomerate them. We obtain a hierarchical dendogram which is cut to the desired number of clusters. \\

 \end{tabularx}
}

\end{document}

But the text appear in double as you can see here :

and the table become bigger than my page.
Is anyone know how to fix this please?
P.S : I am just a beginner using Overflow so I have no idea what part of the code produced that

A: *

*It is not clear, how your table should look.

*So far it is quite unusual. For example, what you like to say with row with "Begin of Table" and "End of Table" in table head?

*Use of the ltablex package can be tricky.

*Package tabu is buggy and not maintained. Don't use it. Instead it try to use relative new, powerful package tabularray.

*You need to cleanup your document preamble:

*

*each packages should be loaded only once

*package hyperref should be loaded last (with rare exception which is not present in your document)

*do you really need all these packages?

*You should be aware that long table can be broken between pages only between rows.

An example of table using longtblr of tabularray package, where some rows are repeated that table is long enough to span over two pages, is:
\documentclass{article}
\usepackage[margin=1in]{geometry}
\usepackage{tabularray}
\UseTblrLibrary{booktabs}  % it load package booktabs,
                            % so delete its other loads

\begin{document}
\noindent\begin{longtblr}[
caption={Description of the selected algorithms},
  label={TABLEA}        ]{hlines, vlines,
                         colspec={*2{X[j]}},
                         row{1} = {c, font=\bfseries},
                         rowhead=2,
                         hspan=minimal}
% table body
Algorithm       & General Operation     \\
\SetCell[c=2]{c,font=\bfseries}    Agglomerative methods
                &                       \\
\SetCell[c=2]{c}    The notion of distance in this family makes it possible to identify cliques through relational proximities
                &                       \\
\textbf{Hierarchical algorithm} with 4 different settings:  Euclidean distance / Complete linkage; Euclidean distance / Ward; Manhattan distance / Complete linkage; Manhattan distance / Ward.
                &   The basic idea is to construct the hierarchical relationship among data in order to cluster. Each data point stands for an individual cluster in the beginning, and then, the most neighboring two clusters are merged into a new one until there is only one cluster left. The concept of "neighborhood" depends on the distance between nodes which is computed by squaring the Euclidean or Manhattan distances and grouping them into a symmetric matrix. The clustering method (here, complete linkage and Ward's algorithm) identifies the closest nodes to agglomerate them. We obtain a hierarchical dendogram which is cut to the desired number of clusters. \\

\SetCell[c=2]{c,font=\bfseries}    Agglomerative methods
                &                       \\
\SetCell[c=2]{c}    The notion of distance in this family makes it possible to identify cliques through relational proximities
                &                       \\
\textbf{Hierarchical algorithm} with 4 different settings:  Euclidean distance / Complete linkage; Euclidean distance / Ward; Manhattan distance / Complete linkage; Manhattan distance / Ward.
                &   The basic idea is to construct the hierarchical relationship among data in order to cluster. Each data point stands for an individual cluster in the beginning, and then, the most neighboring two clusters are merged into a new one until there is only one cluster left. The concept of "neighborhood" depends on the distance between nodes which is computed by squaring the Euclidean or Manhattan distances and grouping them into a symmetric matrix. The clustering method (here, complete linkage and Ward's algorithm) identifies the closest nodes to agglomerate them. We obtain a hierarchical dendogram which is cut to the desired number of clusters. \\

\SetCell[c=2]{c,font=\bfseries}    Agglomerative methods
                &                       \\
\SetCell[c=2]{c}    The notion of distance in this family makes it possible to identify cliques through relational proximities
                &                       \\
\textbf{Hierarchical algorithm} with 4 different settings:  Euclidean distance / Complete linkage; Euclidean distance / Ward; Manhattan distance / Complete linkage; Manhattan distance / Ward.
                &   The basic idea is to construct the hierarchical relationship among data in order to cluster. Each data point stands for an individual cluster in the beginning, and then, the most neighboring two clusters are merged into a new one until there is only one cluster left. The concept of "neighborhood" depends on the distance between nodes which is computed by squaring the Euclidean or Manhattan distances and grouping them into a symmetric matrix. The clustering method (here, complete linkage and Ward's algorithm) identifies the closest nodes to agglomerate them. We obtain a hierarchical dendogram which is cut to the desired number of clusters. \\
\end{longtblr}
\end{document}

Note:

*

*Table is modified that has form as are usual used at tables.

*In preamble are loaded only packages related to this table.

A: Insert \parbox inside \multicolumn. It will format texts similarly to regular paragraphs, most of all it will add line breaks if necessary. It is justified by default so you might need to add \centering, \raggedright etc. to format text.
I also added \strut at the beginning of the text, so that the row can be slightly extended creating a small vertical gap above. If you want larger gaps, add invisible bars instead. For instance, at the beginning of the text insert
\rule{0pt}{12pt}

and at the end of the text append
\rule[-6pt]{0pt}{6pt}

Finally, \parbox requires a mandatory argument: width. In your case, this is a width of the text body reduced by amount space occupied by rules and column separators in the table.
Here's the part of the table with the problematic \multicolumn

\documentclass{article}
\usepackage{tabularx}
\begin{document}
{\noindent
\begin{tabularx}{\textwidth}{| *2{X|}}
    \hline
    \multicolumn{2}{| c |}{Begin of Table} \\
    \hline
    Algorithm & General Operation \\
    \hline
    \multicolumn{2}{| c |}{End of Table} \\
    \hline
    \multicolumn{2}{| c |}{\textbf{Agglomerative methods}} \\
    \hline
    \multicolumn{2}{| c |}{%
        \parbox{\dimexpr\textwidth-2\tabcolsep-2\arrayrulewidth}{\strut
        The notion of distance in this family makes it possible to identify cliques through relational proximities}
    } \\
    \hline
\end{tabularx}\par}
\end{document}


text:
Q: Synchronous file download using WCF I have a WCF REST based service which downloads and stores video files in the web server machine. The maximum size of video files is around 1MB and the download is asynchronous at present.
Is it possible to use synchronous download and will a timeout occur if large number or requests are submitted almost simultaneously? If so is there a mechanism to handle the situation?

A: You could set up your service to act as a singleton.  WCF will handle the queueing of multiple calls.  A similar question can be found here, and may be of help.


text:
Q: How to add hamburger icon to navbar I am new into web development, I am learning CSS right now. I have chosen as project for beginning my personal portfolio.
I am creating an easy navigation bar, I wanted to add hamburger Icon, but when I have added Icon to navbar the icon is stack at the bottom of the navbar and the animation(the lines are crossed like X, when button is toggled). I want the Icon in the left corner of the navbar.
I have tried to add the Icon outside the list, to nav but it overflow
 tag, so I have tried to add to  parent, but it overflows the
 tag as well.

body {
  background: linear-gradient(180deg, rgb(70, 65, 70), rgb(172, 34, 32));
}

.menu {
  border: 2px solid white;
  position: sticky;
  display: flex;
  flex-direction: row;
  height: 95vh;
  width: 17%;
  background: linear-gradient(180deg, #241023ff, #6b0504ff);
  /*linear-gradient(180deg, #2274a5ff, #f75c03ff);*/
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
  transition: 0.5s;
}

.wrapper {
  width: 100%;
  margin: auto;
  display: flex;
  justify-content: flex-start;
}

.container {
  margin-top: 10px;
  width: 100%;
  height: 25px;
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  cursor: pointer;
}

.menu-logo {
  height: 3px;
  width: 30px;
  background-color: white;
}

.showmenu {
  width: 25%;
}

/* #endregion Toggle button animation*/

/* #region Hover effect*/

nav:hover,
nav:active {
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
}

li a:hover,
li a:active {
  font-weight: bold;
  border: 1px solid white;
  border-radius: 10px;
  background: rgb(246, 246, 246);
  transition: 0.5s;
}

li a:hover svg,
li a:active svg {
  fill: #f75c03ff;
}

li a:hover span,
li a:active span {
  color: #f75c03ff;
  stroke: #f75c03ff;
}

/* #endregion Hover effect*/

nav {
  width: 100%;
  display: list-item;
  text-align: center;
  justify-content: center;
}

/* #region Welcome text*/

nav .welcome-text {
  width: 100%;
  margin-left: auto;
  display: flex;
  justify-content: center;
  font-size: 3.5vw;
  margin-bottom: 60px;
  color: white;
  text-align: center;
}

/* #endregion Welcome text*/

/* #region Main content*/

/* #region Wave animation*/

.wave {
  width: 50%;
  animation-name: wave-animation;
  /* Refers to the name of your @keyframes element below */
  animation-duration: 2.5s;
  /* Change to speed up or slow down */
  animation-iteration-count: infinite;
  /* Never stop waving :) */
  transform-origin: 70% 70%;
  /* Pivot around the bottom-left palm */
  display: inline-block;
}

@keyframes wave-animation {
  0% {
    transform: rotate( 0.0deg)
  }
  10% {
    transform: rotate(14.0deg)
  }
  /* The following five values can be played with to make the waving more or less extreme */
  20% {
    transform: rotate(-8.0deg)
  }
  30% {
    transform: rotate(14.0deg)
  }
  40% {
    transform: rotate(-4.0deg)
  }
  50% {
    transform: rotate(10.0deg)
  }
  60% {
    transform: rotate( 0.0deg)
  }
  /* Reset for the last half to pause */
  100% {
    transform: rotate( 0.0deg)
  }
}

/* #endregion Wave animation*/

nav ul {
  width: 100%;
  height: 100%;
  display: list-item;
}

nav ul li {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
}

li a {
  width: 100%;
  height: 7%;
  text-decoration: none;
  display: flex;
  text-align: left;
  font-size: 100%;
  justify-content: center;
  margin-bottom: 10px;
}

li a span {
  width: 100%;
  font-size: 2.7vw;
  align-self: center;
  color: white;
  margin-left: 10px;
}

li a svg {
  width: 20%;
  height: 20%;
}

    <input class="checkbox" type="checkbox" name="" id="" />

Welcome

          <svg viewBox="0 0 24 24" fill="transparent" stroke="white" xmlns="http://www.w3.org/2000/svg">
                                <path
                                    d="M21 8.77217L14.0208 1.79299C12.8492 0.621414 10.9497 0.621413 9.77817 1.79299L3 8.57116V23.0858H10V17.0858C10 15.9812 10.8954 15.0858 12 15.0858C13.1046 15.0858 14 15.9812 14 17.0858V23.0858H21V8.77217ZM11.1924 3.2072L5 9.39959V21.0858H8V17.0858C8 14.8767 9.79086 13.0858 12 13.0858C14.2091 13.0858 16 14.8767 16 17.0858V21.0858H19V9.6006L12.6066 3.2072C12.2161 2.81668 11.5829 2.81668 11.1924 3.2072Z" />
                            </svg>
          Home

Full code here:
https://jsfiddle.net/Lhawck59/

A:
,
You didn't write a closing  tag for this tag, so your code didn't work

A: you can add oppacity: 0; on the class menu, and add oppacity: 1; on the class showmenu

 var logo = document.querySelector('.container');
    var menu = document.querySelector('.menu');

    logo.addEventListener('click',function(){
        menu.classList.toggle('showmenu');
    });
    body {
  background: linear-gradient(180deg, rgb(70, 65, 70), rgb(172, 34, 32));
}

.menu {
  border: 2px solid white;
  position: sticky;
  display: flex;
  flex-direction: row;

  height: 95vh;
  width: 17%;
  background: linear-gradient(180deg, #241023ff, #6b0504ff);
  /*linear-gradient(180deg, #2274a5ff, #f75c03ff);*/
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
  transition: 0.5s;
  opacity: 0;

}

/* #region Toggle button animation*/

.wrapper {
  width: 100%;
  margin: auto;
  display: flex;
  justify-content: flex-start;
}

.container {
  margin-top: 10px;
  width: 100%;
  height: 25px;
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  cursor: pointer;

}

.menu-logo {
  height: 3px;
  width: 30px;
  background-color: white;
}

.showmenu {
  width: 25%;
  opacity: 1;
}

/* #endregion Toggle button animation*/
/* #region Hover effect*/

nav:hover,
nav:active {
  border-top-right-radius: 10px;
  border-bottom-right-radius: 10px;
}

li a:hover,
li a:active {
  font-weight: bold;
  border: 1px solid white;
  border-radius: 10px;
  background: rgb(246, 246, 246);
  transition: 0.5s;

}

li a:hover svg,
li a:active svg {
  fill: #f75c03ff;

}

li a:hover span,
li a:active span {
  color: #f75c03ff;
  stroke: #f75c03ff;
}

/* #endregion Hover effect*/
nav {
  width: 100%;
  display: list-item;
  text-align: center;
  justify-content: center;

}

/* #region Welcome text*/
nav .welcome-text {
  width: 100%;
  margin-left: auto;
  display: flex;
  justify-content: center;
  font-size: 3.5vw;
  margin-bottom: 60px;
  color: white;
  text-align: center;

}

/* #endregion Welcome text*/

/* #region Main content*/

/* #region Wave animation*/
.wave {
  width: 50%;
  animation-name: wave-animation;
  /* Refers to the name of your @keyframes element below */
  animation-duration: 2.5s;
  /* Change to speed up or slow down */
  animation-iteration-count: infinite;
  /* Never stop waving :) */
  transform-origin: 70% 70%;
  /* Pivot around the bottom-left palm */
  display: inline-block;
}

@keyframes wave-animation {
  0% {
    transform: rotate(0.0deg)
  }

  10% {
    transform: rotate(14.0deg)
  }

  /* The following five values can be played with to make the waving more or less extreme */
  20% {
    transform: rotate(-8.0deg)
  }

  30% {
    transform: rotate(14.0deg)
  }

  40% {
    transform: rotate(-4.0deg)
  }

  50% {
    transform: rotate(10.0deg)
  }

  60% {
    transform: rotate(0.0deg)
  }

  /* Reset for the last half to pause */
  100% {
    transform: rotate(0.0deg)
  }
}

/* #endregion Wave animation*/

nav ul {

  width: 100%;
  height: 100%;
  display: list-item;

}

nav ul li {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;

}

li a {
  width: 100%;
  height: 7%;
  text-decoration: none;
  display: flex;
  text-align: left;
  font-size: 100%;
  justify-content: center;
  margin-bottom: 10px;

}

li a span {
  width: 100%;
  font-size: 2.7vw;
  align-self: center;
  color: white;
  margin-left: 10px;
}

li a svg {
  width: 20%;
  height: 20%;
}

/* #endregion Main content*/

/* #region footer of navbar*/
ul li div {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 7%;
  display: flex;
  flex-direction: row;
  text-align: left;
  justify-content: flex-start;
}

li div img {
  width: auto;
  height: auto;
  border-radius: 50%;
  border: 2px solid white;
}

nav div span {
  width: 100%;
  font-size: 0;
  align-self: center;
  color: white;
  margin-left: 10px;
  font-weight: bolder;
}

/* #endregion footer of navbar*/

/*TEST*/
.nav-container {

    display: flex;
    justify-content: space-between;
    align-items: left;
    width: 5%;

  }

.nav-container .checkbox {

    position: absolute;
    display: block;
    width: 5%;
    z-index: 5;
    opacity: 0;
    cursor: pointer;
  }
.nav-container .hamburger-lines {
    display: block;
    height: 26px;
    width: 32px;
    position: absolute;
    z-index: 2;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

.nav-container .hamburger-lines .line {
    display: block;
    height: 4px;
    width: 100%;
    border-radius: 10px;
    background: rgb(255, 255, 255);
  }

  .nav-container .hamburger-lines .line1 {
    transform-origin: 0% 0%;
    transition: transform 0.4s ease-in-out;
  }

  .nav-container .hamburger-lines .line2 {
    transition: transform 0.2s ease-in-out;
  }

  .nav-container .hamburger-lines .line3 {
    transform-origin: 0% 100%;
    transition: transform 0.4s ease-in-out;
  }

  .nav-container input[type="checkbox"]:checked ~ .menu-items {
    transform: translateX(0);
  }

  .nav-container input[type="checkbox"]:checked ~ .hamburger-lines .line1 {
    transform: rotate(45deg);
  }

  .nav-container input[type="checkbox"]:checked ~ .hamburger-lines .line2 {
    transform: scaleY(0);
  }

  .nav-container input[type="checkbox"]:checked ~ .hamburger-lines .line3 {
    transform: rotate(-45deg);
  }

  .nav-container input[type="checkbox"]:checked ~ .logo{
    display: none;
  }

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: 'Roboto', sans-serif;
    /*font-family: 'Noto Sans', sans-serif;*/
}
header{
    border: 1px solid black;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/content/content.css">
    <link rel="stylesheet" href="css/navbar/navbar.css">

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,700;1,300;1,500&display=swap" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link rel="stylesheet" href="css/navbar/hamburgerIcon/hamburgerIcon.css">
    <title>Portfolio</title>

Header

        <input class="checkbox" type="checkbox" name="" id="" />

Welcome

              <svg viewBox="0 0 24 24" fill="transparent" stroke="white" xmlns="http://www.w3.org/2000/svg">
                <path d="M21 8.77217L14.0208 1.79299C12.8492 0.621414 10.9497 0.621413 9.77817 1.79299L3 8.57116V23.0858H10V17.0858C10 15.9812 10.8954 15.0858 12 15.0858C13.1046 15.0858 14 15.9812 14 17.0858V23.0858H21V8.77217ZM11.1924 3.2072L5 9.39959V21.0858H8V17.0858C8 14.8767 9.79086 13.0858 12 13.0858C14.2091 13.0858 16 14.8767 16 17.0858V21.0858H19V9.6006L12.6066 3.2072C12.2161 2.81668 11.5829 2.81668 11.1924 3.2072Z" />
              </svg>
              Home

              <svg fill="transparent" stroke="white" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path d="M21 2H6a2 2 0 0 0-2 2v3H2v2h2v2H2v2h2v2H2v2h2v3a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1V3a1 1 0 0 0-1-1zm-8 2.999c1.648 0 3 1.351 3 3A3.012 3.012 0 0 1 13 11c-1.647 0-3-1.353-3-3.001 0-1.649 1.353-3 3-3zM19 18H7v-.75c0-2.219 2.705-4.5 6-4.5s6 2.281 6 4.5V18z" />
              </svg>
              Contact

              <svg fill="transparent" stroke="white" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M17 7C17 5.34315 15.6569 4 14 4H10C8.34315 4 7 5.34315 7 7H6C4.34315 7 3 8.34315 3 10V18C3 19.6569 4.34315 21 6 21H18C19.6569 21 21 19.6569 21 18V10C21 8.34315 19.6569 7 18 7H17ZM14 6H10C9.44772 6 9 6.44772 9 7H15C15 6.44772 14.5523 6 14 6ZM6 9H18C18.5523 9 19 9.44772 19 10V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V10C5 9.44772 5.44772 9 6 9Z" />
              </svg>
              My work

              <svg fill="transparent" stroke="white" xmlns="http://www.w3.org/2000/svg" class="bi bi-chat-dots-fill" viewBox="0 0 16 16">
                <path d="M16 8c0 3.866-3.582 7-8 7a9.06 9.06 0 0 1-2.347-.306c-.584.296-1.925.864-4.181 1.234-.2.032-.352-.176-.273-.362.354-.836.674-1.95.77-2.966C.744 11.37 0 9.76 0 8c0-3.866 3.582-7 8-7s8 3.134 8 7zM5 8a1 1 0 1 0-2 0 1 1 0 0 0 2 0zm4 0a1 1 0 1 0-2 0 1 1 0 0 0 2 0zm3 1a1 1 0 1 0 0-2 1 1 0 0 0 0 2z" />
              </svg>
              References

              <svg xmlns="http://www.w3.org/2000/svg" fill="white" class="bi bi-person-circle" viewBox="0 0 16 16">
                <path d="M11 6a3 3 0 1 1-6 0 3 3 0 0 1 6 0z" />
                <path d="M0 8a8 8 0 1 1 16 0A8 8 0 0 1 0 8zm8-7a7 7 0 0 0-5.468 11.37C3.242 11.226 4.805 10 8 10s4.757 1.225 5.468 2.37A7 7 0 0 0 8 1z" />
              </svg>
              About


text:
Q: R anova (aov) repeated measures gives same effect in different error sources I have a repeated measures design, where A and B are within-subjects factors. I tried
m1 <- aov(y ~ A * B + Error(subject/(A*B)))
summary(m1)

But the results came back:
Error: subject
          Df    Sum Sq   Mean Sq F value  Pr(>F)
A          1 176166607 176166607   20.89 0.00600 **
B          1 143823233 143823233   17.05 0.00909 **
Residuals  5  42166494   8433299
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Error: subject:A
      Df  Sum Sq Mean Sq F value Pr(>F)
A      1 2263122 2263122   4.404 0.0899 .
B      2 1056720  528360   1.028 0.4227
Residuals  5 2569581  513916
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Error: subject:B
              Df    Sum Sq   Mean Sq F value   Pr(>F)
B              3 2.531e+09 843650464  60.871 6.22e-10 ***
A:B            2 8.212e+07  41060723   2.963   0.0759 .
Residuals 19 2.633e+08  13859601
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Error: subject:A:B
          Df   Sum Sq Mean Sq F value Pr(>F)
A:B        3  2075177  691726   1.152  0.351
Residuals 21 12610432  600497

Error: Within
           Df    Sum Sq Mean Sq F value Pr(>F)
Residuals 477 442259616  927169

Why is each effect showing up with so many error terms? Am I misunderstanding something? Or am I doing something wrong?


text:
Q: Declaration of a doubly linked list in a structure Is this the correct procedure in declaring a doubly linked list within a structure.I'm using the structure to read in a text file if this has any relevance.
#define MAX 20
//struct to order contactList
struct contact
{
    string firstName[MAX],lastName[MAX],email[MAX],companyName[MAX];
    long phoneNum[MAX];
    struct listelement *link
    struct node *next;
    struct node *prev;

};

A: Probably not.  Normally, you'd use struct contact *next; struct contact *prev; since the items in the list are (probably) struct contact and not struct node.
Hence, I'd expect to see:
#define MAX 20
//struct to order contactList
struct contact
{
    string              firstName[MAX];
    string              lastName[MAX];
    string              email[MAX];
    string              companyName[MAX];
    long                phoneNum[MAX];    /* 20 phone numbers per contact — wow! */
    struct listelement *link;             /* Semi-colon added.  What is this for? */
    struct contact     *next;
    struct contact     *prev;
};

The email element of the structure is too short (my main email address wouldn't fit, for example; you need 32 bytes at least, I suggest).  That's an awful lot of phone numbers for a single contact.  Also, long will not store all 10-digit phone numbers.
It is not clear what the link element is for.  It presumably is part of a singly-linked list involving these structures.


text:
Q: Bootstrap Modal not popping up when clicking button I'm trying to add a modal when the user clicks on the 'Add' button under 'Categories.' When I use just the code for the modal in js fiddle, it works, but when I add all of the code from the current file, it doesn't. Have tried moving jquery cdn around and also making a separate div container for the modal, but not able to get it. Any help is appreciated.

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>Inventory Management System</title>

    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
      crossorigin="anonymous"
    />
    <link
      href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"
      rel="stylesheet"
    />

    <?php  include_once("./templates/header.php"); ?>

Profile Info

                 Brian Liang

 Admin

Last Login : xxxx-xx-xx

                Edit Profile

Welcome Admin,

New Orders

                      Here you can make new invoices and create new orders.

                    New Orders

Categories

                Here you can manage your categories and can add parent and sub
                categories

              Add
              Manage

Brands

                Here you can manage your brand and can add a new brand

              Add
              Manage

Products

                Here you can manage your products and can add new products

              Add
              Manage

Modal title

                <button
                  type="button"
                  class="close"
                  data-dismiss="modal"
                  aria-label="Close"
                >
                  ×
                </button>

...

                <button
                  type="button"
                  class="btn btn-secondary"
                  data-dismiss="modal"
                >
                  Close
                </button>
                <button type="button" class="btn btn-primary">
                  Save changes
                </button>

A: The code that you useis only available for Bootstrap 4, but in the header, you are including the Bootstrap 5 that have changed some parameters regarding modals :

*

*To trigger a modal:
 // OLD WAY
 data-toggle="modal"
 data-target="#exampleModal"
 // NEW WAY
 data-bs-toggle="modal"
 data-bs-target="#exampleModal"

*Declaring a modal :

Modal title

             <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

             ...

             <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
             <button type="button" class="btn btn-primary">Save changes</button>

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>Inventory Management System</title>

    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
      crossorigin="anonymous"
    />
    <link
      href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"
      rel="stylesheet"
    />

    <?php  include_once("./templates/header.php"); ?>

Profile Info

                 Brian Liang

 Admin

Last Login : xxxx-xx-xx

                Edit Profile

Welcome Admin,

New Orders

                      Here you can make new invoices and create new orders.

                    New Orders

Categories

                Here you can manage your categories and can add parent and sub
                categories

              Add
              Manage

Brands

                Here you can manage your brand and can add a new brand

              Add
              Manage

Products

                Here you can manage your products and can add new products

              Add
              Manage

Modal title

                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>

                ...

                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>

A: You are probably getting your bootstrap versions mixed up. I have tested your code using bootstrap 4 and bootstrap 5 and can confirm it works on bootstrap 4 but does not on bootstrap 5, you can fix your code easily by replacing your bootstrap 5 script imports with bootstrap 4, or you can port your code to bootstrap 5.
Bootstrap 5 recently changed the way modals are triggered, which is why it does not work on 5 but does work on 4.
The following head works for me

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Inventory Management System</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">


text:
Q: How can I refer to controls which are created runtime in c#? I have 2 tables in my database one of which holds things and the other prices. I designed a form which retrieves thing names as checkboxes and adds textboxes against them. They are all created in runtime when the form loads. They all are named in loops accordingly and when form loads I can see them arranged in  the way I wanted to. But I cannot refer them in design time in the form as you can see in below where TextBox1.Text is. May you suggest me how I can do this?. Thanks by now. Below is the code I wrote for controls:
public Form4()
{
    InitializeComponent();
    SqlConnection conn = new SqlConnection("Data Source=ZEFIRAN\\SQLEXPRESS; Initial Catalog=Lab; Integrated Security=true");
    conn.Open();
    string say = "SELECT COUNT(DISTINCT Thing) FROM Sale";
    SqlCommand cmd = new SqlCommand(say, conn);
    Int32 ts = Convert.ToInt32(cmd.ExecuteScalar());
    conn.Close();
    for (int i = 0; i < ts; i++)
    {
        TextBox tb = new TextBox();
        tb.Width = 50;
        tb.Height = 25;
        tb.Name = "TextBox" + (i + 1).ToString();
        tb.Text = i + 1 + ". Test";
        panel1.Controls.Add(tb);
        int x = 150;
        int y = 40;
        tb.Location = new System.Drawing.Point(x, 40 + i * y);
    }
    for (int i = 0; i < ts; i++)
    {
        TextBox tb = new TextBox();
        tb.Width = 50;
        tb.Height = 25;
        tb.Name = "TextBox" + (2 * i + 1).ToString();
        tb.Text = i + 1 + ". Test";
        panel1.Controls.Add(tb);
        int x = 210;
        int y = 40;
        tb.Location = new System.Drawing.Point(x, 40 + i * y);
    }
    List<string> seyler = new List<string>();
    conn.Open();
    string query = "SELECT Thing FROM Things ORDER BY TNo";
    using (SqlCommand cmdtest = new SqlCommand(query, conn))
    {
        using (SqlDataReader dr = cmdtest.ExecuteReader())
        {
            while (dr.Read())
            {
                seyler.Add(dr.GetString(0));
            }
        }
    }
    string toplam = "SELECT COUNT(Thing) FROM Things";
    SqlCommand tplm = new SqlCommand(toplam, conn);
    Int32 top1 = Convert.ToInt32(tplm.ExecuteScalar());
    for (int j = 0; j < top1; j++)
    {
        CheckBox chb = new CheckBox();
        panel1.Controls.Add(chb);
        int t = 50;
        int u = 40;
        chb.Location = new System.Drawing.Point(t, 40 + j * u);
        chb.Width = 100;
        chb.Height = 25;
        chb.Text = seyler[j];
        chb.Name = "cb" + (j + 1).ToString();
    }
    conn.Close();
    TextBox1.Text = "";
}


text:
Q: sequelize ORM asynchronous method calls How can I call methods asynchronously in sequelize ORM? (because I have to use returned value inside other methods).
user.dao.js:
var User = require('./user.model');

class UserDao {
constructor() {}

insert(user) {
    var pk;
    User.sync({ force: false }).then(() => {
        User.create(user).then(function(user) {
            console.log('Entry successful from dao: ' +
    JSON.stringify(user));
            //return generated pk
            pk = user.id;
            console.log('ID: ' + pk);
        });
    });
    return pk;
}

user.test.js:
class UserDaoTest {
constructor() {
    this.userDao = new UserDao();
    this.compare = new UtilsObject();
}

/*
    all CRUD method calls
*/
testAll() {
    this.testInsert();
    this.testUpdate();
    //this.testDelete();
    //this.testRead();
    //this.compare();
}

/*
    insert method
*/
testInsert() {
    // composite form
    var user = {
        name: 'nisha',
        email: 'nisha@gmail.com',
        phoneNo: 8978,
        picUrl: 'nisha',
        description: 'SI',
        status: 'active',
        waitingTime: 10,
        rating: 7
    };

    /*
        calling insert user with above data
    */
    var pk = this.userDao.insert(user);
    console.log('pk value: ' + pk);
    //var obj1 = this.userDao.readById(pk);
    console.log('obj1 value: ' + user);
    //this.testReadById(obj1);
}

testReadById(obj1) {
    var obj2 = this.userDao.readById(obj1);
    this.compare.compare(obj1, obj2);
    this.testDelete(obj1);
}
}

export default UserDaoTest;

Here in user.test.js, in testInsert() method want to get the value of pk which is returned from insert() method of user.dao.js, but right now I am getting pk value as undefined.

A: Use a promise chain.
Suppose you need to get an entry for a particular user & do some operations on it.
Model.User.findById(someId)
.then((user) => {
   // Do something with user.
})

You shouldn't be calling methods synchronously, NodeJs is not designed this way. It works with callbacks or promises.

A: Your code won't work because it is async code.
Watch the famous Youtube video about the event loop
But in short, if you will run the following example, which is like your code but without your logic:
var User = require('./user.model');

class UserDao {
constructor() {}

insert(user) {
    var pk;
    console.log('1');
    User.sync({ force: false }).then(() => {
        pk = 123;
        console.log('3');
    });
    console.log('2');
    return pk;
}

The variable pk will be undefined and your console will look like this:
1
2
3

If you want it to work, you should "wait" for the async functions like this:
var User = require('./user.model');

class UserDao {
    constructor() {}

    // @return Promise
    insert(user) {
         return User.sync({ force: false }).then(() => {
             return User.create(user)
         }).then((user) => {
             console.log('Entry successful from dao: ' + JSON.stringify(user));
             return user.id
         })
    }

And when you use it:
class UserDaoTest {
    constructor() {
        this.userDao = new UserDao();
        this.compare = new UtilsObject();
    }

    /*
        all CRUD method calls
    */
    testAll() {
        // if testInsert and testUpdate can run simultaneously you can keep it like this.
        // Otherwise, use Promise.then as well
        this.testInsert();
        this.testUpdate();
    }

    /*
        insert method
    */

    testInsert() {
        var user = {
            // ...
        };

        /*
            calling insert user with above data
        */
        this.userDao.insert(user).then((userId) => {
            // YOUR COMPARE CODE
        }).then(done); // Where done is a function to let you test framework that you async code is done
    }
}

export default UserDaoTest;

Another way of doing that is using the new async and await. That way you will get a code which is more readable and maintainable.
You can read more here