text:
Q: Total number of NEAR token staked in NEAR Blockchain I need to get the total number of NEAR token staked in NEAR Blockchain programmatically, like it is shown in the NEAR explorer(https://explorer.near.org/nodes/validators).
Total Staked in NEAR Blockchain
NEAR provides JSON RPC API(https://docs.near.org/api/rpc/setup) to get some of the details by hitting respective RPC endpoints.
For example, I am able to get the total number of NEAR token staked in a staking pool using below RPC constructs.
endpoint URL: https://rpc.mainnet.near.org
Header = {"Content-Type":"application/json"}
Body:
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "query",
  "params": {
    "request_type": "call_function",
    "finality": "final",
    "account_id": "staking pool id",
    "method_name": "get_total_staked_balance",
    "args_base64": '{"account_id": "staking account id"}' in base64 encoding
  }
}

But there is no similar details available to get Total NEAR Staked in NEAR Blockchain.
Would appreciate if someone could help me in this. Thanks.
Went through NEAR official API documentation(https://docs.near.org/api/rpc/setup), NEAR explorer codebase(https://github.com/near/near-explorer), NEAR core-contracts codebase(https://github.com/near/core-contracts)

A: You can use the method EXPERIMENTAL_validators_ordered:
curl --location --request POST 'https://archival-rpc.mainnet.near.org/' \
--header 'Content-Type: application/json' \
--data-raw '{
  "jsonrpc": "2.0",
  "id": "dontcare",
  "method": "EXPERIMENTAL_validators_ordered",
  "params": ["JD8o38fkxG34QsBS4ZwT8hieehNUeJMAPCgKGk6xnbuf"]
}'

This will return a list with all validators and their stake:
{
    "jsonrpc": "2.0",
    "result": [
        {
            "account_id": "figment.poolv1.near",
            "public_key": "ed25519:7RjyY1bRKDqkshbKZtgpQdwsdxou8j9my8g1hPKZ9ngM",
            "stake": "32093438089641651528322513598448",
            "validator_stake_struct_version": "V1"
        },
        {
            "account_id": "astro-stakers.poolv1.near",
            "public_key": "ed25519:2nPSBCzjqikgwrqUMcuEVReJhmkC91eqJGPGqH9sZc28",
            "stake": "25153541134999320232972613031893",
            "validator_stake_struct_version": "V1"
        },
        {
            "account_id": "bzam6yjpnfnxsdmjf6pw.poolv1.near",
            "public_key": "ed25519:2ZJqaaCAisK4u8E2i611zFfvNmrvevovnU3M7SpGHkLY",
            "stake": "23349905747168797648450246349622",
            "validator_stake_struct_version": "V1"
        },
        ...
   ]
}

You can also use near-cli: near validators current


text:
Q: How to display bootstrap slider image full screen without stretching on mobile device using img tag? I founded slider on this link (http://codepen.io/jpI/pen/rrVPZd). It's working for me on desktop but getting issue on mobile device.This slider is not display full screen on mobile.I tried below css and getting full screen but image is stretching.I have to display only center part of image.I am using img tag.Would you help me in this.
Thanks in advance
Css
//getting image full screen in mobile device.
 .carousel-inner>.item>img, .carousel-inner>.item>a>img{
  height: 100%;
    }

A: I've corrected your code a bit.
The main idea is to use backgrounds instead of imgs to achieve cover effect.
Here my fork http://codepen.io/g1un/pen/mArjzB
Here are corrections:
1. Changes from imgs to backgrounds
.carousel-inner .item {
/*   max-height: 680px; */
  height: 100vh;
  background: url('https://dl.dropboxusercontent.com/u/4357218/Assets/Images/Codepen/Bootstrap%20Carousel/slide-1.jpg') no-repeat center top;
  background-size: cover;
}

.carousel-inner .item:nth-child(2) {
  background-image: url('https://dl.dropboxusercontent.com/u/4357218/Assets/Images/Codepen/Bootstrap%20Carousel/slide-2.jpg');
}

.carousel-inner .item:nth-child(3) {
  background-image: url('https://dl.dropboxusercontent.com/u/4357218/Assets/Images/Codepen/Bootstrap%20Carousel/slide-3.jpg');
}

2. To center the title vertically on small screens
.carousel-caption {
  bottom: 36%;
}

@media screen and (min-width: 768px) {
  .carousel-caption {
    right: 20%;
    left: 20%;
  }
}

A:

Meow

Just Kitten Around

Meow

Just Kitten Around

Meow

Just Kitten Around

Use this it won't stretching on mobile

A: html {
    position: relative;
    min-height: 100%;
}
.carousel-fade .carousel-inner .item {
    opacity: 0;
    transition-property: opacity;
}
.carousel-fade .carousel-inner .active {
    opacity: 1;
}
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
    left: 0;
    opacity: 0;
    z-index: 1;
}
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
    opacity: 1;
}
.carousel-fade .carousel-control {
    z-index: 2;
}
@media all and (transform-3d),
(-webkit-transform-3d) {
    .carousel-fade .carousel-inner > .item.next,
    .carousel-fade .carousel-inner > .item.active.right {
        opacity: 0;
        -webkit-transform: translate3d(0, 0, 0);
        transform: translate3d(0, 0, 0);
    }
    .carousel-fade .carousel-inner > .item.prev,
    .carousel-fade .carousel-inner > .item.active.left {
        opacity: 0;
        -webkit-transform: translate3d(0, 0, 0);
        transform: translate3d(0, 0, 0);
    }
    .carousel-fade .carousel-inner > .item.next.left,
    .carousel-fade .carousel-inner > .item.prev.right,
    .carousel-fade .carousel-inner > .item.active {
        opacity: 1;
        -webkit-transform: translate3d(0, 0, 0);
        transform: translate3d(0, 0, 0);
    }
}
.item:nth-child(1) {
    background: url(https://ununsplash.imgix.net/photo-1417021423914-070979c8eb34?q=75&fm=jpg&s=55746bd56e02a131b1e48c12196ea866) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
.item:nth-child(2) {
    background: url(https://ununsplash.imgix.net/reserve/oY3ayprWQlewtG7N4OXl_DSC_5225-2.jpg?q=75&fm=jpg&s=85ab821f3fa535036a68155aab571bad) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
.item:nth-child(3) {
    background: url(https://unsplash.imgix.net/photo-1414073875831-b47709631146?q=75&fm=jpg&s=731b6d5150eea8bafa63ae8194e72ebd) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
.carousel {
    z-index: -99;
}
.carousel .item {
    position: fixed;
    width: 100%;
    height: 100%;
}
.title {
  text-align: center;
  margin-top: 20px;
  padding: 10px;
  text-shadow: 2px 2px #000;
  color: #FFF;
}

This is Awesome

redpajama_set_name: RedPajamaStackExchange


text:
Q: auto resize and align javascript for illustrator CS5 I am using illustrator CS5.
and I am using this javascript.
and I want to do, after this script, I want to align those two selections automatically top left of one of those.
How can I do?
var dia = new Window("dialog", "Resize", [0,0,300,170]);
dia.pane1 = dia.add("panel", [10,15,290,90], "Fit to...");
dia.radi1 = dia.pane1.add("radiobutton", [10,15,200,25], "Width");
dia.radi2 = dia.pane1.add("radiobutton", [10,40,200,50], "Height");
dia.bot1 = dia.add("button", [10,100,290,160], "do it", { name:"ok"});
dia.radi1.value = true;
dia.center();
dia.show();

sel = activeDocument.selection;
var Tmax = 0;
var Ymax = 0;
for (i = 0; i < sel.length; i++) {
    if (Tmax < sel[i].height) {
        Tmax = sel[i].height
    }
    if (Ymax < sel[i].width) {
        Ymax = sel[i].width
    }
}

for (i=0; i < sel.length; i++) {
    if (dia.radi2.value) {
        bairitu = Tmax / sel[i].height * 100;
    } else {
        bairitu = Ymax / sel[i].width * 100;
    }

    sel[i].resize(bairitu, bairitu, true, true, true, true, bairitu, Transformation.TOPLEFT);
}


text:
Q: Headers on CSS Columns I have a document that is displayed using CSS columns, as demonstrated here.  The contents of the jsFiddle:
HTML:

 [some sample content]

CSS:
.two-column {
    width: 610px;
    height: 300px;
    -webkit-column-width: 300px;
    -webkit-column-gap: 10px;
}

Obviously, this will only work for webkit browsers, remove/replace the prefix for other engines.
I wish to add a header to every column, but haven't found any documentation that seems relevant (searches are filled with hits for CSS and table columns, or visual "columns" as in 2- or 3-column page layout).
I can position things absolutely for every column with javascript, but I'm hoping that a cleaner, CSS solution exists.

A: I think you can do it like so:
https://jsfiddle.net/maxim_mazurok/ydcwzpra/1/

asd1

asd2

    The div.two-column element will be broken up into two columns via the column-width CSS rule. Notice how the image that is too large to fit fully on this column is pushed to the next.

    Here is some more text.

.two-column {
    width: 610px;
    height: 300px;
    -webkit-column-width: 300px;
    -webkit-column-gap: 10px;
}
.two-column2, .two-column2 > h1 {
    width: 610px;
    font-size: 20px;
    line-height: 20px;
    height: 20px;
    padding: 0;
    margin: 0;
    -webkit-column-width: 300px;
    -webkit-column-gap: 10px;
}

It is not perfect code, but hope you've got the idea.


text:
Q: Does the different partitions occupy the space of the hard disk with a order? Let's say the disk has the position from 0 to 4049 MB.
if the size of partition 1 is 50 MB, so it took the position from 0 to 49?
My assumption comes from the following story:
I am trying to back up my Linux System(a Raspberry PI). Then I googled how should I do it and shrink it to the size of it rather than back up the whole sd-card.
Then I found an answer says that I should at first check how big the boot partition and the main partition are (with gparted). Then run dd, e.g.
dd if=/dev/sdb of=sysbackup.img bs=1M count=1024

So this count is the same as the size of the two partitions.
But I thought dd just scan the whole disk in order. That means the partitions are also located actually in order?

A: Partition locations are described by partition tables. The two most common types of partition tables today are the Master Boot Record (MBR) and the GUID Partition Table (GPT). Details differ, but in both cases, a few sectors of the disk are set aside to describe where each individual partition begins and ends, as well as to hold additional metadata, such as a type code, a name (GPT only), and so on. An OS knows enough to look for a partition table on a disk, to figure out what type it uses (MBR, GPT, or something more exotic), and then to interpret a range of sectors as being a partition that's distinct from another range of sectors.
In the case of both MBR and GPT, the order of partitions in the partition table, and therefore the partition numbers assigned to them (/dev/sda1 vs. /dev/sda2, for instance) does not necessarily match the order in which partitions appear on the disk. That is, /dev/sda2 might occupy sectors 40 to 1,126,439, and /dev/sda1 could occupy sectors 1,126,440 to 15,628,053,134. There can also be unpartitioned space (analogous to parts of a bookshelf that hold no books), areas used by the partitioning system, etc. The start point of the first partition is not entirely standardized, although some values are more common than others. Thus, if your goal is to back up an entire disk, you have three choices:

*

*Whole-disk backup -- You can do a low-level backup (using dd or some other tool) of the entire disk, from sector 0 to the end of the disk. This will have the effect of backing up the partition table, the contents of all partitions, and everything in unpartitioned sections of the disk. When you restore such a backup, it will look just like the original to an OS (give or take questions of the disk model and exact disk size). This is a pretty "dumb" approach, in that it requires no knowledge of the partitions on the disk, what partition table is in use, etc. In part for this reason, it's also relatively inefficient -- you'll likely be backing up areas of the disk that aren't actually in use, which can increase the size of the backup beyond what you probably need. This very inefficiency, although often a drawback, can actually be an advantage in some cases, such as if the disk's data structures are badly damaged -- you can work on the backup to attempt to recover data without worrying about damaging the original. Likewise, you can back up an encrypted disk even if you don't have the decryption key.

*Whole-partition backup -- You can use dd or a similar tool to perform a "dumb" backup of each partition. When you restore the backup, you'll need to create a fresh partition table, which should probably match the original. Thus, you may need to back up the partition table itself, or at least record the sizes of each partition. (The dd backup file sizes may provide this information.) Like a whole-disk backup, such a backup is likely to be space-inefficient, unless most of the disk was unpartitioned and/or the partitions themselves were mostly full. It requires more "smarts" to restore, and as the restored disk might not exactly match the original, some OSes and tools might stop working. The disk might not be bootable, for instance. This approach is basically a compromise between the other two methods.

*Filesystem-aware backup -- In this approach, you use a tool that understands the filesystems in use on each partition -- that is, the tool reads NTFS, FAT, ext4fs, HFS+, or whatever filesystem each partition uses. This could be using something like cp, tar, or zip to back up files, using the OS itself to handle the filesystem; or it could be a filesystem-specific tool that can back up at a lower level, while omitting unused parts of the filesystem. Either way, this approach requires much more "smarts" than any other approach, but the advantage is that the backup is likely to be faster and consume less disk space. The drawback is that you'll need more "smarts" in the tool to restore the backup. You may need to take extra steps to make the restored disk bootable again, and you'll certainly need to either back up the partition table itself or know enough to re-create something compatible. This type of backup is a poor choice if the original filesystem has been damaged, since the tool that reads the filesystem might become confused, omit critical data, or even crash.

Which type of tool you'd want to use depends on your needs. If you want a fast backup or one that uses a minimal amount of space and if the original is intact, you'd want to use a filesystem-aware backup tool. If the disk is small or damaged, a whole-disk (or at least whole-partition) backup is likely to be better.
In the case of a whole-partition or filesystem-aware backup, you should back up the partition table. How to do this depends on the partition table type. In some cases, recording the output of a partitioning tool should be adequate. For instance, you could type sudo fdisk -l /dev/sda and cut-and-paste the output into a text file to record the partitioning data on /dev/sda. Some tools offer ways to record the data in more detail. For instance, my own GPT fdisk (gdisk, cgdisk, and sgdisk) enables backing up GPT data to a binary file. This is done with the b option on gdisk's main menu, with the "Backup" item in cgdisk, or with the -b/--backup command-line option to sgdisk. Whether a simple recording of a partitioning tool's display or a detailed binary backup file like what GPT fdisk produces is necessary depends on your needs, which you haven't specified in enough detail for me to provide advice.
For more on disk partitioning, see:

*

*The Wikipedia article on disk partitioning

*This Howto Geek article

*This LinuxBSDOS article


text:
Q: cant use latex in slader site to draw geometry shapes i use slader site which use latex to answer math question but i can't draw geometric axies nor electric diagrams, i tried to type some solution from stackExchange but it did't work can some one help me

A: I work for Slader as well (I am one of their moderators).
I would recommend to use Geogebra or Desmos to create geometric axes, because a lot of LaTeX packages are not implemented in the LaTeX editor used by the website (only the most used packages and commands have been implemented). I personally prefer to use Geogebra, which is also a lot quicker than using LaTeX.
Similarly, you could use a third-party tool to create electric diagrams. For example, iCircuit could be used (but you have to pay for this technology).
I hope this helps!
Kind Regards,
Sarah Schrijvers


text:
Q: How to reversibly store and load a Pandas dataframe to/from disk Right now I'm importing a fairly large CSV as a dataframe every time I run the script. Is there a good solution for keeping that dataframe constantly available in between runs so I don't have to spend all that time waiting for the script to run?

A: As already mentioned there are different options and file formats (HDF5, JSON, CSV, parquet, SQL) to store a data frame. However, pickle is not a first-class citizen (depending on your setup), because:

*

*pickle is a potential security risk. Form the Python documentation for pickle:

Warning The pickle module is not secure against erroneous or
  maliciously constructed data. Never unpickle data received from an
  untrusted or unauthenticated source.

*pickle is slow. Find here and here benchmarks.

Depending on your setup/usage both limitations do not apply, but I would not recommend pickle as the default persistence for pandas data frames.

A: The easiest way is to pickle it using to_pickle:
df.to_pickle(file_name)  # where to save it, usually as a .pkl

Then you can load it back using:
df = pd.read_pickle(file_name)

Note: before 0.11.1 save and load were the only way to do this (they are now deprecated in favor of to_pickle and read_pickle respectively).

Another popular choice is to use HDF5 (pytables) which offers very fast access times for large datasets:
import pandas as pd
store = pd.HDFStore('store.h5')

store['df'] = df  # save it
store['df']  # load it

More advanced strategies are discussed in the cookbook.

Since 0.13 there's also msgpack which may be be better for interoperability, as a faster alternative to JSON, or if you have python object/text-heavy data (see this question).

A: Pandas DataFrames have the to_pickle function which is useful for saving a DataFrame:
import pandas as pd

a = pd.DataFrame({'A':[0,1,0,1,0],'B':[True, True, False, False, False]})
print a
#    A      B
# 0  0   True
# 1  1   True
# 2  0  False
# 3  1  False
# 4  0  False

a.to_pickle('my_file.pkl')

b = pd.read_pickle('my_file.pkl')
print b
#    A      B
# 0  0   True
# 1  1   True
# 2  0  False
# 3  1  False
# 4  0  False

A: If I understand correctly, you're already using pandas.read_csv() but would like to speed up the development process so that you don't have to load the file in every time you edit your script, is that right? I have a few recommendations:

*

*you could load in only part of the CSV file using pandas.read_csv(..., nrows=1000) to only load the top bit of the table, while you're doing the development

*use ipython for an interactive session, such that you keep the pandas table in memory as you edit and reload your script.

*convert the csv to an HDF5 table

*updated use DataFrame.to_feather() and pd.read_feather() to store data in the R-compatible feather binary format that is super fast (in my hands, slightly faster than pandas.to_pickle() on numeric data and much faster on string data).
You might also be interested in this answer on stackoverflow.

A: Pickle works good!
import pandas as pd
df.to_pickle('123.pkl')    #to save the dataframe, df to 123.pkl
df1 = pd.read_pickle('123.pkl') #to load 123.pkl back to the dataframe df

A: Numpy file formats are pretty fast for numerical data
I prefer to use numpy files since they're fast and easy to work with.
Here's a simple benchmark for saving and loading a dataframe with 1 column of 1million points.
import numpy as np
import pandas as pd

num_dict = {'voltage': np.random.rand(1000000)}
num_df = pd.DataFrame(num_dict)

using ipython's %%timeit magic function
%%timeit
with open('num.npy', 'wb') as np_file:
    np.save(np_file, num_df)

the output is
100 loops, best of 3: 5.97 ms per loop

to load the data back into a dataframe
%%timeit
with open('num.npy', 'rb') as np_file:
    data = np.load(np_file)

data_df = pd.DataFrame(data)

the output is
100 loops, best of 3: 5.12 ms per loop

NOT BAD!
CONS
There's a problem if you save the numpy file using python 2 and then try opening using python 3 (or vice versa).

A: Another quite fresh test with to_pickle().
I have 25 .csv files in total to process and the final dataframe consists of roughly 2M items.
(Note: Besides loading the .csv files, I also manipulate some data and extend the data frame by new columns.)
Going through all 25 .csv files and create the dataframe takes around 14 sec.
Loading the whole dataframe from a pkl file takes less than 1 sec

A: Although there are already some answers I found a nice comparison in which they tried several ways to serialize Pandas DataFrames: Efficiently Store Pandas DataFrames.
They compare:

*

*pickle: original ASCII data format

*cPickle, a C library

*pickle-p2: uses the newer binary format

*json: standardlib json library

*json-no-index: like json, but without index

*msgpack: binary JSON alternative

*CSV

*hdfstore: HDF5 storage format

In their experiment, they serialize a DataFrame of 1,000,000 rows with the two columns tested separately: one with text data, the other with numbers. Their disclaimer says:

You should not trust that what follows generalizes to your data. You should look at your own data and run benchmarks yourself

The source code for the test which they refer to is available online. Since this code did not work directly I made some minor changes, which you can get here: serialize.py
 I got the following results:

They also mention that with the conversion of text data to categorical data the serialization is much faster. In their test about 10 times as fast (also see the test code).
Edit: The higher times for pickle than CSV can be explained by the data format used. By default pickle uses a printable ASCII representation, which generates larger data sets. As can be seen from the graph however, pickle using the newer binary data format (version 2, pickle-p2) has much lower load times.
Some other references:

*

*In the question Fastest Python library to read a CSV file there is a very detailed answer which compares different libraries to read csv files with a benchmark. The result is that for reading csv files numpy.fromfile is the fastest.

*Another serialization test
shows msgpack, ujson, and cPickle to be the quickest in serializing.

A: You can use feather format file. It is extremely fast.
df.to_feather('filename.ft')

A: https://docs.python.org/3/library/pickle.html
The pickle protocol formats:
Protocol version 0 is the original "human-readable" protocol and is backwards compatible with earlier versions of Python.
Protocol version 1 is an old binary format which is also compatible with earlier versions of Python.
Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes. Refer to PEP 307 for information about improvements brought by protocol 2.
Protocol version 3 was added in Python 3.0. It has explicit support for bytes objects and cannot be unpickled by Python 2.x. This is the default protocol, and the recommended protocol when compatibility with other Python 3 versions is required.
Protocol version 4 was added in Python 3.4. It adds support for very large objects, pickling more kinds of objects, and some data format optimizations. Refer to PEP 3154 for information about improvements brought by protocol 4.

A: Arctic is a high performance datastore for Pandas, numpy and other numeric data. It sits on top of MongoDB. Perhaps overkill for the OP, but worth mentioning for other folks stumbling across this post

A: pyarrow compatibility across versions
Overall move has been to pyarrow/feather (deprecation warnings from pandas/msgpack).  However I have a challenge with pyarrow with transient in specification Data serialized with pyarrow 0.15.1 cannot be deserialized with 0.16.0 ARROW-7961. I'm using serialization to use redis so have to use a binary encoding.
I've retested various options (using jupyter notebook)
import sys, pickle, zlib, warnings, io
class foocls:
    def pyarrow(out): return pa.serialize(out).to_buffer().to_pybytes()
    def msgpack(out): return out.to_msgpack()
    def pickle(out): return pickle.dumps(out)
    def feather(out): return out.to_feather(io.BytesIO())
    def parquet(out): return out.to_parquet(io.BytesIO())

warnings.filterwarnings("ignore")
for c in foocls.__dict__.values():
    sbreak = True
    try:
        c(out)
        print(c.__name__, "before serialization", sys.getsizeof(out))
        print(c.__name__, sys.getsizeof(c(out)))
        %timeit -n 50 c(out)
        print(c.__name__, "zlib", sys.getsizeof(zlib.compress(c(out))))
        %timeit -n 50 zlib.compress(c(out))
    except TypeError as e:
        if "not callable" in str(e): sbreak = False
        else: raise
    except (ValueError) as e: print(c.__name__, "ERROR", e)
    finally:
        if sbreak: print("=+=" * 30)
warnings.filterwarnings("default")

With following results for my data frame (in out jupyter variable)
pyarrow before serialization 533366
pyarrow 120805
1.03 ms ± 43.9 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
pyarrow zlib 20517
2.78 ms ± 81.8 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
msgpack before serialization 533366
msgpack 109039
1.74 ms ± 72.8 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
msgpack zlib 16639
3.05 ms ± 71.7 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
pickle before serialization 533366
pickle 142121
733 µs ± 38.3 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
pickle zlib 29477
3.81 ms ± 60.4 µs per loop (mean ± std. dev. of 7 runs, 50 loops each)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
feather ERROR feather does not support serializing a non-default index for the index; you can .reset_index() to make the index into column(s)
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=
parquet ERROR Nested column branch had multiple children: struct<x: double, y: double>
=+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+==+=

feather and parquet do not work for my data frame. I'm going to continue using pyarrow.  However I will supplement with pickle (no compression).  When writing to cache store pyarrow and pickle serialised forms.  When reading from cache fallback to pickle if pyarrow deserialisation fails.

A: A lot of great and sufficient answers here, but I would like to publish a test that I used on Kaggle, which large df is saved and read by different pandas compatible formats:
https://www.kaggle.com/pedrocouto39/fast-reading-w-pickle-feather-parquet-jay
I'm not the author or friend of author of this, hovewer, when I read this question I think it's worth mentioning there.

CSV: 1min 42s Pickle: 4.45s Feather: 4.35s Parquet: 8.31s Jay: 8.12ms
or 0.0812s (blazing fast!)


text:
Q: Is there a way to convert a CSV into XLS on Mac with VBscript code? I need a programmatic way to repeatedly convert a downloaded CSV into an XLS, essentially keeping the same name of the file and just replacing the XLS each time. I work on a Mac 10.12, and am well-versed in the command line, but haven't found an easy way to do this without having to download a third-party library. I found an answer that gave me a VBscript that I can use on PowerShell, but I need some help with it.
I've downloaded PowerShell and I'm able to use it in Terminal. I have this script from another StackOverflow question:
Dim file, WB

With CreateObject("Excel.Application")
    On Error Resume Next
    For Each file In WScript.Arguments
        Set WB = .Workbooks.Open(file)
        WB.SaveAs Replace(WB.FullName, ".csv", ".xlsx"), 51
        WB.Close False
    Next
    .Quit
End With

WScript.Echo "Done!"

What would be the command to execute this script (in PowerShell) with an argument?
I've tried a variation of execution commands but always get CommandNotFoundException, probably because I'm doing it super wrong. My ideal outcome here is that Desktop/data.csv can become Desktop/data.xls repeatedly, whether it's with this script or something infinitely easier for a Mac user.
Thank you!
*edited for specificity/simplification

A: I do not think that there is a native solution on Mac to do this.
The simplest solution I known is to use Gnumeric, an open-source spreadsheet which has a terminal interface.
To install Gnumeric using Homebrew:
brew install gnumeric

Then you can use in the Terminal:
for f in *.csv; do ssconvert $f ${f%.csv}.xls; done

If it is a requirement to use Powershell, this should also be working:
gci *.csv | %{ssconvert $_ ($_.BaseName + ".xls")}

You can also use the ImportExcel Module, as suggested, but to my knowledge it will only converts in .xlsx and not in .xls as asked:
Install-Module -Name ImportExcel -RequiredVersion 5.4.2
gci *.csv | %{Import-Csv $_ | Export-Excel ($_.basename + ".xlsx")}

Alternatively you can just change the extension from .csv to .xls, Excel will show an error message when the file is opened but will nonetheless do to the conversion by itself.


text:
Q: Form adding value from answer twice I am developing a form the should show a different result depending on your final score. Currently, it just shows the added score at the bottom and ONLY updates when you click on any of the radio inputs (Q1 or Q2).
While adding all values from the questions, if you fill in both Question 1 and Question 2, Question 3's value is doubled.
I assume it's something in the javascript function but how can I fix it?
https://jsfiddle.net/8rpqp8dm/7/

1. Com que frequência tem perdas de urina? (Escolha uma opção):

      <form>
        <input type="radio" name="q1" value="0"> Nunca

        <input type="radio" name="q1" value="1"> Uma vez por semana ou menos

        <input type="radio" name="q1" value="2"> Duas ou três vezes por semana

        <input type="radio" name="q1" value="3"> Uma vez por dia

        <input type="radio" name="q1" value="4"> Várias vezes por dia

        <input type="radio" name="q1" value="5"> Constantemente
      </form>

2. Gostaríamos de saber a quantidade de urina que acha que perde.
Que quantidade de urina costuma perder?
(Quer use ou não protecção) (Escolha uma opção)

      <form>
        <input type="radio" name="q2" value="0"> Nenhuma

        <input type="radio" name="q2" value="2"> Uma quantidade pequena

        <input type="radio" name="q2" value="4"> Uma quantidade moderada

        <input type="radio" name="q2" value="6"> Uma grande quantidade
      </form>

3. No geral, a perda de urina interfere muito no seu dia-a-dia?
Escolha entre 0 (nada) e 10 (bastante)

      <form>
        <input type="range" name="q3" id="q3" value="5" min="0" max="10" oninput="cOut.value = q3.value" style="width: 300px;">

        <output name="cOutName" id="cOut">5</output>
      </form>

A: total += +document.getElementById('q3').value;
you are using this line in each function so it will take the value of q3 for each checked option.
try this:-
var $inputs = $('.question input[type=radio]').on('change', function() {
        var total = 0;
        var q3 = document.getElementById('q3').value;
        $inputs.filter(':checked').each(function() {
            total += +this.value;

        });
        total += +q3 ;

        $('.result').text(total);
    });

A: Your q3 value is being doubled because when you have both questions checked, the loop to add the values of q1 and q2 to q3 is running twice as there are two checked items.
To solve this, pull this line:
    total += +document.getElementById('q3').value;
Out of the 'checked' loop and place it underneath.
Hope that helps!


text:
Q: No instance of type variable(s) T exist so that ID conforms to Comparable super T> I'm learning about generics and I don't know how to resolve a problem.
This is the code:
public abstract class AbstractMapService<T, ID> {

    protected Map<ID, T> map = new HashMap<>();

    Set<T> findAll(){
        return new HashSet<>(map.values());
    }

    T findById(ID id) {
        return map.get(id);
    }

    T save(ID id, T object){
       map.put(id, object);
       return object;
    }

    void deleteById(ID id){
        map.remove(id);
    }

    void delete(T object){
        map.entrySet().removeIf(entry -> entry.getValue().equals(object));
    }

    private Long getNextId() {
        return Collections.max(map.keySet()) + 1;
    }
}

And this is the error:
max(java.util.Collection<? extends T>) in Collections cannot be applied to (java.util.Set<ID>)

reason: no instance of type variable(s) T exist so that ID conforms to Comparable<? super T>

Can someone explain to me why I get this error and how to resolve it? Thank you!

A: This error means the elements in the parameter Collection of method Collections.max should implement interface Comparable. So it can use the compareTo to find the max elements in the Collection.
You can make it compile by declaring it this way:
public abstract class AbstractMapService<T, ID extends Comparable<ID>>

private ID getNextId() {
    return Collections.max(map.keySet());
}

but I do not think this make much sense.
You might want to re-consider your design. With your current code, the ID can be any type. For exmaple, it could be String. And this time, your getNextId should not return current maxID + 1, since the +1 is only make sense when your ID is a Number.

If ID is supposed to be Long, then you should not declare it as type parameter, you can write it this way:
public abstract class AbstractMapService<T> {

    protected Map<Long, T> map = new HashMap<>();

    Set<T> findAll(){
        return new HashSet<>(map.values());
    }

    T findById(Long aLong) {
        return map.get(aLong);
    }

    T save(Long aLong, T object){
       map.put(aLong, object);
       return object;
    }

    void deleteById(Long aLong){
        map.remove(aLong);
    }

    void delete(T object){
        map.entrySet().removeIf(entry -> entry.getValue().equals(object));
    }

    private Long getNextId() {
        return Collections.max(map.keySet()) + 1L;
    }
}


text:
Q: Versions of L'Hôpital's rule I am familiar with the following version of L'Hôpital's rule:
Let $f,g:I\to\Bbb R$ be differentiable on the interval $I$, further assume that $g'(x)\ne0$. Let $a\in I$ and assume the limit $\lim_{x\to a}\frac{f'(x)}{g'(x)} $ exists. If it is the case that $\lim_{x\to a}f(x)=\lim_{x\to a}g(x)=0$ or $\lim_{x\to a}g(x)=\infty$ then the limit $\lim_{x\to a}\frac{f(x)}{g(x)}$ exists, and it coincides with $\lim_{x\to a}\frac{f'(x)}{g'(x)} $. Now my question is, why do such an overwhelming number of books state the theorem with the requirement that $\lim_{x\to a}f(x)=\lim_{x\to a}g(x)=0$ or $\lim_{x\to a}f(x)=\lim_{x\to a}g(x)=\infty$? In the latter case, $\lim_{x\to a}f(x)=\infty$ is really not needed. But I have seen the theorem stated like this even in non introductory books. What's the deal? thanks

A: Your question is really a pedagogical question, not an analysis question.
First, you're right: when $g(x) \rightarrow \infty$ the condition $f(x) \rightarrow \infty$ is not needed: a statement of the result in this form can be found in Rudin's Principles of Mathematical Analysis.  So why is this condition included in most elementary treatments, e.g. virtually all freshman calculus books?
As a veteran instructor of freshman calculus, I can say that L'Hopital's Rule is such a source of confusion and pitfalls to students that I almost wish we didn't cover it at all.  The statement is simply too subtle, and students often misuse it.  (Congratulations by the way on stating it correctly!)
We generally present the rule in the context of a larger discussion of Indeterminate Forms, i.e., limits like $0/0$ and $\infty/\infty$ which cannot be evaluated from the above form but depend on the actual functions involved.  In freshman calculus it is relatively rare that $\lim_{x \rightarrow a} f(x)$ simply does not exist, and if the limit is some finite number $L$ then $L/\infty$ is not an indeterminate form: it is always $0$.  Thus in practice one would not use this extension of the rule in freshman calculus, and including it would run the serious risk of further confusing students on the concept of an indeterminate form.
(Nevertheless I state the rule this way in my honors calculus notes.)
It would be interesting to see as a rebuttal, an example of a limit that can be computed by this "freshman excluded" case of L'Hopital and cannot otherwise be easily computed by the methods of freshman calculus.  Can anyone think of a natural example, one that could conceivably be shown to freshman calculus students?


text:
Q: Configuring pysparkling logger with custom format I'm trying to productionize Python Sparkling Water application and I want to unify logging formats from my app, Spark and H2O.
I was able to modify log4j.properties in Spark home and achieve it with Spark logs, however, H2O logs doesn't have format applied (i.e. timestamp, severity are missing).
How to do it?

A: It looks like guys from H2O didn't hear about logging module: https://github.com/h2oai/h2o-3/blob/master/h2o-py/h2o/model/metrics_base.py#L669... They are happily print messages instead of use proper logging. It's sad.


text:
Q: Color of Python Comment Keywords in Latex if have the following problem.
I have to insert Python Code in Latex.
I copied a nice code for Latex which creates a good looking Python output for my purposes.
Now I have the problem that I defined a certain color for programming keywords like "for, and,..."
But Latex, of course, displays also the and's and for's that I used in the comment section in Python after the # sign in this color.
Is there any way to change this?
Best
Felix

A: Use \lstset. Here is a MWE:
\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}

\definecolor{keywords}{RGB}{255,0,90}
\definecolor{comments}{RGB}{0,0,113}
\definecolor{red}{RGB}{160,0,0}
\definecolor{green}{RGB}{0,150,0}

\begin{document}

\lstset{language=Python,
        basicstyle=\ttfamily\small,
        keywordstyle=\color{keywords},
        commentstyle=\color{comments},
        stringstyle=\color{red},
        showstringspaces=false,
        identifierstyle=\color{green},
        keywords=[2]{pow},
        keywordstyle=[2]{\color{orange}},
}

\begin{lstlisting}
#This is a comment with keywords: and or for in range
n = 5
for i in range(0, n):
    print( pow(i,3) )
#Over and out
\end{lstlisting}

\end{document}

The above code will give you this:


text:
Q: Efficient Socket.io distribution with Mongoose stream I'm trying to create an efficient streaming node.js app, where the server would connect to a stream (capped collection) in MongoDB with mongoose, and then emit the stream directly to the client browsers.
What I'm worried about is the scalability of my design. Let me know if I'm wrong, but it seems that right now, for every new web browser that is opened, a new connection to MongoDB will also be opened (it won't re-use the previously utilized connection), and therefore there will be a lot of inefficiencies if I have a lot of user connected at the same time. How can I improve that?
I'm thinking of a one server - multiple client type of design in socket.io but I don't know how to achieve that.
Code below:
server side (app.js):
io.on('connection', function (socket) {
  console.log("connected!");
  var stream = Json.find().lean().tailable({ "awaitdata": true, numberOfRetries: Number.MAX_VALUE}).stream();
  stream.on('data', function(doc){
    socket.emit('rmc', doc);
  }).on('error', function (error){
    console.log(error);
  }).on('close', function () {
    console.log('closed');
  });
});

client side (index.html):
socket.on('rmc', function(json) {
  doSomething(); // it just displays the data on the screen
});

A: Unfortunately this will not depend only on mongo performance . unless you have a high level of concurrency (+1000 streams) you shouldn't worry about mongo (for the moment).
because with that kind of app you have bigger problems example: the data type and compression , buffer overflows , bandwith limit , socket.io limits , os limits . These are the kind of problems you will most likely face first.
now to answer your question. As far as i know no you are not opening a connection to mongo per user. the users are connected to the app not the database . the app is connected with the database.
lastly , these links will help you understand and tweak your queries for this kind of job (streaming)
https://github.com/Automattic/mongoose/issues/1248
https://codeandcodes.com/tag/mongoose-vs-mongodb-native/
http://drewww.github.io/socket.io-benchmarking/
hope it helps !


text:
Q: What is the error in it and it is very simple, error is showing in the last 'end' statement. What is the error There is an error in this code. How can I find it out?
CREATE DEFINER=`root`@`localhost` TRIGGER `check` BEFORE INSERT ON `whatstore` FOR EACH ROW
 BEGIN
    declare last_insert_time datetime;
    declare new_insert_time datetime;
    set @last_insert_time=(select insert_time from whatstore order by id desc limit 1);
    select datediff(new.insert_time,@last_inserted_time) into new_insert_time;
    case
        when last_insert_time-new.insert_time>1 then insert into `delete`.table3(time_diff)  values(new_inserted_time);
    end
END

A: Your code has a CASE statement, not a CASE expression.
I would advise you to just use IF, but you can adjust your code with END CASE:
 begin
    declare last_insert_time datetime;
    declare new_insert_time datetime;

    set @last_insert_time = (select insert_time from whatstore order by id desc limit 1);

    select datediff(new.insert_time, @last_inserted_time) into new_insert_time;

    case when last_insert_time - new.insert_time > 1
         then insert into `delete`.table3 (time_diff)
                  values (new_inserted_time);
    end case;
end;

It seems simpler to write this with no conditional logic:
insert into `delete`.table3 (time_diff)
    select w.last_insert_time
    from (select insert_time
          from whatstore
          order by id desc
          limit 1
         ) w
    where w.last_insert_time > new.insert_time;


text:
Q: PowerShell Script in Task Scheduler with Async Function I have a fairly large PowerShell script that I've broken into two separate scripts. The first script ends with a call to an async function and then exits.
The function checks on the status of an e-mail export that was generated in the previous script, performing a WHILE loop where it makes a call to Google every sixty seconds to see if the export is ready. Once the export is ready it updates a couple of SQL dbs and my second script knows to take over.
This works 100% of the time when I run the "first script" in the shell/console. But I've started noticing that when my scheduled task is triggered in Task Scheduler that... nothing happens. I have extensive logging, so I know that the parameters ARE being sent over to the async function, but it seems to just poop out rather than continue to loop through the WHILE and do the every-sixty-second checks.
I feel like I've done my due diligence in Googling here, but... is there something I'm missing with a Task Scheduler job to ensure that a function containing a WHILE loop will properly run?
EDIT BELOW
To better explain what I'm doing I will include stripped code from my function and the call to the function from the main script below.
First, the call to the function at the very end of "script_01."
# Let's send the Google Vault export information over to our function.
        Try {
            $VaultParameters = @{
                employee_name = "$employee_name"
                export_name = "$export_name"
                sql_id = "$sql_id"
                vault_status_id = "$vault_status_id"
            }
            VaultExport @VaultParameters

            $LoggingParameters = @{
                logfile = "C:\script_logs\log.log"
                log = "INFO: Sent the Google Vault export information over to our async function."
            }
            EventLogging @LoggingParameters
        } Catch {
            $LoggingParameters = @{
                logfile = "C:\script_logs\log.log"
                log = "ERROR: Could not send the Google Vault export information over to our async function.`n$_"
            }
            EventLogging @LoggingParameters
        }

And now the function itself. It is large...
function VaultExport {
    param (
        [cmdletbinding()]
        [parameter()]
        [string]$employee_name,
        [parameter()]
        [string]$export_name,
        [parameter()]
        [string]$sql_id,
        [parameter()]
        [string]$vault_status_id
    )

    $scriptBlock = {
        param ($employee_name,$export_name,$sql_id,$vault_status_id)
        Import-Module SimplySQL
        $logfile = "C:\script_logs\log.log"
        $now = (Get-Date).tostring("MM-dd-yyyy hh:mm:ss")

        # Let's define our MySQL database credentials for later use.
        # DEFINING SQL CREDS HERE

        # Let's generate secure credentials for our MySQL 'terms' db.
        # GENERATING SECURE CREDS HERE

        # And now we'll connect to our SQL db...
        # CONNECTING TO SQL HERE

        $vault_ready = "no"
        Add-Content $logfile "$now INFO: Beginning the WHILE loop while $export_name completes..."
        while ($vault_ready -eq "no") {
            $vault_status = gam info export "Email Exports" "$export_name"
            $vault_status = $vault_status -Match "COMPLETED"
            $vault_status = $vault_status -split(": ")
            $vault_status = $vault_status[1]
            if ($vault_status -eq "COMPLETED") {
                $vault_ready = "yes"
                $completed = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
                Invoke-SqlUpdate -Query "UPDATE ``table`` SET ``vault_status`` = '$vault_status', ``vault_completed`` = '$completed' WHERE ``id`` = '$vault_status_id'"
                Invoke-SqlUpdate -Query "UPDATE ``table`` SET ``vault_status`` = '1' WHERE ``id`` = '$sql_id'"
                $now = (Get-Date).tostring("MM-dd-yyyy hh:mm:ss")
                Add-Content $logfile "$now INFO: $export_name is ready to download. Updated vault_status in our dbs."
            } else {
                $vault_status = gam info export "Email Exports" "$export_name"
                $vault_status = $vault_status -Match "IN_PROGRESS"
                $vault_status = $vault_status -split(": ")
                $vault_status = $vault_status[1]
                Invoke-SqlUpdate -Query "UPDATE ``table`` SET ``vault_status`` = '$vault_status' WHERE ``id`` = '$vault_status_id'"
                $now = (Get-Date).tostring("MM-dd-yyyy hh:mm:ss")
                Add-Content $logfile "$now INFO: $export_name is not yet ready: ($vault_status). Checking again in sixty seconds."
                Start-Sleep 60
            }
        }
    }
    Start-Job -ScriptBlock $scriptBlock -ArgumentList @($employee_name,$export_name,$sql_id,$vault_status_id)
}
exit

A: I'm unsure why you wouldn't just have the task execute every 30 seconds instead of having a process run indefinitely and using it's own timers
The condition you are setting for the WHILE statement is being met, this is why the loop doesn't continue.
Change the condition to something that will never be met and the problem should go away, i.e.
$Value1 = 0
WHILE($Value1 -ne 1){
#do things, never updating the $value1 variable
}


text:
Q: Jsoup java не подгружаются некоторые элементы Парсю сайт с ценами на бензин , вот мой код:
Document doc = Jsoup.connect(BENZ_URL).userAgent(userAgent).get();
    Elements elements = doc.getElementsByClass("grid-item");

    for (Element element : elements) {
        Elements ai98 = element.select("div[class=item ai98]");
        System.out.println(ai98.toString());

    }

В браузере div с ценами отображается корректно:

Однако Jsoup распарсивает его так:

</div

Как решить эту проблему?

A: Вам нужно парсить не сам сайт а данную страницу


text:
Q: How does jackson implement json transfer to object I'm trying to test jackson. I have a class that no setters and no constructors with params(only have a default constructor and getters).
Code like the following:
public class BeanA {
  private int attr1;
  private int attr2;

  public BeanA(){
  }

  public int getAttr1(){
    return attr1;
  }

  public int getAttr2(){
    return attr2;
  }

}

I used jackson to transfer json to BeanA.jackson can work well.
I can't understand jackson how to assign values without setter and constructor.

A: Using reflection, by assigning to the fields directly.
Example of what it's doing internally:
Object o = BeanA.class.newInstance();
Field attr1 = BeanA.class.getDeclaredField("attr1");
attr1.setAccessible(true);
attr1.set(o, 42);
System.out.println(((BeanA) o).getAttr1());

A: As mentioned by @JB User there are various configuration & defaults Jackson apply for serialization/deserialization. Have look at the below links
http://wiki.fasterxml.com/JacksonFeaturesSerialization and
http://wiki.fasterxml.com/JacksonFeatureAutoDetect
If you override the Feature "CAN_OVERRIDE_ACCESS_MODIFIERS" to false you will get the error you expected.


text:
Q: Methods for showing that 4 points lie on the same circle? I'm looking for commonly used methods in contest geometry to show that 4 point lie on the same circle. Are there any tricks besides using the fact that the angles across add up to 180°?

A: If the coordinates of the four different
points are known, then they are
concyclic points if and only
if the following determinant is zero.
$$0 = \begin{vmatrix}
x_1^2+y_1^2&x_1&y_1&1\\
x_2^2+y_2^2&x_2&y_2&1\\
x_3^2+y_3^2&x_3&y_3&1\\
x_4^2+y_4^2&x_4&y_4&1
\end{vmatrix}$$
This is a consequence of the general equation of a circle being
$$ 0 = (x^2 + y^2) + ax + by + c. $$

A: We can prove that quadrilateral $ABCD$ is cyclic by infinitely many methods:

*

*If there is a point $O$ in the plane of the quadrilateral $ABCD$ such that $OA=OB=OC=OD$, so $ABCD$ is cyclic;

*If midperpendiculars to sides of quadrilateral $ABCD$ are intersected in the same point, so $ABCD$ is cyclic;

*If for quadrilateral $ABCD$ we have $\measuredangle ABD=\measuredangle ACD,$ so $ABCD$ is cyclic;

*Let for quadrilateral $ABCD$ we have $AB\cap CD=\{P\},$ $B$ and $C$ be midpoints of $PQ$ and $PR$ respectively, $AM$ and $DM$ be perpendiculars to $AB$ and $CD$ respectively. Now,  if $M\in QR$, so $ABCD$ is cyclic;
$$\bullet$$
$$\bullet$$
$$\bullet$$

A: Here is a way to tell from the distances between the points without knowing their rotational order.
Leg $d_{ij}$ be the distance between two points $i$ and $j$.  By Ptolemy's Theore, if the rotational order of the points is 1-2-3-4 then
$d_{13}d_{24}=d_{12}d_{34}+d_{14}d_{23}; d_{13}d_{24}-d_{12}d_{34}-d_{14}d_{23}=0$
For the other two possible rotational orders we get similar results:
$d_{12}d_{34}-d_{14}d_{23}-d_{13}d_{24}=0$
$d_{14}d_{23}-d_{13}d_{24}-d_{12}d_{44}=0$
Now take all three cases into account with one blow by multiplying the three zero factors together.  It looks inelegant, true --- unless we slip in an extra factor:
$d_{13}d_{24}+d_{12}d_{34}+d_{14}d_{23}=0$
The product of a four factor equations is then a simple form that involves only even powers:
$(d_{12}d_{34})^4+(d_{13}d_{24})^4+(d_{14}d_{23})^4-2(d_{12}d_{34})^2(d_{13}d_{24})^2-2(d_{13}d_{24})^2(d_{14}d_{23})^2-2(d_{14}d_{23})^2(d_{12}d_{34})^2=0$
$\color{blue}{(d_{12}d_{34})^4+(d_{13}d_{24})^4+(d_{14}d_{23})^4=2[(d_{12}d_{34})^2(d_{13}d_{24})^2+(d_{13}d_{24})^2(d_{14}d_{23})^2+(d_{14}d_{23})^2(d_{12}d_{34})^2]}$
With this formulation, you do not need square root extractions to get the even powers of the distances in the above expression.  You will, however, run into large numbers with seemingly small coordinates.  For instance, consider the four points
$1\to(0,5);2\to(5,0);3\to(3,4);4\to(3,-4).$ (They're "rigged" to lie on $x^2+y^2=5^2$).
Then from the Pythagorean formula for squared distance
$d_{12}^2=50,d_{13}^2=10,d_{14}^2=90,d_{23}^2=20,d_{24}^2=20,d_{34}^2=64$
And then
$(d_{12}d_{34})^4+(d_{13}d_{24})^4+(d_{14}d_{23})^4=3200^2+200^2+1800^2=\color{blue}{13520000}$
$2[(d_{12}d_{34})^2(d_{13}d_{24})^2+(d_{13}d_{24})^2(d_{14}d_{23})^2+(d_{14}d_{23})^2(d_{12}d_{34})^2]=2×[(3200×200)+(3200×1800)+(200×1800)]=\color{blue}{13520000}.$

A: Let the points be considered as lying on the complex plane, say, $z_1,z_2,z_3,z_4$. Then, consider the map (also called the cross ratio of $z,z_2,z_3,z_4$) given by,
$$
M(z)=\left(\frac{z-z_3}{z-z_4}\right)/\left(\frac{z_2-z_3}{z_2-z_4}\right).
$$
This is a Mobius transformation which sends $z_2,z_3,z_4$ to $1,0,\infty$ respectively. Since Mobius transformations preserve circles (including straight lines considered as circles), it maps the circle made by $z_2,z_3,z_4$ to the real axis. Also, Mobius transformations are invertible, hence, no other point which is not on the above circle will be mapped to the real axis.
Hence, if $M(z_1)$ is real, $z_1$ lies on the circle formed by $z_2,z_3,z_4$.
In conclusion,
if
$$
\left(\frac{z_1-z_3}{z_1-z_4}\right)/\left(\frac{z_2-z_3}{z_2-z_4}\right)
$$
is real, then $z_1,z_2,z_3,z_4$ lie on a circle.


text:
Q: How to format computer I used to dual boot? My Mint install is very slow on idle and my python is broken after downloading packages for python2 and 3 - all imports stopped working.
Currently I have windows10 and Mint on my machine, and I want to format my computer to wipe out both of these for a new lighter distribution of Linux, in which I can carefully set up virtual environments and virtual machines in order to not break my python install again.
Currently my disk is divided as so:

I believe FS3 is the Windows reserved partition, and FS5 is the Windows Disk. I have tried deleting the latter, to no avail.
If I format regularly with another distro, will all these disks be wiped out?


text:
Q: VBA login cant click button Everything works up until I try to click the button.  The button does not have a name so i tried to get it by class. Any suggestions?
Button:
<input type="button" value="Sign On" class="ButtonSm" onclick="submitForm();">

My Code:
Dim IE

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = 1
IE.navigate "www.xxx.com"

Do While (IE.Busy)
    Application.Wait DateAdd("s", 1, Now)

Loop

With IE.Document
        .getElementByID("USER").Value = UserName
        .getElementByID("PASSWORD").Value = Password
        .getElementByClassName("ButtonSm").Click
End With

End Sub

A: CSS selectors:
Try using a CSS selector to target the element.  The selector input[value='Sign On' targets the first element on the page found with input tag and having attribute value whose value is 'Sign On'.

Applying the selector with VBA:
Applied via the querySelector method of document.
IE.document.querySelector("input[value='Sign On']").Click

You may also try
IE.document.querySelector("input[value='Sign On']").FireEvent "onclick"

Other observations:
There is not enough HTML nor an URL to advise further. You could potentially just submit the form directly with:
IE.document.forms(formIndexGoesHere).Submit


text:
Q: Laravel Forge SSL Your connection is not private I am experincing a strange issue after deploying my site and installing a ssl certificate.
I contacted other people who live in other cities and they can access the website. However every time I access it I get:
Your connection is not private, NET::ERR_CERT_AUTHORITY_INVALID

I tried, clearing chrome cache, cookies..., reseting the dns resolver cache of my machine, emptying cache and hard reloading...
I am using Laravel Forge, Digital Ocean and a Comodo Certificate.
Regards,
Diego

A: There is no particular reason to suspect Laravel of causing this issue. One easy way to check is to upload a simple .txt file and then load that into your browser with https.
If the problem persists, then you should contact your host and ask them for assistance.


text:
Q: Starting thin server on different ports I'm a newbie o thin. I have a ruby on rails application. Today I can start the application normally, by the command
sudo thin start -d

We have created a new database for tests. (one is a clean database, and he other is for testing so can be messed up) on the database.yml file.
I would like to start the same application in two different ports using the different databases.
To start an application with the database I can use the ENV option of thin:
sudo thin start -d -e production -p 3040

It woks fine. But when I try to start the 'regular' server, it says thins is already running. How could I start both application in the ame thin command. Is there a way to make a configuration file for this?

A: Just to people know.
I found the solutions for this question. You CAN start the thin server on different ports with tha same application and with the same environment.
You just need to set different PID files by the -P (UpperCase) parameter.
Example:
Server 1 (port 3030, production environment, default pid, deattached)
thin start -e production -p 3030 -d

Server 2 (port 3040, production environment,"MY_PID.pid" pid file, deattached)
thin start -e production -p 3040 -P MY_PID.pid -d


text:
Q: pagination div pages with jquery With this script i try show pages inside divs with content, and move each time and the people wants see some page, can click over number page and load, the problem actually it´s when people click over number page, show more of 1 page, and not show the page´s number
TEST HERE :
https://jsfiddle.net/2mvek66f/

HTML CODE WITH PAGES
Pages:

1
2
3

When the people click over links in footer ,"gopage" must load the select div, but actually the problem in many cases, it´s that when click over pagination´s number, show more divs and not selected div


text:
Q: No extension to complex numbers? Complex numbers are 2D. It is a commonly cited result that there is no 3D or 4D analogue of the complex numbers.
I just want to be clear on exactly what this result says:

*

*It is impossible to construct a 4D field.

*It is impossible to construct a 4D field which the complex numbers are a subset of.

*It is impossible to construct a 4D field which the real numbers are a subset of.

*Something else?
(I'd also like to know why it's true - but given that I didn't understand the answer the first $2^7$ times, I doubt I'll understand it this time either. :-} Oh well...)

A: The field of rational functions is infinite-dimensional. It includes the complex and real numbers.
The same is correct about the field of analytic (holomorphic) functions.

A: It is impossible to have a field which is $n$ dimensional over $\mathbb{R}$ for any $n\geq 3$. The reason why this is true boils down to the following two statements.

*

*Any field $K\supseteq \mathbb{R}$ which is finite dimensional over $\mathbb{R}$ is algebraic over $\mathbb{R}$.

*The complex numbers are the algebraic closure of $\mathbb{R}$.

Thus is $K\supseteq \mathbb{R}$ is a field which is finite dimensional over $\mathbb{R}$, then it is algebraic over $\mathbb{R}$, and hence is contained in the algebraic closure of $\mathbb{R}$, i.e., $K\subseteq \mathbb{C}$. Since $\mathbb{C}$ has dimension $2$ over $\mathbb{R}$, this implies that $K$ has dimension either $1$ or $2$ over $\mathbb{R}$. In the first case, $K = \mathbb{R}$, and in the second $K = \mathbb{C}$.

A: Since $\mathbb{C}$ is algebraically closed, every finite extension of $\mathbb{C}$ is $\mathbb{C}$ itself. The quaternions are not a field because they are not commutative; they are what is called a normed division algebra. Hurwitz's theorem gives a complete description of the possible normed division algebras (over $\mathbb{R}$) - the are either the real numbers, the complex numbers, the quaternions or the octonions. Only the first two are fields, and only the first three are associative.
The nonexistence of a three-dimensional real normed algebra can be viewed as a consequence of the hairy ball theorem. If $\mathbb{R}^3$ could be given a normed division algebra structure, the unit sphere $S^2$ could be endowed with a smooth group structure (the elements of norm $1$ form a group). But the hairy ball theorem implies that there is no such thing, because otherwise, by letting an infinitesimal element of the group act on the left on the sphere, we would obtain a nowhere vanishing, continuous vector field on the sphere, which is impossible by the hairy ball theorem.

A: A question is, why one would need exactly a field. The bicomplex numbers aka tessarines are a commutative associative ring.
Yes, there are some elements that have no inverse, but that is not bad at all: dual numbers and split-complex numbers also have such elements.
Bicomplex numbers have subrings, isomorphic to complex numbers and hyperbolic (split-complex) numbers. They can be represented as commutative real matrices.
They are a really great thing, generalizing the various notions of complex number.


text:
Q: Duplicating each character for all permutations of a string This is a slightly odd/unique request. I am trying to achieve a result where e.g "yes" becomes, "yyes", "yees", "yess", "yyees", "yyess", "yyeess".
I have looked at this: Find all lowercase and uppercase combinations of a string in Javascript which completes it for capitalisation, however my understanding is prohibiting me from manipulating this into character duplication (if this method is even possible to use in this way).
export function letterDuplication(level: number, input: string){

const houseLength = input.length;
if (level == 1){

    var resultsArray: string[] = [];
    const letters = input.split("");
    const permCount = 1 << input.length;

    for (let perm = 0; perm < permCount; perm++) {
        // Update the capitalization depending on the current permutation
        letters.reduce((perm, letter, i) => {

        if (perm & 1) {
        letters[i] = (letter.slice(0, perm) + letter.slice(perm-1, perm) + letter.slice(perm));
        } else {
        letters[i] = (letter.slice(0, perm - 1) + letter.slice(perm, perm) + letter.slice(perm))

      }
          return perm >> 1;
        }, perm);

        var result = letters.join("");
        console.log(result);
        resultsArray[perm] = result;

    }

If I haven't explained this particularly well please let me know and I'll clarify. I'm finding it quite the challenge!

A: General idea
To get the list of all words we can get from ordered array of letters, we need to get all combinations of letters, passed 1 or 2 times into word, like:
word = 'sample'
array = 's'{1,2} + 'a'{1,2} + 'm'{1,2} + 'p'{1,2} + 'l'{1,2} + 'e'{1,2}

Amount of all possible words equal to 2 ^ word.length (8 for "yes"), so we can build binary table with 8 rows that represent all posible combinations just via convering numbers from 0 to 7 (from decimal to binary):
0 -> 000
1 -> 001
2 -> 010
3 -> 011
4 -> 100
5 -> 101
6 -> 110
7 -> 111

Each decimal we can use as pattern for new word, where 0 means letter must be used once, and 1 - letter must be used twice:
0 -> 000 -> yes
1 -> 001 -> yess
2 -> 010 -> yees
3 -> 011 -> yeess
4 -> 100 -> yyes
5 -> 101 -> yyess
6 -> 110 -> yyees
7 -> 111 -> yyeess

Code
So, your code representation may looks like this:

// Initial word
const word = 'yes';
// List of all possible words
const result = [];

// Iterating (2 ^ word.length) times
for (let i = 0; i < Math.pow(2, word.length); i++) {
    // Get binary pattern for each word
    const bin = decToBin(i, word.length);
    // Make a new word from pattern ...
    let newWord = '';
    for (let i = 0; i < word.length; i++) {
        // ... by adding letter 1 or 2 times based on bin char value
        newWord += word[i].repeat(+bin[i] ? 2 : 1);
    }
    result.push(newWord);
}

// Print result (all possible words)
console.log(result);

// Method for decimal to binary convertion with leading zeroes
// (always returns string with length = len)
function decToBin(x, len) {
    let rem, bin = 0, i = 1;
    while (x != 0) {
        rem = x % 2;
        x = parseInt(x / 2);
        bin += rem * i;
        i = i * 10;
    }
    bin = bin.toString();
    return '0'.repeat(len - bin.length) + bin;
}

A: Maybe this example can help you. It's a bit not neat and not optimal, but it seems to work:

function getCombinations(word = '') {
  const allCombination = [];
  const generate = (n, arr, i = 0) => {
    if (i === n) {
      return allCombination.push([...arr]);
    } else {
      arr[i] = 0;
      generate(n, arr, i + 1);
      arr[i] = 1;
      generate(n, arr, i + 1);
    }
  }
  generate(word.length, Array(word.length).fill(0));

  return allCombination.map((el) => {
    return el.map((isCopy, i) => isCopy ? word[i].repeat(2) : word[i]).join('')
  });
}

console.log(getCombinations('yes'));
console.log(getCombinations('cat'));


text:
Q: Как лучше всего передать огромное количество id'шников? Сайт построен на ASP и C# (это уже печалит).
Есть большая таблица. У каждой строки свой id. Нужно при нажатии на кнопку отправить список/массив этих id на сервер с помощью AJAX (метод GET).
Внимание, вопрос!
Каким образом лучше всего формировать строку данных в ajax'e для передачи на сервер? Можно ли там передавать/принимать массивы? Что делать, если количество id под сотню?
A: Составляйте json-ответ и принимайте его.
У меня по схеме - sql -> сервер -> mobile. Передается через json по 500кб быстро.


text:
Q: What is the dual norm of the norm induced by a convex body? Suppose $U\subset \mathbb{R}^n$ is a symmetric convex body. For $x\in\mathbb{R}^n$, the norm  of $x$ induced by $U$ is defined as
$$ \|x\|_U= \inf\{r>0:x/r \in U\}. $$
For norm $\|\cdot\|$ defined in $\mathbb{R}^n$, its dual norm is defined as
$$ \|x\|_* = \sup\{\langle z,x\rangle: \|z\|\leq 1\} $$
for $x \in \mathbb{R}^n$. What's the induced norm of $\|x\|_U$? Is it also an induced norm of some convex body?

A: The dual norm of $\|\cdot\|_U$ is the norm induced by the polar body of $U$. See Lemma 1.5 in these notes by Rothvoss. The definition of the polar body is in Definition 1.2 in the same notes.


text:
Q: three tables side by side on one page Hi does anyone know the easiest way to put 3 table side by side like in the figure below, but with only one caption at the bottom of these tables.

A: Maybe this is an awful and unpractical way to achieve what you want but here you go
\documentclass{article}

\begin{document}

\begin{table}
\centering
\begin{tabular}{
|c|c|c@{\hskip 1cm}
|c|c|c@{\hskip 1cm}
|c|c|c@{\hskip 1cm}
}
\cline{1-2}\cline{4-5}\cline{7-8}
Cell 1 & Cell 2 && Cell 3 & Cell 4 && Cell 5 & Cell 6 \\
\cline{1-2}\cline{4-5}\cline{7-8}
Cell 1 & Cell 2 && Cell 3 & Cell 4 && Cell 5 & Cell 6 \\
\cline{1-2}\cline{4-5}\cline{7-8}
Cell 1 & Cell 2 && Cell 3 & Cell 4 && Cell 5 & Cell 6 \\
\cline{1-2}\cline{4-5}\cline{7-8}
Cell 1 & Cell 2 && Cell 3 & Cell 4 && Cell 5 & Cell 6 \\
\cline{1-2}\cline{4-5}\cline{7-8}
Cell 1 & Cell 2 && Cell 3 & Cell 4 && Cell 5 & Cell 6 \\
\cline{1-2}\cline{4-5}\cline{7-8}
\end{tabular}
\caption{Caption here}
\end{table}

\end{document}

A: You can add only one caption command in the table float environment. As for three tables one by one, you can directly use the tabular environment.
    \documentclass[a4paper,10pt]{article}
    \begin{document}
    \begin{table}
      \centering
        \begin{tabular}{|c|c|}
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
        \end{tabular}
        \hfill
        \begin{tabular}{|c|c|}
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
        \end{tabular}
        \hfill
        \begin{tabular}{|c|c|}
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
          \hspace{4em}  &  \hspace{4em}   \\
          \hline
        \end{tabular}
      \caption{Three table}\label{tab}
    \end{table}
    \end{document}

gives


text:
Q: Import .cdr file into gis/cad format I have a Corel draw (.cdr) file that I would like to import into a GIS. It is a vector format which I think has no geographic information associated. I would like to be able to get it into MapInfo Professional and use the vector registering tools to place it correctly.
The problem I have is I cannot get it into .tab easily.
Does anyone know a way of getting it into any GIS/CAD format I could work with
Thanks,

A: Your best bet is to convert the corel draw file to a DXF and then import into MapInfo using universal translator.  Adobe Illustrator can export to DXF, although you may have trouble importing from Corel (this will depend on your version).  Try and split the document into layers from within a vector editor if you can, and convert them individually.
edit
As an alternative to illustrator you could use inkspace which has a dxf export plugin.
If you are working with polygons an alternative would be to set the color differently for each polygon and then create a very high resolution raster from within your vector editor.  This raster could then be georeferenced and vectorised.  This sound like a cludge but can yield surprisingly good results.  By rasterising you reduce the potential problems that could occur in the conversion process, and have a well understood work flow.

A: As it says the very 'best' way to convert cdr to dxf (then import in mapinfo with universal translator)
http://www.coreldrawtools.com/standard/index.html


text:
Q: Cannot remove additional information tab from product view in XML This is my xml :
<?xml version="1.0"?>
   <layout>
      <catalog_product_view>
        <reference name="product.info.tabs">
            <action method="unsetChild">
                <child>product_additional_data</child>
            </action>
        </reference>
       </catalog_product_view>
</layout>

I clear the cache but nothing happens. I want to remove the additional info tab, but keeps the description. What should I change or check ? thx
UPDATE
This is the xml from catalog.xml base:
   <block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml">
                    <action method="addToParentGroup"><group>detailed_info</group></action>
                    <action method="addToParentGroup"><group>detailed_info</group></action>
                    <action method="setTitle" translate="value"><value>Additional Information</value></action>
                </block>

A: Using this xml code I manage to remove the additional info tab:
<catalog_product_view>
   <remove name="product.attributes"/>
</catalog_product_view>

A: there are different way
Method 1:

Additional Information

Method 2
If you want the 'Additional Information' not to be shown on the product description,
find out attributes which 'Visible on Product View Page on Front-end' and 'Used in product listing' is set to 'Yes',
and then turn them to 'No'.
If all the attributes are set to 'No', then the 'Additional Information' tab will be disappeared.
Method 3:
local.xml

<catalog_product_view>
    <reference name="product.info.tabs">
        <action method="unsetChild">
            <child>product_additional_data</child>
        </action>
    </reference>
</catalog_product_view>

</layout>

Method 4:
commend catalog.xml
<action method="addTab" translate="title" module="catalog"><alias>additional</alias><title>Additional Information</title><block>catalog/product_view_attributes</block><template>catalog/product/view/attributes.phtml</template></action>

A: *

*Your syntax is  wrong:
<child>product_additional_data</child>
should be
<name>product_additional_data</name>

*

*You have using alias name instead of block name

      <block type="catalog/product_view_additional"
      name="product.info.additional" as="product_additional_data" />

Here
In your code you need to use :
<reference name="product.info.tabs">
        <action method="unsetChild"><name>product.info.additional</name></action>

</reference>


text:
Q: simple css failed to load in the run The below code is not working and I don't know why

          Facebook helps you connect and share with the people in
          your life.

A: Spelling errors- you're trying to style a class that doesn't exist (.gridient)


text:
Q: how to get user confirmation status from AWS Cognito I need getting an information about user confirmation status, using amazon-cognito-identity-js
Using this function i can't do it
export const getCognitoUser = (email) => {
    const userData = {
        Username: email,
        Pool: getUserPool()
    }
  return new AmazonCognitoIdentity.CognitoUser(userData)
}

export const getAuthDetails = (email, password) => {
  const authenticationData = {
    Username: email,
    Password: password,
   }
  return new AmazonCognitoIdentity.AuthenticationDetails(authenticationData)
}

A: if you are using the backend api, one way is you can use adminGetUser method to get userStatus, more details here https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminGetUser.html


text:
Q: Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0 // while trying to sign in in flutter I created a flutter application with sign in and sign up screens, the sign up screens works perfectly well and saves the email and username in the firebase, but when I try to sign in this error occurs: Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0, and when I printed the size of the query snapshot it was zero.. Any help would be appreciated.

This is the code for the method that is called when I press the sign in button:

  AuthMethods authMethods = new AuthMethods();
  final formKey = GlobalKey<FormState>();
  TextEditingController emailTextEditingController = new TextEditingController();
  TextEditingController passwordTextEditingController = new TextEditingController();

  QuerySnapshot snapshotUserInfo;
  bool isLoading = false;

signMeIn() {
    if (formKey.currentState.validate()) {
      HelperFunctions.saveUserEmailSharedPrefrence(emailTextEditingController.text);
      databaseMethods.getUserByUserEmail(emailTextEditingController.text).toString();

      databaseMethods.getUserByUserEmail(emailTextEditingController.text).then((val) {
        snapshotUserInfo = val;
        HelperFunctions.saveUserNameSharedPrefrence(
            snapshotUserInfo.docs[0].data()["name"]);  });

      setState(() {
        isLoading = true; });
      print("the size of the returnd query snapshot is:");  print(snapshotUserInfo.size);
      print("is the snapshot null? ");  print(snapshotUserInfo == null);

      authMethods
          .signInWithEmailAndPassword(emailTextEditingController.text,
              passwordTextEditingController.text)
          .then((val) {
        if (val != null) {
          HelperFunctions.saveUserLoggedInSharedPrefrence(true);
          Navigator.pushReplacement(
              context, MaterialPageRoute(builder: (context) => ChatRoom())); }
      });
    }}

This is the code of the helper functions:

import 'package:shared_preferences/shared_preferences.dart';

class HelperFunctions {
  static String sharedPrefrenceUserLoggedInKey = "ISLOGGEDIN";
  static String sharedPrefrenceUserNameKey = "USERNAMEKEY";
  static String sharedPrefrenceUserEmailKey = "USEREMAILKEY";

  //saving data to share prefrence
  static Future<bool> saveUserLoggedInSharedPrefrence(
      bool isUserLoggedIn) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return await prefs.setBool(sharedPrefrenceUserLoggedInKey, isUserLoggedIn);
  }

  static Future<bool> saveUserNameSharedPrefrence(String userName) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return await prefs.setString(sharedPrefrenceUserNameKey, userName);
  }

  static Future<bool> saveUserEmailSharedPrefrence(String userEmail) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return await prefs.setString(sharedPrefrenceUserEmailKey, userEmail);
  }

  //getting data from share prefrence
  static Future<bool> getUserLoggedInSharedPrefrence() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getBool(sharedPrefrenceUserLoggedInKey);
  }

  static Future<String> getUserNameSharedPrefrence() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(sharedPrefrenceUserNameKey);
  }

  static Future<String> getUserEmailSharedPrefrence(String userEmail) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString(sharedPrefrenceUserEmailKey);
  }
}

And this the code of database.dart:

import 'package:cloud_firestore/cloud_firestore.dart';

class DatabaseMethods {
  getUserByUsername(String username) async {
    return await FirebaseFirestore.instance
        .collection("users")
        .where("name", isEqualTo: username)
        .get();
  }

  getUserByUserEmail(String userEmail) async {
    return await FirebaseFirestore.instance
        .collection("users")
        .where("email", isEqualTo: userEmail)
        .get();
  }

  uploadUserInfo(userMap) {
    FirebaseFirestore.instance.collection("users").add(userMap).catchError((e) {
      print(e.toString());
    });
  }

  createChatRoom(String chatRoomId, chatRoomMap) {
    FirebaseFirestore.instance
        .collection("ChatRoom")
        .doc(chatRoomId)
        .set(chatRoomMap)
        .catchError((e) {
      print(e.toString());
    });
  }
}

And here is a screenshot from my firebase database:


text:
Q: Constructing a more efficient javascript user-based chat I am going to bed soon, so I will not be on until the morning, but I have been struggling with trying to find a javascript/jquery method that solves my problem.  I am trying to make a chat box feature where once a post is submitting it is then echoed back out and users on both ends can see it.  I know that I need to use javascript and or jquery.  Right now I am using a very inefficiency system:
<script language='javascript' type='text/javascript'>
    setInterval( function() {
    $('#responsechat').load('echogetconversation.php?username=<?php echo   $username; ?>&otherchatuser=<?php echo $otherchatuser; ?>');
    }, 100);
    </script>

The only reason that I am using it is because it is the only way I know how to project new posts to both users.  I was wondering if someone knew a way to do this.  Once a post is submitted, it fades into a div and both users can see it, not only the user who submitted it, so it is like a facebook chat in a way.  I have no idea about any possible solutions, and have done research, but I could not find any that i could get to work.  Any help and/or insight to what I should do next would be appreciated.

A: What you are looking for is ajax long pulling, also called Comet (it's a silly pun). The basic idea is simple--instead of polling the server, you send your ajax request and the server blocks on it until it gets a new message.
"Blocking" here simply means it does not send a response. You get your request then first up a thread (is that what you would do in PHP? I've only ever used node.js for this) and wait until something changes before sending the response back to the client.
Once the client has a response, it sends another request immediately.
There is one other trick: requests can time out. This means that the server should send a response back after a certain time even if nothing has updated.
This methodology is good if you have to support older browsers; if you can ignore those and stick to newer ones, you can use "websockets".
There are libraries that help you use websockets or fall back on Comet. I think the most popular one is socket.io.
Coincidentally, if you're not tied to PHP, I really suggest using a different server. node.js is a great option--it is a natural fit for this sort of problem and you can write the server-side code in JavaScript, which you already know. Even Facebook--the bastion of PHP--used a different language (Erlang) for their chat backend.
So, in summary: use socket.io. If you can, try using a different backend, although PHP is fine too.

A: If you don't want to use another language you can simply do it by AJAX..
Just set an interval and update the PHP-generated div's html.. and when you send a message then the reply would be the updated div -html so that both you and the user can assure that their message is posted successfully..  There's a snippet of my own chat system code : look:
function updMsg() {

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
    var objDiv = document.getElementById('chatwid');
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("chatwid").innerHTML=xmlhttp.responseText;}
  }
xmlhttp.open("GET","Msg.php?pg=1",true);
xmlhttp.send();
}

function sendMsg()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
msg=document.getElementById('msgfrm').value;
sender='<?php echo $name;?>';
xmlhttp.open("GET","Msg.php?msg="+msg+"&sender="+sender+"<?php if(isset($_GET['a']) && $_GET['a'] = 1) { echo "&a=1"; } ?>" ,true);
xmlhttp.send();
document.getElementById('msgfrm').value="";
xmlhttp.onreadystatechange=function()
  {
    var objDiv = document.getElementById('chatwid');
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("chatwid").innerHTML=xmlhttp.responseText;}
  }
}
function interval() {
updMsg();
t=setTimeout(interval(),500);}
interval();

This code is actually only PHP and Javascript. It's not sufficient to include the whole jQuery Library just for using the AJAX capability. right?


text:
Q: In Strapi i can get a specific product but how do I get ALL products? I set up a product collection type, added three records and in the browser type
localhost:1337/api/products/2 and it correctly displays record 2:
{"data":{"id":2,"attributes":{"title":"Gillette Razor","price":9.99,"description":"/assets/product-images/product-2.png","featured":true,"createdAt":"2022-08-20T12:23:10.685Z","updatedAt":"2022-08-20T12:29:45.062Z","publishedAt":null}},"meta":{}}
(also works for /1  and /3, showing those products).
But, when I try to see ALL products by typing:
localhost:1337/api/products I get:
{"data":[],"meta":{"pagination":{"page":1,"pageSize":25,"pageCount":0,"total":0}}}
I have given "public" access to "find" and "findOne". Server is running. Why is it not producing a list of the three products entered?

A: The solution was the data has to be "published" (default is "draft") for the /api/products to show all records, even though the /api/products/x had no issue revealing product x details without being published.
After marking the data as published localhost:1337/api/products now gives me ALL of my products:
{"data":[{"id":1,"attributes":{"title":"razor blade","price":1.99,"description":"/assets/product-images/product-1.png","featured":false,"createdAt":"2022-08-20T12:22:12.498Z","updatedAt":"2022-08-20T15:37:08.598Z","publishedAt":"2022-08-20T15:37:08.597Z"}},{"id":2,"attributes":{"title":"Gillette Razor","price":9.99,"description":"/assets/product-images/product-2.png","featured":true,"createdAt":"2022-08-20T12:23:10.685Z","updatedAt":"2022-08-20T15:37:01.649Z","publishedAt":"2022-08-20T15:37:01.648Z"}},{"id":3,"attributes":{"title":"Barber Razor","price":7.99,"description":"/assets/product-images/product-3.png","featured":null,"createdAt":"2022-08-20T12:23:52.749Z","updatedAt":"2022-08-20T15:36:52.579Z","publishedAt":"2022-08-20T15:36:52.577Z"}}],"meta":{"pagination":{"page":1,"pageSize":25,"pageCount":1,"total":3}}}


text:
Q: access xampp server online without getting hacked hi im working with xampp and laravel 8
the software author don't want the server to be online but he want to have it as localhost server
and also he want to access the server from outside
online xampp server

before tow years i was working in project as localhost and i opened port with my static ip so i access the project online ..
but the problem was thats i get hacked encrypt all files after i turned of the firewall .. and im afraid to have the same problem again ..
xampp

so what is the safest way to make xampp server can access online ..
thanks


text: Q: Want to change icon as the theme apply on device I am trying launcher for android device, I want to add the themes and styles, applying these themes icon of the app should change same as every launcher provides. if anyone can help . Thank you.


text:
Q: Git push to main project repo throws an error after git subtree add Trying to use git subtree to share common library files across multiple projects. Here's the problem I keep encountering.
1) Add subtree so "jquery_treetable" subdirectory of my project.
$ git subtree add -P jquery_treetable ssh://epedgov@gerrit.ericsson.se:29418/global_share/3pp/foss/jquery_treetable master --squash

