text:
Q: Formic always shows that form is invalid Here I used formic with yup . Even I defied some schema for validation and even the values in the inputs full fill that rules formic in combination with YUP always says that the form is invalid even the form values are valid. I am a beginner. So I would be much thankful to you if you could provide some in-depth answer.
Thank you
import React, { useEffect, useState } from 'react'
import './index.css'
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import axios from 'axios'

const Inedex = () => {

const [projects, setProjects] = useState([])
const [memebers, setMemebers] = useState([])

const [formData, setFormData] = useState({
    projectId: "",
    title: "",
    actualOutcomes: "",
    expectedOutcomes: ""
})

const setData = (key, value) => {
    setFormData({ ...formData, [key]: value })
    console.log(formData, { key, value })
}

useEffect(() => {
    getProjects();
}, [])

const getProjects = () => {
    axios.get("http://localhost:5000/project/all/names").then(res => {
        console.log(res.data)
        setProjects([...res.data])
    })
}

const handleProjectChange = (value) => {
    setData("projectId", value);
    axios.post("http://localhost:5000/project/roles", {
        "projectId": value,
        "role": "DEV"
    }).then(res => {
        console.log(res.data)
        setMemebers(res.data)
    })

}

const submitForm = (values) => {
    console.log(values);
};

const initialValues = {
    project:"",
    developer:"",
    email: "",
    title: "",
    project: "",
    developer: "",
    title: "",
    actualOutcomes: "",
    expectedOutcomes: ""
};

const DynamicProjectOptions = () => {
    return (
        projects.map(project => {
            return (
                <option value={project.id} key={projects.name} >{project.name}</option>
            )
        })
    )
}

const DynamicMembers = () => {
    return (
        memebers.map(memeber => {
            return (
                <option value={memeber.id} key={memeber.name} >{memeber.name}</option>
            )
        })
    )
}

const signInSchema = Yup.object().shape({
    project: Yup.string().min(1, 'Too Short!').required("Project is required"),
    developer: Yup.string().min(1, 'Too Short!').required("Developer is required"),
    title: Yup.string().min(5, 'Too Short!').required("Title is required"),
    actualOutcomes: Yup.string().min(5, 'Too Short!').required("Actual outcomes is required"),
    expectedOutcomes: Yup.string().min(5, 'Too Short!').required("Expected outcomes is required"),

});

return (
    <Formik
        initialValues={initialValues}
        validationSchema={signInSchema}
        onSubmit={(values) => alert(values)}
    >
        {({ errors, touched, isValid, dirty }) => {

            return (<Form>

Report a bug

                    {/* Project  */}

                    {isValid}

                        Project
                        <Field
                            name="project"
                            component="select"
                            id="project"
                            className={(errors.email && touched.email ? "is-invalid" : null) + " form-control "}
                            onChange={e => { handleProjectChange(e.target.value) }}
                            value={formData.projectId}
                        >
                            <DynamicProjectOptions />
                        </Field>

                        {JSON.stringify(formData.selectedProject)}
                        <ErrorMessage name="project" component="span" className="invalid-feedback" />

                    {/* Developer  */}

                        Developer

                        <Field
                            name="developer"
                            component="select"
                            id="developer"
                            className={(errors.email && touched.email ? "is-invalid" : null) + " form-control "}
                        >
                            <DynamicMembers />
                        </Field>

                        <ErrorMessage name="developer" component="span" className="invalid-feedback" />

                        Title
                        <Field
                            type="text"
                            name="title"
                            id="email"
                            className={(errors.email && touched.email ? "is-invalid" : null) + " form-control "}
                            onChange={(e) => { setData("title", e.target.value) }}
                            value={formData.title}
                        />
                        <ErrorMessage name="title" component="span" className="invalid-feedback" />

                        Actual outcomes
                        <Field
                            type="text"
                            name="actualOutcomes"
                            id="actualOutcomes"
                            className={(errors.email && touched.email ? "is-invalid" : null) + " form-control "}
                            onChange={(e) => { setData("actualOutcomes", e.target.value) }}
                            value={formData.actualOutcomes}
                        />
                        <ErrorMessage name="actualOutcomes" component="span" className="invalid-feedback" />

                        Expected outcomes
                        <Field
                            type="text"
                            name="expectedOutcomes"
                            id="expectedOutcomes"
                            className={(errors.email && touched.email ? "is-invalid" : null) + " form-control "}
                            onChange={(e) => { setData("expectedOutcomes", e.target.value) }}
                            value={formData.expectedOutcomes}
                        />
                        <ErrorMessage name="expectedOutcomes" component="span" className="invalid-feedback" />

                    {JSON.stringify({dirty , isValid , touched})}
                    {/* {JSON.stringify(Object.keys(errors))} */}
                    <button
                        type="submit"
                        className={!(dirty && isValid) ? "disabled-btn" : ""}
                        disabled={!(dirty && isValid)}
                    >
                        Sign In
                    </button>

            </Form>
            );
        }}
    </Formik>
      );
     };

   export default Inedex;

A: Check sandbox, https://codesandbox.io/s/sharp-leftpad-0j792?file=/src/App.js
multiple issues here, <Field/> component automatically manages onChange to set to formik state,

*

*you dont need to manage form state separately

*you have to call setFieldValue if you give custom onChange function

*you dont need to pass value to <Field/> component, it is done from within.