gitk looks like below after subtree add

2) push updates to main project repo(Gerrit)
$ git push origin HEAD:refs/for/master
remote: Resolving deltas: 100% (1/1)
remote: Processing changes: refs: 1, done
remote: ERROR: [36fb8f5] missing Change-Id in commit message footer
remote:
remote: Hint: To automatically insert Change-Id, install the hook:
remote:   gitdir=$(git rev-parse --git-dir); scp -p -P 29418 epedgov@gerrit.ericsson.se:hooks/commit-msg ${gitdir}/hooks/
remote: And then amend the commit:
remote:   git commit --amend
remote:
To https://gerrit.ericsson.se/a/lte/tools/mkdoc
 ! [remote rejected] HEAD -> refs/for/master ([36fb8f5] missing Change-Id in commit message footer)

3) git log looks like below

4) I think, I get this rejection because of change-id is missing in 2nd commit in git log (Squashed one). But how to add Change-id for this Squashed subtree.

A: You have two un merged commits ( The commit Date is same for both commits, so i guess both are created at the same time and are not merged ) and the issue is not with first commit , it is with second commit ( Error message shows that 36fb8f5) which had git-subtree in commit message and change-Id is missing , gerrit will check for change id of all changes which are to be merged, you might need to a
git reset --soft HEAD^1 ( If you want previous changes of merge commit )
However if you want to resolve issue at hand and have a clean slate
git reset --hard HEAD^1
Above command should now bring you branch HEAD position to  36fb8f5
you can check the same using
git log -2

Now perform
git commit --amend
Now check if the change Id got append to the commit message , if it is , you can push the change and issue should be resolved


text:
Q: How to animate as a callback to another animate function I'm beginner level jquery and I setup this script but i need to modify it. I want to have it so that on hover, the arrow moves to the right 3px and then back to the left origional position..all before the mouse moves out.
Right now it is set to return to its original position but...only after mouse out. I want to include that step in the hover as a callback.  so it moves to right then left consecutively.  The red box effect remains the same for hover and out.
This is the script I have so far but having an issue changing it. any help would be wonderful so that I can learn.
<script type="text/javascript">

$(document).ready(function() {
    var $red   = $('#red');
    var $arrow = $('#arrow');
    $('#wording').hover(
      function() {
        $red.animate({'width': 'toggle'});
        $arrow.css('color', 'white').delay(100).animate({'right': '-=3px'}, 'fast');
      }, function() {
        $red.animate({'width': 'toggle'});
        $arrow.css('color', 'red').delay(100).animate({'right': '+=3px'}, 'fast');
     });
});

</script>

A: $('#wording').on('mouseenter', function() {
  $red.animate({'width': 'toggle'});
  $arrow.css('color', 'white').delay(100).animate({'right': '-=3px'}, 'fast', function(){
    $red.animate({'width': 'toggle'});
    $arrow.css('color', 'red').delay(100).animate({'right': '+=3px'}, 'fast');
  });
});