text:
Q: Android TabLayout with viewpager tab text color not working at first I'm using TabLayout/ViewPager and there are three fragments.
I set a default page of ViewPager with  ViewPager.setCurrentItem(). ViewPager shows me a fragment what i wanted to see but the tab's text color of TabLayout isn't applied properly.(First tab's text color is displayed as a selected tab at unconditionally at onCreate)
Can anyone please give me an advise about how can i fix this?

    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    TabLayout tabs = (TabLayout) findViewById(R.id.tabs);

    pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    pager.setCurrentItem(1);
    pager.setOffscreenPageLimit(2);

    tabs.setBackgroundColor(Color.parseColor("#a3000e"));
    tabs.setTabTextColors(Color.parseColor("#999999"), Color.parseColor("#ffffff"));
    tabs.setupWithViewPager(pager);

A: Try something like this:
mUnderlinePageIndicator.setViewPager(mViewPager);

A: You have to synchronize your TabLayout with your ViewPager:
tabLayout.setupWithViewPager(viewPager);

Perform the setCurrentItem-operation after the setupWithViewPager-method was called.

A: I updated android design support library and problem fixed.
compile 'com.android.support:design:22.2.1' in gradle

redpajama_set_name: RedPajamaStackExchange


text:
Q: Centos 5.5 won't boot anymore; the dreaded "Could not find filesystem /dev/root" error Normally I have no problems finding my answers online but I have been trying to fix my downed server for 3 days now and I am no step further.
The server in question is a Centos 5.5 machine running an openvz-kernel, 2.6.18-194.8.1.el5.028stab070.5 to be more precicse. We don't have physical access to the server, neither do we have serial/net console of some sorts. We do have a debian-based rescue-disk loaded over pxe.
The server has two disks, SDA:
Disk /dev/sda: 320.0 GB, 320071851520 bytes
255 heads, 63 sectors/track, 38913 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x00000000

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *         524        1193     5381775   83  Linux
/dev/sda2               1         523     4200997   82  Linux swap / Solaris
/dev/sda3            1194       38913   302985900   83  Linux

Partition table entries are not in disk order

and SDB:
Disk /dev/sdb: 320.0 GB, 320072933376 bytes
255 heads, 63 sectors/track, 38913 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x00000000

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1               1       38913   312568641   83  Linux

sda1 has the filesystem, sda2 is the swap space, sda3 and sdb1 together form md0 which is mounted on /vz. Here is the fstab.
/dev/sda1               /                       ext3    defaults        1 1
proc                    /proc                   proc    defaults        0 0
sysfs                   /sys                    sysfs   defaults        0 0
/dev/sda2               swap                    swap    defaults        0 0
/dev/md0                /vz                     ext3    defaults        0 0

and menu.lst/grub.conf
boot=/dev/sda
default=0
timeout=15
#splashimage=(hd0,0)/boot/grub/splash.xpm.gz

title CentOS (2.6.18-194.8.1.el5.028stab070.5)
        root (hd0,0)
        kernel /boot/vmlinuz-2.6.18-194.8.1.el5.028stab070.5 ro root=/dev/sda1
        initrd /boot/initrd-2.6.18-194.8.1.el5.028stab070.5.img
title CentOS (default)
        root (hd0,0)
        kernel /boot/bzImage ro root=/dev/sda1

Now for some reason the server went down and we have been unable to get it in working order again. Our provider tried to "fix" our problem by reinstalling grub via the earlier mentioned rescue-disk while mounting sda1 @ /mnt.
grub-install --root-directory=/mnt '(hd0)'

http://i.stack.imgur.com/1FRi6.jpg
This is photo of the monitor output of the server when booted. Now it can clearly load /etc/fstab since it tries to resume from our swap partition.
Now because we don't have access to the server we are using Qemu to try and debug the problem but we can never be sure it's behaves the same way, plus everytime we make changes on sda1 we need to reboot the server for qemu to see the changes, any pointers to do this an other way are welcome. We use qemu the following way.
qemu-system-x86_64 -vnc :0 -hda /dev/sda -hdb /dev/sdb

We've tried to reinstall the latest kernel. Tried to make a new initrd without raid-support and forced ext3 support. Copying the /boot from a server with the same setup. Installing grub on almost all possible disks / partitions.
I have no clue what else I can try. Any tips at all are greatly appreciated.
tl;dr: Server went down, won't reboot because of "could not find filesystem error"

A: What does your grub.conf look like? Maybe there's suddenly a wrongly configured root= or init= parameter?
If that's not the case, is there a /dev directory present when you mount the CentOS / partition via your Debian-based rescue system? If there is, what does it look like? Does it match with /dev/sda1 information if you check it out with stat or ls -lah? Maybe /dev/root is pointing there to wrong location (or, has been created with wrong mknod parameters).
Yes, /dev should be quite dynamic these days, but you never know... back in kernel 2.4 days I hosed one of my Gentoo systems and got it booting after I recreated some device nodes by hand.
Edit after grub.conf was added to original question:
The very first line (boot=/dev/sda) of your grub.conf looks suspicious. Try to comment it out and reboot.
If this did not work, you might also want to check out /dev/sda1 parameters with ls -lah. It should look like this:
brw-r----- 1 root disk 104, 1 Sep 29 01:23 /dev/sda1

Observe the values similar to 104, 1. Then create the /dev/root with
mknod -m 640 /dev/root b 104 1

where you change 104 and 1 values according to yours.
Hope this helps!

A: For us, the issue described here was actually the partition label being missing.
See: https://serverfault.com/a/123165/191716


text:
Q: Spark History Server not showing jobs from a different user I have set up a YARN cluster (using hadoop-3.3.0) and configured spark (spark-3.0.0-bin-hadoop3.2) so that I can run my spark applications on YARN. All this set up has been done via admin user. admin user is present on each node of my cluster. To monitor the applications I have also started Spark History Server. The history server correctly shows spark applications submitted via admin user.
However if the spark job is submitted via a different user say alice the Spark History Server does not show applications submitted by alice. Is there any solution for this?
Setup details:
spark.eventLog.enabled true
spark.eventLog.dir hdfs://<HDFS_URL>/spark-logs
spark.history.provider org.apache.spark.deploy.history.FsHistoryProvider
spark.history.fs.logDirectory hdfs://<HDFS_URL>/spark-logs
spark.history.fs.update.interval 10s
spark.history.ui.port 8080
spark.yarn.historyServer.address <HISTORY_SERVER_IP>:8080

hdfs://<HDFS_URL>/spark-logs has permission 777
$YARN_HOME/logs has permission 777
$YARN_HOME/logs/userlogs has permission 777


text:
Q: MySQL select column length in php (below PHP7) How do I get the actual max length of a specified column in php (prior to PHP7)?
For instance, this table:
id - int(11)
name - string(20)
I want in php to select the maximum number of characters that a field can have, like
SELECT length(name) from table1

and it should then return 20 (since it's the maximum number of characters for that field).

A: You should use mysql_field_len
http://php.net/manual/en/function.mysql-field-len.php

A: You can use mysql_field_len for a single column or use the SHOW COLUMNS FROM table query in MySQL to get information about all the columns at once.

A: Just be careful when using mysql_field_len to read columns that are not ints or strings. For example, decimal(6,4) will return 10 from mysql_field_len.
You may wish to use SHOW COLUMNS and parse the data, if you need all of the column information.

A: Please keep in mind that mysql_field_len has been removed in PHP 7.0.0. A good solution will be using mysql_fetch_lengths, to get an array with length of all fields in a result. There are other calls, such as mysqli_fetch_fields or PDOStatement::getColumnMeta which return fully detailed description, including table name, field name, type, length and more.


text:
Q: how to view different detailView of selected row on iOS Master Detail I'm working on master detail app and i would like to view different detailView of selected row. and to be my question clear i give you example here:
Master Detail

detail 1         >

detail 2         >

the target is when i press [detail 1 >] give me self detailview of detail 1 row. and press [detail 2] give self detailview of detail 2 row. i think it's clear. also add customize buttons, images inside every detail view if possible!!
any help will be appreciated.

A: DetailViewController *detailView = [[DetailViewController alloc]init];
detailView.tagValue = 1;
[self.navigationController pushViewController:detailView animated:YES];

You can send a tag value to detailView and based on this value you can show different views.
Like make a property like @property(nonatomic)NSInteger tagValue; in .h class of detailView and synthesize it in .m class. Now you can send the tagValue from master Class like this
Now you can check value of tagValue in DetailViewController and based on this you can create your View.
I think it is clear now. But if you still have any issue, you can write your code.

A: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{
    DetailViewController *detailView = [[DetailViewController alloc]init];

    detailView.tagValue = indexPath.row;

    [self.navigationController pushViewController:detailView animated:YES];
}

we need to give detailView.tagValue = indexPath.row;


text:
Q: Swift dateformatter.date(from: string) strange behaviour import UIKit

let dateString="2018.03.11"

let df = DateFormatter()

df.timeZone=TimeZone(secondsFromGMT: 0)
df.dateFormat="YYYY.MM.dd"

let date=df.date(from: dateString)

print("orig dateString: \(dateString)")
print("date(from: string): \(date)")
print("converted again: \(df.string(from: date!))")

now this code seems to work as expected. Both input and output dates are the same:
orig dateString: 2018.03.11
date(from: string): Optional(2018-03-11 00:00:00 +0000)
converted again: 2018.03.11
But if I try to change the input format:
import UIKit

    let dateString="11.03.2018"

    let df = DateFormatter()

    df.timeZone=TimeZone(secondsFromGMT: 0)
    df.dateFormat="dd.MM.YYYY"

    let date=df.date(from: dateString)

    print("orig dateString: \(dateString)")
    print("date(from: string): \(date)")
    print("converted again: \(df.string(from: date!))")

I get the following result:
orig dateString: 11.03.2018
date(from: string): Optional(2017-12-24 00:00:00 +0000)
converted again: 24.12.2017
The date(from: String) seems to initialize the date in a way that I do not understand.
Any help appreciated.
Thank you.

A: The problem is with the date format.
change these lines:
df.dateFormat="YYYY.MM.dd"
df.dateFormat="dd.MM.YYYY"

to this:
df.dateFormat="yyyy.MM.dd"
df.dateFormat="dd.MM.yyyy"


text:
Q: Only allow some rows to be editable in ng-grid I have an ng-grid that I would like to allow only certain rows to be editable.  It seems ng-grid is an all or nothing editable grid, am I missing something or is there a workaround?

A: The workaround I came up with is to replace the cellEditTemplate in the $templateCache with an extra condition on the ng-edit-cell-if directive.  For example, we want row 0 to be editable and row 1 to be read only:
$templateCache.put("cellEditTemplate.html",
  "
" +
    "
   " +
    "       DISPLAY_CELL_TEMPLATE" +
    "
" +
    "
" +
    "       EDITABLE_CELL_TEMPLATE" +
    "
" +
    "
"
);


text:
Q: What's this sensor called? Found it in my AC unit It's a 2 wire sensor I found in my central home air-conditioning unit. Any ideas what it's called? Wasn't able to find a part number on it.
Is there a test I can do to find out, using a multimeter?

A: This looks like it could either be a thermocouple or thermistor. The copper sheathing exists to protect the sensor inside. Many thermistors use a glass-covered sensor which can be easily damaged. A thermocouple generates (mVs of) voltage and a thermistor changes its resistance. If you have a multimeter, measuring the resistance across its wires can determine what it is. A thermistor will read a certain resistance, depending on the temperature. Common values include ~10K and ~100K Ω, but it may vary. A thermocouple will give anything else. Many multimeters have a thermocouple mode, but only for specific types, and probing the sensor is not very easy. Posting a picture of the connector may help identify the sensor, as many thermocouples use standard connectors.
However, as Dmitri and Nick mention in the comments, a thermocouple is unlikely due to noise in motors interfering and the lack of color-coded wires.


text:
Q: To show a function is zero. For $\alpha>0$, consider $f\in L^1([\alpha,\infty))$ satisfying
$$\int_\alpha ^\infty   e^{-yt}e^{ixt}f(t)dt=0, \forall x\in\mathbb{R},y>0.   $$
Is it true that $f=0$ almost everywhere on $[\alpha,\infty)?$
My try:
$$\int_\alpha ^\infty   e^{izt}f(t)dt=0, \forall z\in\mathbb{H}.   $$
Also $\hat{f}=0\implies f=0.$ But $f\in L^1([\alpha,\infty))$ instead of $L^1(\mathbb{R})$.

A: Let $g(t)=f(t)e^{-t}$ for $t \geq \alpha$ and $0$ for $t <\alpha$. Then $g$ in integrable and its FT is $0$. Hence $g=0$ a.e and this implies $f=0$ a.e. on $[\alpha , \infty)$


text:
Q: Remote Desktop Cannot connect to the remote computer for one of these reasons on amazon web services windows instance I Have set in bound rules to allow all traffic and allow all protocols from all ip's
i was able to connect to the instance via rdp until recently i am unable to connect all of a sudden
I have already set inbound rules to the VPC security group as well as the security group in the EC2 console, and the ACL but my rdp is still not connecting

A: Go to security groups ->Inbound -> Edit -> Add rule -> select RDP ->  in drop down(select anyware ) -> save

A: First of all there can be multiple reasons why this RDP is not connecting.
You can try to do stop and restart the instance. Sometimes this solves the problem instantly, but sometimes there might be a firewall issue, check your rules.

As you said you have enabled all IPs on all protocols in security
  group.

You may also try the troubleshooting steps suggested by AWS.

A: I have made a video on How to set your Remote Desktop using AWS Ec2 instance. You can refer to this link if it fits your need.
you need to add RDS inbound rule which by default runs on port 3291. Give access permission to Anywhere.


text:
Q: Добавление столбца в  MySQL Я пишу чат с помощю php, mysql, ajax и jQuery. Хочу добавить столбик в mysql-е для добавления даты каждого сообщения, чтобы потом с помощю ajax вывести на экран новые сообщения. Имя моей таблицы в mysql-е messages, в нем есть 3 столбика id, message и date.
$message = $_POST['messages'];
    $timestamp=123456789;
    $format="d.m.Y G:i:s";
    $DB->Query("INSERT INTO messages(message, date) VALUES('$message', 'date($format, $timestamp)' )");

Так я добавляю message и date в таблицу, но что-то не так, оно добавляет
0000-00-00 00:00:00 в столбике date, помогите разобраться.
A: Как вариант можно настроить столбец в базе примерно так:
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Тогда можно вообще не думать вообще об этом столбце и делать вставку примерно так:
$DB->Query("INSERT INTO messages(message) VALUES('$message')");

A: Не пробовали просто NOW() вместо date($format, $timestamp)?
Добавлено.
Так делаете?
$DB->Query("INSERT INTO messages(message, date) VALUES ('$message', NOW())");

P.S в бд нельзя ввести дату в своем формате. Она всегда там записана как YYYY-MM-DD, вы можете вывести из нее только в своем формате, а дата там храниться только так.
A: У вас неправильный формат даты.
Для mysql правильным форматом даты является:
$format="Y-m-d H:i:s";

Попробуйте так: (Изменил)
$date = date("Y-m-d H:i:s");
$DB->Query("INSERT INTO messages(message, date) VALUES('$message', '$date' )");


text:
Q: Set encoding when using ogr2ogr to export from Oracle db to MapInfo table? I am trying to automate the export of spatial data from a oracle database to mapinfo .tab files. Using this thread I made my script. However I can't see how to set the encoding right.
My data have latin1 encoding. But this is not the case in the output file. I get warnings regarding invalid characters when running the script and Local characters like æøå is not intact in the output.
This is my code:
REM Unsuccessful attempt to change encoding:
SET PGCLIENTENCODING = LATIN1
SET OGR_FORCE_ASCII = NO

C:\OSGeo4W\bin\ogr2ogr.exe -f "MapInfo File" C:\OUTPUT\PATH\test.TAB OCI:"<USERNAME>/<LOGIN>@(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = <HOST>)(PORT = <PORT>)))(CONNECT_DATA = (SID =<SID-NUMBER>))):<TABLES>

A: The OGR driver for Oracle (OCI driver) accesses the database just like any other client, and so it's behavior regarding character set is the same as for any other client.
In particular, the character set in which the database will send the strings to the client (here ogr2ogr via its OCI plugin) is influenced by the setting of the NLS_LANG environment variable. On windows, that variable (like others) is in the registry. It may be that this variable is incorrectly set up in your environment, or maybe it is missing entirely if you use the light-weight Oracle "thin client".

Local characters like æøå is not intact in the output.

Do you mean they come out as "?" characters ? If so that probably means that you do not have any NLS_LANG set, and so the client library applies the default of US7ASCII (which is unable to encode those characters).
Confirm first that your database is correctly setup with the proper character set. What does the following show ?
SQL> select value from nls_database_parameters where parameter='NLS_CHARACTERSET';

If your database is on Windows and you do have it set up for ISOLatin1 then you should get something like WE8MSWIN1252. If it is on Unix/Linux (also ISOLatin1) then you should see WE8ISO8859P1.
Try the following: before running ogr2ogr set the following:
SET NLS_LANG=AMERICAN_AMERICA.WE8MSWIN1252

That will make sure the OCI plugin gets the strings in ISOlatin1. And you then can only hope that ogr proper does not play any tricks with those strings and passes them on to the Mapinfo plugin (hoping too that that also lets them through unadulterated).
PGCLIENTENCODING obviously has no effect: it is only for PostgreSQL
OGR_FORCE_ASCII is also best left out: according to the doc, it will replace all non-ASCII7 characters with "?" - precisely what you do not want. But then again it only applies to XML and derived formats - not your case anyway.

A: This works for me (for Windows):
SET NLS_LANG=.CL8MSWIN1251
ogr2ogr [...]


text:
Q: Ionic JSON, add card to favorites I have a JSON Parse in my project and its work fine
let data:Observable<any>;

data = this.http.get(API);
data.subscribe(result => {
    this.items = result;
    this.saveData();
});

HTML:
    <ion-card *ngFor="let item of items">
        <ion-card-content id="{{item.id}}">
        ....
        ....
        </ion-card-content>
    </ion-card>

Now I want a 'Favorite' function.
I have an icon with a click event.
How I do, that when anyone clicks on the icon he add the specific card to his favorites and he can show his favorites on another page?


text:
Q: what's the difference between share() and publish().autoConnect()? According to my point of view.I thinkshare() is the same withpublish().autoConnect().But in this code the results are not the same
Observable<Integer> cold = Observable.create(subscriber -> {
        for (int i = 0; i <= 2; i++) {
            System.out.println("Hot Observable Emit " + i);
            subscriber.onNext(i);
        }
    });

    ConnectableObservable<Integer> connectble = cold.publish().autoConnect(2);
    //Obserable(Integer) connectavle = cold.share();
    connectble.subscribe(subscriber1);
    connectble.subscribe(subscriber2);

the publish(). autoConnect() output
Hot Observable Emit 0
Subscriber 1 : 0
Subscriber 2 : 0
....

the share() output
Hot Observable Emit 0
Subscriber 1 : 0
//the subscriber2 not receive event

In this case,we can not use share() for Multicasting in rx-java?  I find a conclusion but not suitable for this case.
test environment: oracle jdk1.8 rx-java 1.2 IDEA ubuntu

A: They are different in that when subscribers unsubscribe from a share, the upstream is disconnected and when new subscribers subscribe, the upstream source is resubscribed and starts from the beginning (if cold).
autoConnect waits for the specified amount of subscribers, connects once and never disconnects when all subscribers unsubscribe. Here is a description about how it works.


text:
Q: Getting the Line Postion In iText i am using iText 5.1.0 for creating the PDF in java . I have 3 blocks of tables , whose sizes may change dynamically
Table 1

.

.

.

Table 2

.

.

.

.

End of page

Now i am in need of the method that would compute the space below the table 2 . And i am using the pagesize as A4
Intially it printed like this ,
But when the data in the previous tables increased it printed , like the 2 nd one.
So i would like to calculate the space below if possible before i insert the table
Any suggestions are highly appreciated.
Thank you

A: There's a method in PdfWriter called getVerticalPosition(). It takes a Boolean parameter that tells iText to ensure a new line or not. If you don't ensure a new line (false), you get the current Y, but that may not be the position you need. If you ensure a new line (true), a new line is added and you get the position where the new line starts.
As you are creating A4 pages from start, and as the Y axis points upwards, you need to subtract the bottom margin from this vertical position to find out how much space is left for your new table.
Note that we aren't happy with the getVerticalPosition() method at iText: having a getter that changes the content of the document isn't very elegant. In cases like yours, we prefer working with ColumnText to take charge over the layout process intstead of letting iText decide where to split a table.


text:
Q: Access all the form data in AngularJS I have the following code
<form method="POST">

{{c.value}}
<input class="form-control" type="text" ng-if="c.type == 3" name="field_{{c.id}}" placeholder="{{c.label}}" pattern="{{c.regex}}" value="{{c.defaultValue}}" />

 <nvd3-pie-chart ng-if="pieChart" data="pieChartData" id="pieChartExample" height="350" showlabels="true" interactive="true" x="xPieFunction()" y="yPieFunction()"><svg height="250"></svg></nvd3-pie-chart>

{{ c.label }}

<input type="checkbox" name="field_{{c.id}}" value="defaultValues[$index]"  /> {{chk.name}}

<button ng-click="back()" ng-if="$index != 0" class="btn btn-primary pull-left">Back</button>
<button ng-if="canContinue" ng-click="submit()" class="btn btn-primary pull-right">Next</button>

Some of the elements are dynamically used depending upon the requirement. For example in some cases only the text input will be visible while at some cases both text and checkbox and few additional inputs will be visible. The name atribute of these form elements also varies as you can see it is set from the data which is passed to the form
example
Scenario 1
input id = 4
input name = field_4
Scenario 2
input id = 1
input name = field_1
I have this function in my controller
$scope.submit = function(){                };
Here i want to get all the posted data. Currently as per what i have searched and understood i need to specify the ng-model attribute and then use $scope to get the data but due to the limitations i.e the dynamic naming i'm unsure how to do this.


text:
Q: Solving PDE with Matlab `sol = pdepe(m,@ParticleDiffusionpde,@ParticleDiffusionic,@ParticleDiffusionbc,x,t);
% Extract the first solution component as u.
u = sol(:,:,:);

function [c,f,s] = ParticleDiffusionpde(x,t,u,DuDx)
global Ds
c = 1/Ds;
f = DuDx;
s = 0;

function u0 = ParticleDiffusionic(x)
global qo
u0 = qo;

function [pl,ql,pr,qr] = ParticleDiffusionbc(xl,ul,xr,ur,t,x)

global Ds K n
global Amo Gc kf rhop
global uavg
global dr R nr

sum = 0;
for i = 1:1:nr-1
r1 = (i-1)*dr; % radius at i
r2 = i * dr; % radius at i+1
r1 = double(r1); % convert to double precision
r2 = double(r2);
sum = sum + (dr / 2 * (r1*ul+ r2*ur));
end;
uavg = 3/R^3 * sum;

ql = 1;
pl = 0;

qr = 1;
pr = -((kf/(Ds.*rhop)).*(Amo - Gc.*uavg - ((double(ur/K)).^2).^(n/2) ));`

dq(r,t)/dt = Ds( d2q(r,t)/dr2 + (2/r)*dq(r,t)/dr )

q(r, t=0) = 0

dq(r=0, t)/dr = 0

dq(r=dp/2, t)/dr = (kf/Ds*rhop) [C(t) - Cp(at r = dp/2)]

q = solid phase concentration of trace compound in a particle with radius dp/2

C = bulk liquid concentration of trace compound

Cp = trace compound concentration at particle surface

I want to solve the above pde with initial and boundary conditions given. Tried Matlab's pdepe, but does not work satisfactorily. Maybe the boundary conditions is creating problem for me. I also used this isotherm equation for equilibrium: q = K*Cp^(1/n). This is convection-diffusion equation but i could not find any write ups that addresses solving this type of equation properly.

A: There are two problems with the current implementation.
Incorrect Source Term
The PDE you are attempting to solve has the form

which has the equivalent form

where the last term arises due to the factor of 2 in the original PDE.
The last term needs to be incorporated into pdepe via a source term.
Calculation of q average
The current implementation attempts to calculate the average value of q using the left and right values of q passed to the boundary condition function.
This is incorrect.
The average value of q needs to be calculated from a vector of up-to-date values of the quantity.
However, we have the complication that the only function to receive all mesh values is ParticleDiffusionpde; however, the mesh values passed to that function are not guaranteed to be from the mesh we provided.
Solution: use events (as described in the pdepe documentation).
This is a hack since the event function is meant to detect zero-crossings, but it has the advantage that the function is given all values of q on the mesh we provide.
So, the working example below (you'll notice I set all of the parameters to 1 since I didn't know better) uses the events function to update a variable qStore that can be accessed by the boundary condition function (see here for an explanation), and the boundary condition function performs a vectorized trapezoidal integration for the average calculation.
Working Example
function [] = ParticleDiffusion()

    %   Parameters
    Ds   = 1;
    q0   = 0;
    K    = 1;
    n    = 1;
    Amo  = 1;
    Gc   = 1;
    kf   = 1;
    rhop = 1;

    %   Space
    rMesh = linspace(0,1,10);
    rMesh = rMesh(:) ;
    dr    = rMesh(2) - rMesh(1) ;

    %   Time
    tSpan = linspace(0,1,10);

    %   Vector to store current u-value
    qStore = zeros(size(rMesh));

    options.Events = @(m,t,x,y) events(m,t,x,y);

    %   Solve
    [sol,~,~,~,~] = pdepe(1,@ParticleDiffusionpde,@ParticleDiffusionic,@ParticleDiffusionbc,rMesh,tSpan,options);

    %   Use the events function to update qStore
    function [value,isterminal,direction] = events(m,~,~,y)
        qStore     = y; % Value of q on rMesh
        value      = m; % Since m is constant, it will never be zero (no event detection)
        isterminal = 0; % Continue integration
        direction  = 0; % Detect all zero crossings (not important)
    end

    function [c,f,s] = ParticleDiffusionpde(r,~,~,DqDr)

        %   Define the capacity, flux, and source
        c = 1/Ds;
        f = DqDr;
        s = DqDr./r;

    end

    function u0 = ParticleDiffusionic(~)
        u0 = q0;
    end

    function [pl,ql,pr,qr] = ParticleDiffusionbc(~,~,R,ur,~)

        %   Calculate average value of current solution
        qL    = qStore(1:end-1);
        qR    = qStore(2: end );
        total = sum((qL.*rMesh(1:end-1) + qR.*rMesh(2:end))) * dr/2;
        qavg  = 3/R^3 * total;

        %   Left boundary
        pl = 0;
        ql = 1;

        %   Right boundary
        qr = 1;
        pr = -(kf/(Ds.*rhop)).*(Amo - Gc.*qavg - (ur/K).^n);
    end

end


text:
Q: Mongoose - How to handle the result after using the populate method? I´m starting a work with mongoose. I have created 2 schemas . The second schema with reference to the first. The schemas are :
User.js
const Schema = mongoose.Schema;
const userSchema = new Schema({
  username: {type: String, unique: true},
  first_name: String,
  middle_name: String,
  first_surname: String,
  second_surname: String,
  email: String,
  password: String
});
const UserModel = mongoose.model('user', userSchema);

Resource.js
const Schema = mongoose.Schema;
const User = require('models/user');
const resourceSchema = new Schema({
  resourceType: String,
  creator: {type: Schema.Types.ObjectId, ref: 'user'},
  creationTime: String
});

const ResourceModel = mongoose.model('resource', resourceSchema);

Now I want to make a query to know the user who has created a resource. Here , I use the Populate Method,according to the documentation of mongoose Documentacion about Populate. I have tried several options:
Resources.js
  ResourceModel.findOne({'_id': options.resourceId}).populate('creator').exec().then(resource => {
    log.info(resource.creator.username);
  });

The log.info return a undefined. If I change the code :
 ResourceModel.findOne({'_id': options.resourceId}).populate('creator').exec().then(resource => {
        log.info(resource.creator);
      });

The log.info return this:
$__: {
      "strictMode": true,
      "getters": {},
      "wasPopulated": true,
      "activePaths": {
        "paths": {
          "username": "init",
          "second_surname": "init",
          "password": "init",
          "middle_name": "init",
          "first_surname": "init",
          "first_name": "init",
          "email": "init",
          "_id": "init"
        },
        "states": {
          "ignore": {},
          "default": {},
          "init": {
            "username": true,
            "second_surname": true,
            "password": true,
            "middle_name": true,
            "first_surname": true,
            "first_name": true,
            "email": true,
            "_id": true
          },
          "modify": {},
          "require": {}
        },
        "stateNames": [
          "require",
          "modify",
          "init",
          "default",
          "ignore"
        ]
      },
      "emitter": {
        "domain": {
          "domain": null,
          "_events": {},
          "_eventsCount": 1,
          "members": [
            {
              "_readableState": {
                "objectMode": false,
                "highWaterMark": 16384,
                "buffer": [],
                "length": 0,
                "pipes": null,
                "pipesCount": 0,
                "flowing": true,
                "ended": true,
                "endEmitted": true,
                "reading": false,
                "sync": true,
                "needReadable": false,
                "emittedReadable": false,
                "readableListening": false,
                "resumeScheduled": false,
                "defaultEncoding": "utf8",
                "ranOut": false,
                "awaitDrain": 0,
                "readingMore": false,
                "decoder": null,
                "encoding": null
              },
              "readable": false,
              "domain": "[Circular]",
              "_events": {},
              "_eventsCount": 2,
              "socket": {
                "_connecting": false,
                "_hadError": false,
                "_handle": {
                  "bytesRead": 746,
                  "_externalStream": {},
                  "fd": 16,
                  "reading": true,
                  "owner": "[Circular]",
                  "onconnection": null,
                  "writeQueueSize": 0
                },
                "_parent": null,
                "_host": null,
                "_readableState": {
                  "objectMode": false,
                  "highWaterMark": 16384,
                  "buffer": [],
                  "length": 0,
                  "pipes": null,
                  "pipesCount": 0,
                  "flowing": true,
                  "ended": false,
                  "endEmitted": false,
                  "reading": true,
                  "sync": false,
                  "needReadable": true,
                  "emittedReadable": false,
                  "readableListening": false,
                  "resumeScheduled": false,
                  "defaultEncoding": "utf8",
                  "ranOut": false,
                  "awaitDrain": 0,
                  "readingMore": false,
                  "decoder": null,
                  "encoding": null
                },
                "readable": true,
                "domain": null,
                "_events": {
                  "end": [
                    null,
                    null
                  ],
                  "drain": [
                    null,
                    null
                  ],
                  "close": [
                    null,
                    null
                  ]
                },
                "_eventsCount": 10,
                "_writableState": {
                  "objectMode": false,
                  "highWaterMark": 16384,
                  "needDrain": false,
                  "ending": false,
                  "ended": false,
                  "finished": false,
                  "decodeStrings": false,
                  "defaultEncoding": "utf8",
                  "length": 0,
                  "writing": false,
                  "corked": 0,
                  "sync": true,
                  "bufferProcessing": false,
                  "writecb": null,
                  "writelen": 0,
                  "bufferedRequest": null,
                  "lastBufferedRequest": null,
                  "pendingcb": 0,
                  "prefinished": false,
                  "errorEmitted": false,
                  "bufferedRequestCount": 0,
                  "corkedRequestsFree": {
                    "next": null,
                    "entry": null
                  }
                },
                "writable": true,
                "allowHalfOpen": true,
                "destroyed": false,
                "_bytesDispatched": 0,
                "_sockname": null,
                "_pendingData": null,
                "_pendingEncoding": "",
                "server": {
                  "domain": null,
                  "_events": {
                    "connection": [
                      null,
                      null
                    ],
                    "clientError": [
                      null,
                      null
                    ]
                  },
                  "_eventsCount": 9,
                  "_connections": 1,
                  "_handle": {
                    "bytesRead": 0,
                    "_externalStream": {},
                    "fd": 15,
                    "reading": false,
                    "owner": "[Circular]",
                    "onread": null,
                    "writeQueueSize": 0
                  },
                  "_usingSlaves": false,
                  "_slaves": [],
                  "_unref": false,
                  "allowHalfOpen": true,
                  "pauseOnConnect": false,
                  "httpAllowHalfOpen": false,
                  "timeout": 120000,
                  "_pendingResponseData": 0,
                  "_connectionKey": "6::::3000"
                },
                "_server": "[Circular]",
                "_idleTimeout": 120000,
                "_idleNext": {
                  "_idleNext": "[Circular]",
                  "_idlePrev": "[Circular]"
                },
                "_idlePrev": "[Circular]",
                "_idleStart": 21855,
                "parser": {
                  "_headers": [],
                  "_url": "",
                  "_consumed": true,
                  "socket": "[Circular]",
                  "incoming": "[Circular]",
                  "outgoing": null,
                  "maxHeaderPairs": 2000
                },
                "_paused": false,
                "_consuming": true,
                "_httpMessage": {
                  "domain": "[Circular]",
                  "_events": {},
                  "_eventsCount": 1,
                  "output": [],
                  "outputEncodings": [],
                  "outputCallbacks": [],
                  "outputSize": 0,
                  "writable": true,
                  "_last": false,
                  "chunkedEncoding": false,
                  "shouldKeepAlive": true,
                  "useChunkedEncodingByDefault": true,
                  "sendDate": true,
                  "_removedHeader": {},
                  "_contentLength": null,
                  "_hasBody": true,
                  "_trailer": "",
                  "finished": false,
                  "_headerSent": false,
                  "socket": "[Circular]",
                  "connection": "[Circular]",
                  "_header": null,
                  "_headers": null,
                  "_headerNames": {},
                  "log": {
                    "domain": null,
                    "_events": {},
                    "_eventsCount": 0,
                    "_level": 30,
                    "streams": [
                      {
                        "type": "stream",
                        "stream": {
                          "_connecting": false,
                          "_hadError": false,
                          "_handle": {
                            "bytesRead": 0,
                            "_externalStream": {},
                            "fd": 1,
                            "writeQueueSize": 0,
                            "owner": "[Circular]"
                          },
                          "_parent": null,
                          "_host": null,
                          "_readableState": {
                            "objectMode": false,
                            "highWaterMark": 16384,
                            "buffer": [],
                            "length": 0,
                            "pipes": null,
                            "pipesCount": 0,
                            "flowing": null,
                            "ended": false,
                            "endEmitted": false,
                            "reading": false,
                            "sync": true,
                            "needReadable": false,
                            "emittedReadable": false,
                            "readableListening": false,
                            "resumeScheduled": false,
                            "defaultEncoding": "utf8",
                            "ranOut": false,
                            "awaitDrain": 0,
                            "readingMore": false,
                            "decoder": null,
                            "encoding": null
                          },
                          "readable": false,
                          "domain": null,
                          "_events": {},
                          "_eventsCount": 3,
                          "_writableState": {
                            "objectMode": false,
                            "highWaterMark": 16384,
                            "needDrain": false,
                            "ending": false,
                            "ended": false,
                            "finished": false,
                            "decodeStrings": false,
                            "defaultEncoding": "utf8",
                            "length": 0,
                            "writing": false,
                            "corked": 0,
                            "sync": false,
                            "bufferProcessing": false,
                            "writecb": null,
                            "writelen": 0,
                            "bufferedRequest": null,
                            "lastBufferedRequest": null,
                            "pendingcb": 0,
                            "prefinished": false,
                            "errorEmitted": false,
                            "bufferedRequestCount": 0,
                            "corkedRequestsFree": {
                              "next": null,
                              "entry": null
                            }
                          },
                          "writable": true,
                          "allowHalfOpen": false,
                          "destroyed": false,
                          "_bytesDispatched": 766,
                          "_sockname": null,
                          "_writev": null,
                          "_pendingData": null,
                          "_pendingEncoding": "",
                          "server": null,
                          "_server": null,
                          "_type": "pipe",
                          "fd": 1,
                          "_isStdio": true
                        },
                        "raw": false,
                        "level": 30,
                        "closeOnExit": false
                      }
                    ],
                    "serializers": null,
                    "src": false,
                    "fields": {
                      "name": "hommer-ml",
                      "module": "log",
                      "hostname": "sd-dev",
                      "pid": 14028
                    }
                  },
                  "_time": 1471589378213,
                  "acceptable": [
                    "application/json",
                    "text/plain",
                    "application/octet-stream",
                    "application/javascript"
                  ],
                  "formatters": {},
                  "req": "[Circular]",
                  "serverName": "hommer-ml",
                  "methods": [
                    "GET"
                  ]
                }
              },
              "connection": "[Circular]",
              "httpVersionMajor": 1,
              "httpVersionMinor": 1,
              "httpVersion": "1.1",
              "complete": true,
              "headers": {
                "host": "localhost:3000",
                "authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmaXJzdF9uYW1lIjoiamVzdXMiLCJtaWRkbGVfbmFtZSI6Implc3VzIiwiZmlyc3Rfc3VybmFtZSI6ImNhcm1vbmEiLCJpZCI6IjU3OTcyNzQ4NjkxZmZhNmY0MWFlYWQ4YyIsImhvc3QiOiIxMC4wLjIuMiIsImlhdCI6MTQ3MDEyNjIyMH0._qU7nBVrWb0m5Q__dA8FCgjaKp47Nnv1zB9rzjn4CNY",
                "user-agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
                "content-type": "application/json",
                "accept": "*/*",
                "accept-encoding": "gzip, deflate, sdch",
                "accept-language": "en-US,en;q=0.8,es;q=0.6",
                "x-forwarded-for": "10.0.2.2",
                "x-forwarded-host": "localhost:8080",
                "x-forwarded-server": "127.0.1.1",
                "connection": "Keep-Alive"
              },
              "rawHeaders": [
                "Host",
                "localhost:3000",
                "Authorization",
                "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmaXJzdF9uYW1lIjoiamVzdXMiLCJtaWRkbGVfbmFtZSI6Implc3VzIiwiZmlyc3Rfc3VybmFtZSI6ImNhcm1vbmEiLCJpZCI6IjU3OTcyNzQ4NjkxZmZhNmY0MWFlYWQ4YyIsImhvc3QiOiIxMC4wLjIuMiIsImlhdCI6MTQ3MDEyNjIyMH0._qU7nBVrWb0m5Q__dA8FCgjaKp47Nnv1zB9rzjn4CNY",
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36",
                "Content-Type",
                "application/json",
                "Accept",
                "*/*",
                "Accept-Encoding",
                "gzip, deflate, sdch",
                "Accept-Language",
                "en-US,en;q=0.8,es;q=0.6",
                "X-Forwarded-For",
                "10.0.2.2",
                "X-Forwarded-Host",
                "localhost:8080",
                "X-Forwarded-Server",
                "127.0.1.1",
                "Connection",
                "Keep-Alive"
              ],
              "trailers": {},
              "rawTrailers": [],
              "upgrade": false,
              "url": "/api/authorizations/57b566ee593e745b25008983/permission",
              "method": "GET",
              "statusCode": null,
              "statusMessage": null,
              "client": "[Circular]",
              "_consuming": true,
              "_dumped": false,
              "log": {
                "domain": "[Circular]",
                "_events": {},
                "_eventsCount": 0,
                "_level": 30,
                "streams": [
                  {
                    "type": "stream",
                    "stream": "[Circular]",
                    "raw": false,
                    "level": 30,
                    "closeOnExit": false
                  }
                ],
                "serializers": null,
                "src": false,
                "fields": {
                  "name": "hommer-ml",
                  "module": "log",
                  "hostname": "sd-dev",
                  "pid": 14028,
                  "req_id": "cb1702ef-2c55-49bb-9cbd-ad5e65eee8f8",
                  "action": "GET",
                  "ip": "10.0.2.2"
                }
              },
              "_time": 1471589378213,
              "serverName": "hommer-ml",
              "_version": "*",
              "_url": {
                "protocol": null,
                "slashes": null,
                "auth": null,
                "host": null,
                "port": null,
                "hostname": null,
                "hash": null,
                "search": null,
                "query": null,
                "pathname": "/api/authorizations/57b566ee593e745b25008983/permission",
                "path": "/api/authorizations/57b566ee593e745b25008983/permission",
                "href": "/api/authorizations/57b566ee593e745b25008983/permission"
              },
              "_cacheURL": "/api/authorizations/57b566ee593e745b25008983/permission",
              "params": {
                "resource_id": "57b566ee593e745b25008983"
              },
              "context": "[Circular]",
              "route": {
                "path": "api/authorizations/:resource_id/permission",
                "method": "GET",
                "versions": [],
                "name": "getapiauthorizationsresource_idpermission"
              },
              "_dtraceId": 1,
              "_anonFuncCount": 2,
              "_currentRoute": "getapiauthorizationsresource_idpermission",
              "_currentHandler": "handler-1",
              "_timerMap": {
                "bunyan": [
                  0,
                  297414
                ],
                "parseQueryString": [
                  0,
                  115094
                ],
                "readBody": [
                  0,
                  1285054
                ],
                "parseBody": [
                  0,
                  684934
                ],
                "logContext": [
                  0,
                  1316491
                ],
                "handler-0": [
                  0,
                  2723801
                ],
                "handler-1": [
                  970057,
                  332862660
                ]
              },
              "_id": "cb1702ef-2c55-49bb-9cbd-ad5e65eee8f8",
              "timers": [
                {
                  "name": "bunyan",
                  "time": "[Circular]"
                },
                {
                  "name": "parseQueryString",
                  "time": "[Circular]"
                },
                {
                  "name": "readBody",
                  "time": "[Circular]"
                },
                {
                  "name": "parseBody",
                  "time": "[Circular]"
                },
                {
                  "name": "logContext",
                  "time": "[Circular]"
                },
                {
                  "name": "handler-0",
                  "time": "[Circular]"
                }
              ],
              "query": {},
              "_clen": false,
              "_contentType": "application/json",
              "body": "",
              "user": {
                "first_name": "jesus",
                "middle_name": "jesus",
                "first_surname": "carmona",
                "id": "57972748691ffa6f41aead8c",
                "host": "10.0.2.2",
                "iat": 1470126220
              }
            },
            "[Circular]"
          ]
        },
        "_events": {},
        "_eventsCount": 0,
        "_maxListeners": 0
      }
    }
    --
    _doc: {
      "username": "jecargar",
      "second_surname": "garcia",
      "password": "test",
      "middle_name": "jesus",
      "first_surname": "gonzalez",
      "first_name": "juan",
      "email": "email@email.com",
      "_id": "57972748691ffa6f41aead8c"
    }
    --
    _pres: {
      "$__original_save": [
        null,
        null
      ]
    }
    --
    _posts: {
      "$__original_save": []
    }

According to the above result, acceding to ._doc.creator, we can find the attributes of the creator of the resource. Finally, I use this:
 ResourceModel.findOne({'_id': options.resourceId}).populate('creator').exec().then(resource => {
    log.info(resource.creator._doc.username);
  });

The log.info show the creator´s username but I do not know if it's the right way to use Populate method.
Thanks for your help.

A: Is there an error thrown if you use:
ResourceModel.findOne({_id : options.resourceId})
             .populate('creator')
             .exec((error, resource) => {
                   if (error) throw error;
                   console.log(resource._id);
                   console.log(resource.creator._id);
                   console.log(resource.creator.username);
              });

Is there an export in your models? I'm not sure if  you need it, but I use something like:
var mongoose = require('mongoose');
var OtherModel = require('./OtherModel.js');
var Schema = mongoose.Schema;

module.exports = mongoose.model('User', new Schema({
    linkedField: {type: Schema.Types.ObjectId, ref: 'other'}
});

and then I use User.findOne({_id : ... in my routes

A: handle response this way
 ResourceModel.findOne({
     '_id': options.resourceId
 })
 .populate('creator')
 .exec(function(err, res) {
     console.log(err)
     console.log(res)

 })


text:
Q: Decoding URL containing unicode characters I have the following code in a Mako template:
${inv_name}

This applies url escaping to  the name string of an object representing a company.  The resulting escaped string is then used in a url.  The Mako documentation states that url encoding is provided using urllib.quote_plus(string.encode('utf-8')).
On the server I receive the company name part into the argument investment_name:
def Investment(client, fund_name, investment_name, **kwargs):
    client          = urllib.unquote_plus(client)
    fund_name       = urllib.unquote_plus(fund_name)
    investment_name = urllib.unquote_plus(investment_name)

I then use investment_name as a key back in to the same dictionary from which it was extracted in the template.
This works fine for all the standard cases, such as spaces, slashes, and single quotes in the company name.  However, it fails if the company name contains unicode characters outside of the ascii character set.
For instance, the url for company name "Eptisa Servicios de Ingeniería S.L." is rendered as "Eptisa+Servicios+de+Ingenier%C3%ADa+S.L."  When this value arrives back at the server, I'm reversing the url escaping but clearly failing to decode the unicode properly because my attempt to use the result as a dictionary key generates a key error.
I've tried adding unicode decoding in these two forms, without luck:
    investment_name = urllib.unquote_plus(investment_name.decode('utf-8'))
    investment_name = urllib.unquote_plus(investment_name.encode('raw_unicode_escape').decode('utf-8'))

Can anyone suggest what I must do to "Eptisa+Servicios+de+Ingenier%C3%ADa+S.L." to turn it back into "Eptisa Servicios de Ingeniería S.L."?

A: Do it in the reverse order: first unquote then .decode('utf-8')
Do not mix bytes and Unicode strings.
Example
import urllib

q = "Eptisa+Servicios+de+Ingenier%C3%ADa+S.L."
b = urllib.unquote_plus(q)
u = b.decode("utf-8")
print u

Note: print u might produce UnicodeEncodeError. To fix it:
print u.encode(character_encoding_your_console_understands)

Or set PYTHONIOENCODING environment variable.
On Unix you could try locale.getpreferredencoding() as character encoding, on Windows see output of chcp


text:
Q: Irrespective of mentioning int as return type when I return string, I am still not getting error! why is that? What is the use of mentioning a return type?
def func() -> int:
    print("H")
    return "Harith"

x = func()
print(x)

A: This is perfectly normal, as from the Python documentation for type hints:

Note: The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.

Of course, it would only be reasonable to follow the type hints.


text:
Q: Why %{HTTP_HOST} doesn't work while HTTP_HOST literal string works? I have the next Apache code to prevent hotlinking, and it works.
RewriteCond %{HTTP_REFERER} ^$ [OR]
RewriteCond %{HTTP_REFERER} !^https?://itransformer.*$ [NC]
RewriteRule /usuarios/.*\.(gif|jpe?g|png|wbmp)$ - [R=404,L]

The questions are two:
1.If I change the above to:
RewriteCond %{HTTP_REFERER} ^$ [OR]
RewriteCond %{HTTP_REFERER} !^https?://%{HTTP_HOST}.*$ [NC]
RewriteRule /usuarios/.*\.(gif|jpe?g|png|wbmp)$ - [R=404,L]

it doesn't work. %{HTTP_HOST} is equal to itransformer (in my localhost), so I don't understand why it isn't working in this way.
2. The default 404 page is shown instead of my custom 404 page that is shown in all other 404 responses. What can be happening here?

A: *

*Reason why it doesn't is that you cannot use these Apache internal variables in right hand side of RewriteCond.

*I just noticed R=404. If you need custom 404 handler then make sure you have similar line like this on top of your .htaccess:
ErrorDocument 404 /404.php


text:
Q: Vaadin Flow 14 how to set HttpOnly cookie flag We have a Vaadin Flow 14.x enterprise app and a recent security review highlighted the lack of HttpOnly flag being set with the JSESSIONID cookie.  How do we set this flag with Vaadin Flow 14?  I've searched quite a bit and have not found any references to this.
Our app uses embedded jetty, but that probably doesn't matter in this case as its Vaadin that's setting JSESSIONID from what we can tell.
SOLUTION
The solution as described below is to configure embedded jetty to set HttpOnly.  In my case I did this via:
WebAppContext context = new WebAppContext();
context.getSessionHandler().setHttpOnly(true);

A: The key is to configure this through Jetty. Vaadin is just using javax.servlet.http.HttpSession without directly touching any low-level session management details such as cookies.


text:
Q: Jquery animate () issue I have created a jquery animation, when you click on one of the buttons the hidden div slides from left: -650px; to left: 0px;click here to see example However i noticed when you click on another button to reveal another hidden div, the pervious hidden div does not go back to it's original position of left: -650px; it stay at left: 0; does anyone know what i need to added in order to achieve this...?
HTML:

block

test

test

Lists

hello

test

JS
$(document).ready(function () {
    $('.proBtn').click(function () {
        $('li').removeClass('active');
        $('li a').removeClass('blue');
        $(this).parent("li").addClass('active');
        $(this).addClass('blue');
    });

    $('#one').click(function () {
        $('#two-bck').animate({
            left: '-650px;',
            opacity: 0
        }, 500).removeClass('animated');
        $('#three-bck').animate({
            left: '-650px;',
            opacity: 0
        }, 500).removeClass('animated');
        $('#four-bck').animate({
            left: '-650px;',
            opacity: 0
        }, 500).removeClass('animated');
        $('#one-bck').addClass('animated').animate({
            left: '0px',
            opacity: 1
        }, 500);
    });

    $('#two').click(function () {
        $('#one-bck').animate({
            left: '-650px;',
            opacity: 0
        }, 500).removeClass('animated');
        $('#three-bck').animate({
            left: '-650px;',
            opacity: 0
        }, 500).removeClass('animated');
        $('#four-bck').animate({
            left: '-650px;',
            opacity: 0
        }, 1500).removeClass('animated');
        $('#two-bck').addClass('animated').animate({
            left: '0px',
            opacity: 1
        }, 500);;
    });

    $('#three').click(function () {
        $('#one-bck').animate({
            left: '-650px;',
            opacity: 0
        }, 500).removeClass('animated');
        $('#two-bck').animate({
            left: '-650px;',
            opacity: 0
        }, 500).removeClass('animated');
        $('#four-bck').animate({
            left: '-650px;',
            opacity: 0
        }, 500).removeClass('animated');
        $('#three-bck').addClass('animated').animate({
            left: '-650px;',
            opacity: 0
        }, 500);
    });

});

A: Remove the semi-colon after the 'px' on left:'-650px;' .
Should only be left:'-650px' .

A: You can really try to simplify this apart from just fixing the css and removeClass issue.  Instead of binding event handlers to each of those ids can be a mintenance headache as they all do the same thing. You can add a data attribute to the anchor tags i.e data-target="#three-bck" and select them to be animated. It can all go in just one event handler.
HTML:

block

test

test

Lists

hello

test

JS:
$(document).ready(function () {
    $('.proBtn').click(function () {
        $('li').removeClass('active').find('a').removeClass('blue'); //chain it
        var $this = $(this); //cache this first
        $this.addClass('blue').closest("li").addClass('active');

        $('.mid-block.animated').animate({ //start animate for reverse in case if there is anything already selected
            left: '-650px',
            opacity: 0
        }, 500, function(){
           $(this).removeClass('animated'); //once done remove its class
        }).promise().done(function () { //once this is done start animating your target by selecting the target element from its own data attribute
            $($this.data('target')).addClass('animated').stop(true, true).animate({
                left: '0px',
                opacity: 1
            }, 500);
        });
    });
});

Fiddle


text:
Q: A sequence has the recurrence formula $u_{n+1} = \frac{a-1}{a+1}u_n$. Find the range of values of a that ensure this is a convergent sequence. For the answer of this question, I am told that it is $a > 0$, but if $a$ is $1$ then would the resulting fraction not be $\frac{0}{2}$. Is it still converging then?
Am I wrong in thinking the answer should be $a > 1$ instead?

A: There is nothing wrong with a feaction like $0/2$ where just the numerator is zero; such a fraction is just zero.  The problem is if the _ denominator_ is zero.

A: As commented, you have
$$u_n=\left(\frac{a-1}{a+1}\right)^nu_0$$
and the above converges (to a finite value, that is) iff ( since you're given $\;a>0\;$)
$$\left|\frac{a-1}{a+1}\right|\le1\iff |a-1|\le|a+1|= a+1$$
Now, we can do:
$$\begin{align*}&0<a< 1: \implies -a+1\le a+1\implies 2a\ge0\;,\;\;\text{and this is true in any such case}\\{}\\
&a\ge1: \implies a-1\le a+1\iff -1\le 1\,,\,\,\text{and again this is true in any such case}\end{align*}$$
Thus, the sequence $\;\{u_n\}\;$ converges to a finite value, which is either $\;u_0\;$ o $\;0\;$ , for any value of $\;a>0\;$ .

A: Hint for a geometric solution:
As a geometric sequence, it converges if and only if $\;\dfrac{\lvert a-1\rvert}{\lvert a+1\rvert}\iff\lvert a-1\rvert<\lvert a+1\rvert$.
Now interpret in terms of distance: if $\;b>c$,
$$\lvert a-b\rvert <\lvert a-c\rvert\iff a > \frac{b+c}2.$$


text:
Q: Assign a delayed object to a dask array TypeError: Delayed objects of unspecified length have no len() I have the following setting: a function returning an array and a Dask array.
I want to call the function inside a for loop and fill a dask array with the function's return. This should be done in parallel.
import dask
import numpy as np

def some_function(params):
# do calculations and returns an array X
... # calculations
return some_array

I want to fill the Dask array in parallel in this manner :
( The code below won't work as the output is a delayed object)
if __name__ == '__main__' :

    client = Client(n_workers=4)

    N = 20_000

    # (20,2) is the shape of the returned array by some_function
    X = dask.da.zeros(shape=(N, 20, 2), chunks=(1, 20, 2))

    # List of parameters taken by some_function
    l = [ np.random.random(size=3) for i in range(N)]

    for i, param in enumerate(l):
        output = dask.delayed(some_function)(param)
        X[i] = output

What I want is to be able to do both computations and storage in parallel.
Thanks for your help.

A: You seem to want dask.array.from_delayed, You can then .compute the results later when you need.
import numpy as np
import dask
import dask.array as da
from dask.distributed import Client

@dask.delayed
def some_function(param):
    return np.random.rand(20, 2)

if __name__ == "__main__":
    client = Client(n_workers=2)
    N = 10
    X = da.zeros(shape=(N, 20, 2), chunks=(1, 20, 2))
    l = [np.random.random(size=3) for i in range(N)]

    for i, param in enumerate(l):
        output = some_function(param)
        X[i] = da.from_delayed(output, shape=(20, 2), dtype=np.float64)

Output
print(X[0].compute())

[[0.3521712  0.6159578 ]
 [0.67023109 0.13890086]
 [0.71952075 0.3986291 ]
 [0.76702816 0.84669244]
 [0.82703851 0.72321066]
 [0.92060717 0.77926133]
 [0.27857667 0.2510426 ]
 [0.85014582 0.34709649]
 [0.46328749 0.44324011]
 [0.84134094 0.28890227]
 [0.33616886 0.09771338]
 [0.35734385 0.0832578 ]
 [0.04038898 0.41059205]
 [0.01776568 0.31226509]
 [0.03036941 0.70490505]
 [0.78646762 0.33381309]
 [0.02535621 0.5715431 ]
 [0.16349511 0.37746425]
 [0.11798384 0.87281911]
 [0.26136318 0.59016981]]


text:
Q: Is there any Heroku command to open my app's code? I need to check my app codes in Heroku. By mistake I deleted some code in a file locally but it already hosted on Heroku and I need to write it back locally, so that's why I want to know is there any Heroku command to open the app code.

A: Assuming you deployed to Heroku via git push you should be able to clone your code via Heroku's Git service:
heroku git:clone <your-app-name>

If you already have a local repository connected to Heroku you can try git fetch or git pull as well.
Note that, although this may help you today, it isn't meant to be part of your primary workflow:

Heroku provides the git service primarily for deployment, and the ability to clone from it is offered as a convenience. We strongly recommend you store your code in another git repository such as GitHub and treat that as canonical.

(Also, if you do have a local repository, your previously deployed code should exist in one or more revisions in that repository. Local Git commands like git checkout <revision-hash> -- <path/to/file> are probably a simpler, more direct way to retrieve your code.)


text:
Q: How to create child tag using JaxB annotations? I need to create XML export from my java models using Jaxb annotations.
What I need is the following xml in which  is parent entity which contains multiple  entities which should be as a child tree of order.
<order>
<staffId>1</staffId>
<status>ACTIVE</status>
<id>12</id>
<name>Order 1</name>
     <itemList>
         <item>Item 1</item>
         <item>Item 2</item>
         <item>Item 3</item>
     </itemList>
</order>

Following is my JaxB annotated class
import java.io.Serializable;
import java.util.*;

import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlType(propOrder = {"staffId", "status", "id", "name", "itemList"})
public class Order implements Serializable {

    private static final long serialVersionUID = 1L;
    private int id;
    private int staffId;
    private String status;
    private String name;
    private List<String> itemList = new ArrayList<>();

    @XmlElement
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    @XmlElement
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @XmlElement
    public int getStaffId() {
        return staffId;
    }
    public void setStaffId(int staffId) {
        this.staffId = staffId;
    }
    @XmlElement
    public String getStatus() {
        return status;
    }
    public void setStatus(String status) {
        this.status = status;
    }
    @XmlElement
    public List<String> getItemList() {
        return itemList;
    }
    public void setItemList(List<String> itemList) {
        this.itemList = itemList;
    }
}

But the output I am getting is as per following, in which item list comes in same hierarchy as order.
<order>
    <staffId>1</staffId>
    <status>ACTIVE</status>
    <id>12</id>
    <name>Order 1</name>
    <itemList>Item 1</itemList>
    <itemList>Item 2</itemList>
    <itemList>Item 3</itemList>
</order>

Please suggest me what is missing here.

A: This is a duplicate of JAXB Annotations. What you are looking for is the @XmlElementWrapperannotation used in conjunction with the @XmlElement annotation.
FWIW, Blaise Doughan's blog post on JAXB & Collection Properties has some other useful information on handling collections.


text:
Q: .schema for postgres I'm migrating a database from sqlite3 to postgres and am wondering if there are any short tutorials that can teach me the new syntax.
Also, as a short term question, how do I see the schema of a postgres table which is equivalent to .schema in sqlite?

A: You could use pg_dump command line utility, i.e.:
pg_dump --table <table_name> --schema-only <database_name>

Depending on your environment you probably need to specify connection options (-h, -p, -U switches).

A: You could use \d from within psql:
=> \?
...

Informational
  (options: S = show system objects, + = additional detail)
  \d[S+]                 list tables, views, and sequences
  \d[S+]  NAME           describe table, view, sequence, or index
...

=> \d people
                                           Table "public.people"
         Column         |            Type             |                      Modifiers
------------------------+-----------------------------+-----------------------------------------------------
 id                     | integer                     | not null default nextval('people_id_seq'::regclass)
 created_at             | timestamp without time zone | not null
 updated_at             | timestamp without time zone | not null
...
Indexes:
    "people_pkey" PRIMARY KEY, btree (id)
...
Check constraints:
    "chk_people_latlng" CHECK ((lat IS NULL) = (lng IS NULL))
....

You can also root around in the information_schema if you're not inside psql.

A: If you are using psql (and \d... ) then you can
\set ECHO_HIDDEN

to see the sql for the queries that psql is executing to put together the \d... output-- this is useful not only as sql syntax examples but it also shows you where find, and how to connect, the database metadata.
To get the schema name for a table you can:
SELECT  n.nspname AS schema_name,
        c.relname AS table_name
FROM pg_catalog.pg_class c
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relname = '<table_name>'
;

(don't know how that compares to .schema)

A: Maybe you can use a PostgreSQL Cheat Sheet:
http://www.postgresonline.com/special_feature.php?sf_name=postgresql83_cheatsheet&outputformat=html


text:
Q: Is it safe to touch 1000 Volts DC at 1 mA of constant current? 0.1 mA? 0.01 mA? I would like to study the phenomenon where thousands of volts are safe to touch. Generators like Tesla coil and static electricity generators generate discontinuous sparks, which is why they are safe to touch. If I were to build a Class-E Tesla coil capable of generating 1000 Volts at 0.01 mA of constant current, will it be safe to touch? will I see an arc at all?
My understanding is that in practice, it is not just current or just volts which are the deciding factor in whether or not it is safe to touch, but instead it is both of them combined: Watts. I expect 1 Watt to be safe to touch no matter if it is 1 Volt at 1 Amp, or 1000 Volts at 0.001 Amps, or 0.001 Volts at 1000 Amps.
If my understanding is wrong, please correct me.
Also, how would I then go about generating 1000 Volts DC at 0.01 mA of constant current or anything close for this study?

A: Unless we're talking about being cooked alive, no, it's really not the Watt that kills you. It's the current flowing through your body, making muscles contract through electrochemical reactions, and nerves disfunctional.
To achieve a dangerous current, due to the resistance of skin, your body and your contact to whatever closes the circuit with the source of electricity, you need sufficient voltage. And, of course, as you noticed, even if you have a voltage source, it must be able to source that amount of current without breaking down.
So, your wattage considerations are plain wrong. Wattage is a side effect, but the power spent in the human body has nothing to do with danger. If your 10 kV voltage source can only source 1 mA, it is way safer than a 100 V supply that can supply 100 mA.
Soooo, let's have a graphic:

From this article.
In short: don't ever conduct more than 10 mA through a human body.

A: So I always wondered about this. Finaly it sunk in. You would be talking open circuit 1000V. So once the maximum current available completes the circuit the voltage matches that. At 0.1mA probably about 10V.
If on the other hand 1000A is availiable and say only 12V, because of the resistance of the human body the current this time would drop to next to nothing. Now you could have wet hands and that would change things a bit. But at any current available and say only 1V then nothing would happen. Even if wet perhaps through a cut 10mA at most.


text:
Q: how to subtract DB timestamp from current timestamp in Oracle I have a timestamp field in oracle table. I want to deduct that timestamp field from current timestamp. How can I do that?
Select date_time from test where id = 123;

returns
14-02-12 11:00:00 -03:30 as a result. (Note: date_time type is timestamp).
I want to subtract date_time field from current timestamp. Any help please.


text:
Q: "Except for us" or "Except us" Please check the two sentences below.

*

*No one calls us names except for us.

*No one calls us names except us.

What's the difference between them?

A: In this case, you can use either one:

1a. No one calls us names except for us.
  1b. No one calls us names except us.

In this example "us" is the list of exceptions to the set of all people ("everyone").  When you have a discrete set like this, you can use either one with the same meaning.
But sometimes you don't have a discrete set.  For example:

2a. It was a pleasant day, except for the weather.
  2b. *It was a pleasant day, except the weather.

"A pleasant day" isn't a discrete set of things to which "the weather" is an exception.  As a result, you need except for.

You also use except for at the beginning of a sentence:

3a. Except for me, everyone got to eat cake.
  3b. *Except me, everyone got to eat cake.

But you typically use except before a preposition phrase:

4a. ?She likes to go for walks except for on rainy days.
  4b. She likes to go for walks except on rainy days.

(People do say things like example 4a, but it's a lot less common.)


text:
Q: Could not instantiate implementation: com.thinkaurelius.titan.diskstorage.cassandra.thrift.CassandraThriftStoreManager I have downloaded Titan from the link
[https://github.com/thinkaurelius/titan/wiki/Downloads]
and I started Titan using titan.sh start.
Got this:
Forking Cassandra...
Running nodetool statusthrift... OK (returned exit status 0 and printed string "running").
Forking Elasticsearch...
Connecting to Elasticsearch (127.0.0.1:9300)..... OK (connected to 127.0.0.1:9300).
Forking Gremlin-Server...
Connecting to Gremlin-Server (127.0.0.1:8182)..... OK (connected to 127.0.0.1:8182).
Run gremlin.sh to connect.

Started gremlin shell using gremlin.sh , gemlin shell has started .
But when I ran the below command , i got the below error..
gremlin> graph = TitanFactory.open('conf/titan-cassandra-es.properties')
Could not instantiate implementation: com.thinkaurelius.titan.diskstorage.cassandra.thrift.CassandraThriftStoreManager
Display stack trace? [yN] y
java.lang.IllegalArgumentException: Could not instantiate implementation: com.thinkaurelius.titan.diskstorage.cassandra.thrift.CassandraThriftStoreManager
        at com.thinkaurelius.titan.util.system.ConfigurationUtil.instantiate(ConfigurationUtil.java:55)
        at com.thinkaurelius.titan.diskstorage.Backend.getImplementationClass(Backend.java:473)
        at com.thinkaurelius.titan.diskstorage.Backend.getStorageManager(Backend.java:407)
        at com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration.<init>(GraphDatabaseConfiguration.java:1320)
        at com.thinkaurelius.titan.core.TitanFactory.open(TitanFactory.java:94)
        at com.thinkaurelius.titan.core.TitanFactory.open(TitanFactory.java:62)
        at com.thinkaurelius.titan.core.TitanFactory$open.call(Unknown Source)
        at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:110)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:122)
        at groovysh_evaluate.run(groovysh_evaluate:3)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at org.codehaus.groovy.tools.shell.Interpreter.evaluate(Interpreter.groovy:69)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at org.codehaus.groovy.tools.shell.Groovysh.execute(Groovysh.groovy:185)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at org.codehaus.groovy.tools.shell.Shell.leftShift(Shell.groovy:119)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at org.codehaus.groovy.tools.shell.ShellRunner.work(ShellRunner.groovy:94)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.super$2$work(InteractiveShellRunner.groovy)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:130)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuper0(ScriptBytecodeAdapter.java:150)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.work(InteractiveShellRunner.groovy:123)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at org.codehaus.groovy.tools.shell.ShellRunner.run(ShellRunner.groovy:58)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.super$2$run(InteractiveShellRunner.groovy)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
        at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
        at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1207)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:130)
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuper0(ScriptBytecodeAdapter.java:150)
        at org.codehaus.groovy.tools.shell.InteractiveShellRunner.run(InteractiveShellRunner.groovy:82)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at org.apache.tinkerpop.gremlin.console.Console.<init>(Console.groovy:144)
        at org.codehaus.groovy.vmplugin.v7.IndyInterface.selectMethod(IndyInterface.java:215)
        at org.apache.tinkerpop.gremlin.console.Console.main(Console.groovy:303)
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at com.thinkaurelius.titan.util.system.ConfigurationUtil.instantiate(ConfigurationUtil.java:44)
        ... 46 more
Caused by: com.thinkaurelius.titan.diskstorage.TemporaryBackendException: Temporary failure in storage backend
        at com.thinkaurelius.titan.diskstorage.cassandra.thrift.CassandraThriftStoreManager.getCassandraPartitioner(CassandraThriftStoreManager.java:208)
        at com.thinkaurelius.titan.diskstorage.cassandra.thrift.CassandraThriftStoreManager.<init>(CassandraThriftStoreManager.java:186)
        ... 51 more

If any one knows about this please tell If i miss any configuration changes
update 1:
GREMLIN SERVER Log:
24245 [main] WARN  org.apache.tinkerpop.gremlin.server.GremlinServer  - Graph [graph] configured at [conf/gremlin-server/titan-berkeleyje-server.properties] could not be instantiated and will not be available in Gremlin Server.  GraphFactory message: GraphFactory could not instantiate this Graph implementation [class com.thinkaurelius.titan.core.TitanFactory]
java.lang.RuntimeException: GraphFactory could not instantiate this Graph implementation [class com.thinkaurelius.titan.core.TitanFactory]
    at org.apache.tinkerpop.gremlin.structure.util.GraphFactory.open(GraphFactory.java:82)
    at org.apache.tinkerpop.gremlin.structure.util.GraphFactory.open(GraphFactory.java:70)
    at org.apache.tinkerpop.gremlin.structure.util.GraphFactory.open(GraphFactory.java:104)
    at org.apache.tinkerpop.gremlin.server.GraphManager.lambda$new$27(GraphManager.java:50)
    at java.util.LinkedHashMap$LinkedEntrySet.forEach(LinkedHashMap.java:671)
    at org.apache.tinkerpop.gremlin.server.GraphManager.<init>(GraphManager.java:48)
    at org.apache.tinkerpop.gremlin.server.util.ServerGremlinExecutor.<init>(ServerGremlinExecutor.java:94)
    at org.apache.tinkerpop.gremlin.server.GremlinServer.<init>(GremlinServer.java:88)
    at org.apache.tinkerpop.gremlin.server.GremlinServer.main(GremlinServer.java:290)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.tinkerpop.gremlin.structure.util.GraphFactory.open(GraphFactory.java:78)
    ... 8 more
Caused by: java.lang.IllegalArgumentException: Could not instantiate implementation: com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager
    at com.thinkaurelius.titan.util.system.ConfigurationUtil.instantiate(ConfigurationUtil.java:55)
    at com.thinkaurelius.titan.diskstorage.Backend.getImplementationClass(Backend.java:473)
    at com.thinkaurelius.titan.diskstorage.Backend.getStorageManager(Backend.java:407)
    at com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration.<init>(GraphDatabaseConfiguration.java:1320)
    at com.thinkaurelius.titan.core.TitanFactory.open(TitanFactory.java:94)
    at com.thinkaurelius.titan.core.TitanFactory.open(TitanFactory.java:74)
    ... 13 more
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.thinkaurelius.titan.util.system.ConfigurationUtil.instantiate(ConfigurationUtil.java:44)
    ... 18 more
Caused by: com.thinkaurelius.titan.diskstorage.TemporaryBackendException: Temporary failure in storage backend
    at com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager.ensureKeyspaceExists(AstyanaxStoreManager.java:572)
    at com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager.<init>(AstyanaxStoreManager.java:291)
    ... 23 more
Caused by: com.netflix.astyanax.connectionpool.exceptions.PoolTimeoutException: PoolTimeoutException: [host=127.0.0.1(127.0.0.1):9160, latency=10005(10005), attempts=1]Timed out waiting for connection
    at com.netflix.astyanax.connectionpool.impl.SimpleHostConnectionPool.waitForConnection(SimpleHostConnectionPool.java:231)
    at com.netflix.astyanax.connectionpool.impl.SimpleHostConnectionPool.borrowConnection(SimpleHostConnectionPool.java:198)
    at com.netflix.astyanax.connectionpool.impl.RoundRobinExecuteWithFailover.borrowConnection(RoundRobinExecuteWithFailover.java:84)
    at com.netflix.astyanax.connectionpool.impl.AbstractExecuteWithFailoverImpl.tryOperation(AbstractExecuteWithFailoverImpl.java:117)
    at com.netflix.astyanax.connectionpool.impl.AbstractHostPartitionConnectionPool.executeWithFailover(AbstractHostPartitionConnectionPool.java:352)
    at com.netflix.astyanax.thrift.ThriftClusterImpl.executeSchemaChangeOperation(ThriftClusterImpl.java:146)
    at com.netflix.astyanax.thrift.ThriftClusterImpl.internalCreateKeyspace(ThriftClusterImpl.java:321)
    at com.netflix.astyanax.thrift.ThriftClusterImpl.addKeyspace(ThriftClusterImpl.java:294)
    at com.thinkaurelius.titan.diskstorage.cassandra.astyanax.AstyanaxStoreManager.ensureKeyspaceExists(AstyanaxStoreManager.java:567)
    ... 24 more

A: It looks like your Cassandra cluster/node isn't running correctly. I've never used titan.sh but I'd probably look to verify that Cassandra is booting cleanly and staying up.

A: The message in the log file indicates that the Gremlin Server tried to instantiate a graph configured in conf/gremlin-server/titan-berkeleyje-server.properties. This is probably configured in your gremlin-server.yaml file under graphs->graph.
You already stated in your question that you want to use a graph configured in conf/titan-cassandra-es.properties. So just change that in the gremlin-server.yaml.


text:
Q: Reducing the rows of a dataframe by adding observed values I have experimental data for a number of microscope slides. For each slide I have taken a number of photographic images, and on each image I have a number of specimens. I would like to know show many specimens I have for each slide:
eg: On slide 0, I have four specimens in total (three in image 1, one in image2):
from pandas import DataFrame, Series
import seaborn as sns

data = {'Slide' :      [0,0,0,0,0,0,0,0,0,  0,0,0,    9,9,],
        'Image' :      [1,1,1,1,1,1,1,1,1,  2,2,2,    1,7],
        'Specimen' :   [1,1,1,1,2,2,3,3,3,  1,1,1,    1,1],
        'Foci' :       [8,9,7,9,6,9,7,9,6,  6,7,6,    9,6]}

df = DataFrame(data, columns=['Slide','Image','Specimen','Foci'])
df

I can get part way to an answer, but this is not quite what I need, as I still need to add up the specimen numbers for each slide:
df.groupby(['Slide','Image']).max()

A: The groupby feature allows you to essentially "pivot" the results like you would in excel:
df = df.groupby(['Slide','Image']).Specimen.nunique()

The .nunique() function will give you the number of unique values per image per slide. You can then use .reset_index() on this series to convert it back to a dataframe.
df.reset_index(inplace=True)

df
    Slide   Image   Specimen
0   0       1       3
1   0       2       1
2   9       1       1
3   9       7       1

If you then want to find just the sum of values by slide you can use one final groupby:
df =  df.groupby('Slide').sum()['Specimen']
df
Slide
0    4
9    2

A: You can get the .nunique() Specimen for each .groupby(['Slide', 'Image') like so:
uniques = df.groupby(['Slide', 'Image'])['Specimen'].nunique()

Then you can .sum() for each slide:
uniques.groupby(level='Slide').sum()

to get:
Slide
0    4
9    2


text:
Q: PUT request with without every field from the DTO model I want to make PUT request in ASP .NET CORE that user can make to update his note.
It's my UpdateNoteDTO:
    public class UpdateNoteDto
    {
        [MaxLength(50)]
        public string NoteTitle { get; set; }
        [MaxLength(500)]
        public string NoteBody { get; set; }
        public int Color { get; set; }
    }

and it's my Update method:
        public void Update(UpdateNoteDto dto, int noteID)
        {
            var note = _dbContext
                       .Notes
                       .FirstOrDefault(r => r.Id == noteID);

            if (note is null)
            {
                throw new NotFoundException("Note not found");
            }

            note.NoteTitle = dto.NoteTitle == string.Empty
                             || dto.NoteTitle is null
                             ? note.NoteTitle : dto.NoteTitle;

            note.NoteBody = dto.NoteBody == string.Empty
                            || dto.NoteBody is null
                            ? note.NoteBody : dto.NoteBody;

            note.Color = dto.Color == 1 ? note.Color : dto.Color;

            _dbContext.SaveChanges();
        }

I want to make request that user can make to change single field without need for declare all of them. This code what i wrote is working but i bet there is better solution for this :D

A: The way you are doing it looks fine but I would suggest two changes,

*

*If you plan to use the endpoint for updating one or some values it's better to change request type to PATCH, the HTTP PATCH request method applies partial modifications to a resource whereas HTTP PUT changes whole resource.

*To easily add conditions for mapping DTOs to entity models I would rather use Automapper which allows user to declare mapping conditions in a single spot and use IMapper interface to map the models.
For example if you have two classes:

public class UpdateNoteDto
{
    [MaxLength(50)]
    public string NoteTitle { get; set; }
    [MaxLength(500)]
    public string NoteBody { get; set; }
    public int Color { get; set; }
}

public class Note
{
    public int Id { get; set; }
    public string NoteTitle { get; set; }
    public string NoteBody { get; set; }
    public int Color { get; set; }
}

you can map them by creating a mapping profile with conditions instead of using if, switch or any other way of comparing whether to map or not
mapping Profile could look like this:
public class NoteProfile: Profile
{
    public NoteProfile()
    {
        CreateMap<UpdateNoteDto, Note>()
            .ForMember(dest => dest.NoteTitle, opt => opt.Condition(src => !string.IsNullOrEmpty(src.NoteTitle)))
            .ForMember(dest => dest.NoteBody, opt => opt.Condition(src => !string.IsNullOrEmpty(src.NoteBody)))
            .ForMember(dest => dest.Color, opt => opt.Condition(src => src.Color != default))
            .ForMember(dest => dest.Id, opt => opt.Ignore());
    }
}

and update the Update(UpdateNoteDto dto, int noteID) function correspondingly:
public void Update(UpdateNoteDto dto, int noteID)
{
    var noteToUpdate = _dbContext
               .Notes
               .FirstOrDefault(r => r.Id == noteID);

    if (note is null)
    {
        throw new NotFoundException("Note not found");
    }

    var note = _mapper.Map(dto, note);

    _dbContext.Update(note);
    _dbContext.SaveChanges();
}

A: client should handled  this issue
Or
if you want update an entity, it is better to use PATCH

If the client wants the previous data not to be edited
It should send you the previous data
Maybe, for example, the user wants to field the "NoteBody" value as empty In which case it cannot do this


text:
Q: TASK: react-native-doc-viewer compileDebugJavaWithJavac FAILED I am getting this errorr while taking android build react-native, screenshot provided below
TASK: react-native-doc-viewer compileDebugJavaWithJavac FAILED
package com.facebook.react.views.webview does not exist

https://i.stack.imgur.com/H17A8.png

A: The deprecated class com.facebook.react.views.webview is not actually being used. It is just a redundant import. Could be fixed by removing the import in node_modules/react-native-doc-viewer/android/src/main/java/com/reactlibrary/RNReactNativeDocViewerModule.java
Remove the ununsed import:
import com.facebook.react.views.webview.ReactWebViewManager;


text:
Q: How do I find the starting and end block numbers of a file using terminal in Ubuntu? Is there any command that will output the beginning and ending hard disk blocks of a file ?
(Solution marked accepted)

Update:
The answers below solve the initial query. I thank 'em all.  But I'm a bit confused with LBA not fitting in the block range shown by fdisk. (however, halving the number aggreees with range; so does that imply LBA blocksize of 2048 ?!?)

A: Use hdparm:
sudo hdparm --fibmap FILENAME

where FILENAME is the path to your file.
Regarding your calculations:
97504*512/1024^2=47,6 that's how you do this.
Regarding the not fitting in the block range:
You circled the NTFS drive in the fdisk output, which ends at LBA 251863039, the hdparm output reports, that the file system on which the tested file resides begins at LBA 251863040. So you are looking at the wrong file system in the fdisk output, because your file is on sda2 not on sda1.

A: The tools you are probably looking for a tail and head.
tail -5 file.txt

head -5 file.txt

This will give you the last 5 (tail) and the first 5 lines (head) of file.txt

A: For an ext4 filesystem, the command
sudo debugfs /dev/sda1 <<<"blocks /boot/vmlinuz-3.11.0-14-generic"

show all blocks used by the given file, so you can extract the first and last blocks as required.