The callback is passed as a third argument to animate


text:
Q: JavaScript - how to check if Object has a certain key, when key is variable? Example:
var o = {'key': 'value'};
var key = 'key';
console.log('key' in o); //true
console.log(key in o); //false

How to do this? =)

A: I'd suggest:
o.hasOwnProperty(key);

JS Fiddle demo.
References:

*

*hasOwnProperty().

A: Try hasOwnProperty:
o.hasOwnProperty(key);


text:
Q: Send WebSocket message every 1 second I've been tasked settings up the following.
6 individual stopwatches which all sync with each other.
They all need to be able to start at the same time
They need to be able to be stopped separately (6 people will be racing, when one finished, their timer will stop).
I'm thinking Web Sockets would be a good idea for this, so the timer can sync with the server, and I've followed this to set it up and get it running.
I'm currently at the stage where I can connect 6 individuals, and one admin page to display how many clients their are, and a "Start Timer" button.
I've created this method which i thought would send the current server time to each client every second (for 10 seconds). But it doesn't work, it sends all 10 messages at once, after 10 seconds.
private function startTimer() {
    for($i = 0;$i < 10;$i++) {
        $now = date('H:i:s d-m-Y');
        foreach($this->all as $client) {
            $client['conn']->send(json_encode(array('action' => 'time', 'time' => $now)));
        }
        sleep(1);
    }
}

So, 1) Are Web Sockets a good way to do this, or, is Javascript/PHP not ideal for doing this project? And 2) If Web Sockets will work, how can I keep each client in sync with each other?

A: Rather than doing a send every second when I pressed start I sent each client the current server time, then get them calculate time passed in Javascript. I realize this may not be the safest solution, but this is a just a little project to be used internally, so it won't be exploited.


text:
Q: Динамическое добавление значения в input text Нужно динамически (id будут подставляться автоматически) при клике добавлять значения input в другой input. Как это сделать? Сейчас добавляет только первое значение.

*

*Значения при нажатии кнопок в поля заменяются.

*Одна кнопка add добавляет значение в name="add" и заменяется сама на другую кнопку del после нажатия, и наоборот, появившиеся кнопка del вместо add, добавляет то же значение (id, value) в другое поле name="del"

*Не трогая name="add" (взаимно)

*И наоборот постоянное переключение кнопок одна взаимен другой.

<input type="text" name="add" value="" />
<input type="text" name="del" value="" />

<input type="text" class="location-1" value="1" />
<input type="button" class="add-1" value="add1" />
<input type="button" class="del-1" value="del1" />

<input type="text" class="location-2" value="2" />
<input type="button" class="add-2" value="add2" />
<input type="button" class="del-2" value="del2" />

<input type="text" class="location-3" value="3" />
<input type="button" class="add-3" value="add3" />
<input type="button" class="del-3" value="del3" />

<input type="text" class="location-4" value="4" />
<input type="button" class="add-4" value="add4" />
<input type="button" class="del-4" value="del4" />

A: Попробуйте вот так:

$(document).ready(function() {
  $("input[type='button']").on('click', function () {
    // Надо получить инпут связанный с кнопкой
    const location = $(this).attr('class');
    const $input = $(`input[type='text'].${location}`);
    $("input[name=add]").val($input.val());
  });
});
input {
  display: block;
  margin: 10px 0;
  width: 150px;
  box-sizing: border-box;
}

<input type="text" name="add" value="" />

<input type="text" class="location-1" value="1" />
<input type="button" class="location-1" value="1" />
<input type="text" class="location-2" value="2" />
<input type="button" class="location-2" value="2" />
<input type="text" class="location-3" value="3" />
<input type="button" class="location-3" value="3" />
<input type="text" class="location-4" value="4" />
<input type="button" class="location-4" value="4" />

A: что-то такое вам надо?

$(".add").click(function(){

   var append = $("#mode").prop('checked');
   var value = null;

   if(append){
      value =  $(this).siblings(".location").val();
   }
   else{
       value = $(".location").map( function(){
                     return $(this).val();
                  }).get().toString();
   }

  $("#favadd").val(value);
});

<input type="checkbox" id="mode"/>Добавлять/заменять

<input type="text" id="favadd" value="" />

  <input type="text" name="location[]" class="location" value="1" />
  <button class="add">+</button>

  <input type="text" name="location[]" class="location" value="2" />
  <button class="add">+</button>


text:
Q: Oracle APEX report - processing a field value I have been creating Oracle APEX reports for a while.
I need to processes a column value to charge it's format.
The current SQL looks like this. All is good.
select PP_RUNDATA.ID as ID,

PP_RUNDATA.PP_START_TIME as PP_START_TIME,

PP_RUNDATA.PP_END_TIME as PP_END_TIME,

from PP_RUNDATA PP_RUNDATA

The time columns are in seconds. This PL/SQL converts the seconds into date / time. (this work well)
alter session set nls_date_format="dd/mm/yyyy - hh24:mi:ss";
select date '1970-01-01' + 1661596871 * interval '1' second result from dual;

I need to bring together the SQL and PL/SQL and change the 1661596871 to the column value.
I know I can use a "List Value" to process the PP_START_TIME / PP_END_TIME column using PL/SQL returning SQL.
A very poor, not working example,
declare
temp1  varchar2(500);
begin
EXECUTE IMMEDIATE 'alter session set nls_date_format="dd/mm/yyyy - hh24:mi:ss"';
select date '1970-01-01' + PP_START_TIME * interval '1' second into temp1 from dual;
return 'select temp2 from dual';
End;

I know there are more than two things wrong with this coding;
1) Syntax to access data in column PP_START_TIME (maybe &PP_START_TIME.)

2) the "return statement"

What am I doing wrong in the coding / my thinking in the above or maybe the overall approach in Oracle APEX Reports?
Thanks for looking
Pete

A: You can use:
select ID,
       DATE '1970-01-01' + PP_START_TIME * INTERVAL '1' SECOND as PP_START_TIME,
       DATE '1970-01-01' + PP_END_TIME   * INTERVAL '1' SECOND as PP_END_TIME
from   PP_RUNDATA

If you want a particular format then you can use TO_CHAR:
select ID,
       TO_CHAR(
         DATE '1970-01-01' + PP_START_TIME * INTERVAL '1' SECOND,
         'dd/mm/yyyy - hh24:mi:ss'
       ) as PP_START_TIME,
       TO_CHAR(
         DATE '1970-01-01' + PP_END_TIME   * INTERVAL '1' SECOND,
         'dd/mm/yyyy - hh24:mi:ss'
       ) as PP_END_TIME
from   PP_RUNDATA