text:
Q: How to invoke a java method asynchronously? Is there any good sample to get started with java synchronous method invocation. I have two methods a and b and have to call b asynchronously. Any suggestion?

A: This is a big topic, with lots of gotchas. But you can get a good start by wrapping your method in a Callable<T> and submitting that to ExecutorService.submit. That will return back a Future<T>, which has a method get(). That last method returns T, but not until the Callable<T> finished.
For instance, let's say foo.b() returns String. You'd do something like:
Callable<String> asyncB = new Callable<String>() {
    @Override
    public String call() {
        foo.b();
    }
};
Future<String> futureB = myExecutorService.submit(asyncB);
// asyncB will now execute on a separate thread,
// which is managed by the ExecutorService
foo.a(); // synchronous call
String resultB = futureB.get();

If you're on Java 8, that first bit can just be:
Callable<String> asyncB = () -> foo.b();

A: If you by any chance are using Spring, they have excellent async support.
http://docs.spring.io/spring/docs/3.0.x/reference/scheduling.html


text:
Q: HashSet uses HashTable as data stucture and HashMap as collection?Memory point of view arrays are not recommended to use? As per this

Underlying data structure for HashSet is hashtable.

But I have also read that HashSet internally uses HashMap to avoid duplicate values which in turn internally uses array of buckets and LinkedList(replaced by tree in Java 8)
So is it right to say that HashSet uses HashTable as data stucture and HashMap as collection?

TreeSet implements the SortedSet interface so duplicate values are not
  allowed.

Does that mean that TreeSet doesn't uses HashMap internally which is used by HashSet to avoid duplicate values?Does LinkedHashSet uses HashMap internally?
As per this

Memory point of view arrays are not recommended to use.

Why?
By what i read before-

Since ArrayList can't be created for primitive data types, members of
  ArrayList are always references to objects at different memory
  locations (See this for details). Therefore in ArrayList, the actual
  objects are never stored at contiguous locations. References of the
  actual objects are stored at contiguous locations. In array, it
  depends whether the arrays is of primitive type or object type. In
  case of primitive types, actual values are contiguous locations, but
  in case of objects, allocation is similar to ArrayList.

A: There is a difference between lowercase hashtable, which is a generally defined data structure, and the java Hashtable class, which is a synchronized implementation of hashtable in Java that predates the HashMap and HashSet classes. HashSet does not use the Hashtable class at all. Instead, it uses the (again, lowercase h) hashtable data structure, which is implemented using HashMap. Hashtable should rarely if ever be used in contemporary code. As per the javadocs for Hashtable:

If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.

As for your other questions:

*

*TreeSet uses a completely different data structure from hashtable, called a red-black tree. See e.g. this detailed answer for an overview of the differences between HashSet and TreeSet.

*I'm not sure what that quote on "Memory point of view arrays" means. That website is not well written.

A:
So is it right to say that HashSet uses HashTable as data structure and HashMap as collection?

Not really. Although Java has a Hashtable class, which dates back to Java 1.0, but HashSet implementation does not share code with that class. Geeks For Geeks article claims that HashSet uses hash table data structure without making a reference to any specific class. They claim that HashSet uses the approach and algorithms of hash tables, which is true: by re-using the code of HashMap, which is based on hash table approach for building associative containers, HashSet uses hash table approach as well.

Does that mean that TreeSet doesn't uses HashMap internally which is used by HashSet to avoid duplicate values?

TreeSet uses TreeMap, which uses a comparison-based (as opposed to hash-based) approach of ensuring uniqueness of its keys.

Does LinkedHashSet uses HashMap internally?

Yes. LinkedHashSet inherits from HashSet, so it uses HashMap, indirectly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple listeners in one class I guess everybody knows the listener interface pattern. I have a class with some favorite items the user can add or remove.
In this class I have:
public static OnFavsChangedListener onFavsChangedListener;

public interface OnFavsChangedListener {
    abstract void onFavsChanged();
}

public static void setOnFavsChangedListener(
        OnFavsChangedListener listener) {
    onFavsChangedListener = listener;
}

public void addToFavorites () {
    if (onFavsChangedListener != null) {
        onFavsChangedListener.onFavsChanged()
    }
}

This works great when I only need to use ONE of those listeners, when I use setOnFavsChangedListener from different Activities, they will overwrite the last one.
My idea was to use an ArrayList of listeners and call them all when my Favs change, but it's hard to not let the ArrayList grow too big (Activities might add a listener on every orientation change / onCreate). I could use a HashMap of IDs and listeners, let every Activity remove it's listener onDestroy, but that seems clumsy.
TL;DR: Whats an elegant way for several Activities to be informed when my Favs change?

A: This may be overkill for your use case, but for notifying classes about events I use an event bus (specifically https://github.com/greenrobot/EventBus).
This allows you to simply post a message and every class that has registered to receive that type of message gets it. Very simple to use, and pretty small as far as libraries go.


text:
Q: WPF minimizing window into bottom of parrent window I try to make a "email messenger". I have two windows. Main window, there is ribbon with bookmarks and one button (New message). This button invoke second window NewMessage. The Mainwindow is owner of the NewMessage window.
MainWindow:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        NewMessage newmessage = new NewMessage();
        newmessage.Show();
    }
}

}
MainWindow XAML:
<Window x:Class="Messenger.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Messenger"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Button Content="New Message" Height="20" Width="80
            " HorizontalAlignment="Left" Margin="35,46,0,0" VerticalAlignment="Top" Click="Button_Click" />
    <TabControl HorizontalAlignment="Left" Height="254" Margin="34,44,0,0" VerticalAlignment="Top" Width="461" Background="{x:Null}" SelectedIndex="1">
        <TabItem Header="Delivered" Visibility="Hidden" Width="80">
            <Grid Background="#FFE5E5E5"/>
        </TabItem>
        <TabItem Header="Delivered" Visibility="Visible" Width="80">
            <Grid Background="#FFE5E5E5"/>
        </TabItem>
        <TabItem Header="Sent" Width="80">
            <Grid Background="#FFE5E5E5"/>
        </TabItem>
        <TabItem Header="Trash" Width="80">
            <Grid Background="#FFE5E5E5"/>
        </TabItem>
    </TabControl>
</Grid>

NewMessage:
public partial class NewMessage : Window
{
    public NewMessage()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        this.Close();
    }
}

}
NewMessage XAML:
<Window x:Class="Messenger.NewMessage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Messenger"
    mc:Ignorable="d"
    Title="NewMessage" Height="351.047" Width="814.398">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="4*"/>
        <ColumnDefinition Width="27*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="23*"/>
        <RowDefinition Height="24*"/>
        <RowDefinition Height="243*"/>
        <RowDefinition Height="31*"/>
    </Grid.RowDefinitions>
    <Label Grid.Row="0" Content="Komu" HorizontalAlignment="Left" VerticalAlignment="Top"/>
    <TextBox Grid.Row="0" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Top" />
    <Label Grid.Row="1" Content="Předmět" HorizontalAlignment="Left" VerticalAlignment="Top"/>
    <TextBox Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Top" />
    <RichTextBox HorizontalAlignment="Left" Height="243" Grid.Row="2" VerticalAlignment="Top" Width="806" Grid.ColumnSpan="2">
        <FlowDocument>
            <Paragraph>
                <Run Text="Sem zadejte text zprávy"/>
            </Paragraph>
        </FlowDocument>
    </RichTextBox>
    <Button Grid.Row="3" Content="Odeslat" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Top" Width="75" Margin="0,5,90,0"/>
    <Button Grid.Row="3" Content="Storno" Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Top" Width="75" Margin="0,5,10,0" Click="Button_Click"/>
</Grid>

I would like to, when I minimize NewMessage window, this window minimize to the bottom of MainWindow "taskbar". If you know gmail, there is the same principle. Any idea?


text:
Q: fetch data from excel to Datatable flutter I have an Excel file I would like to fetch so that I can display it in a DataTable. Now imagine the data below is inside my Excel file:
final allUsers = <User>[
  User(firstName: 'Emma', lastName: 'Field', age: 37),
  User(firstName: 'Max', lastName: 'Stone', age: 27),
  User(firstName: 'Sarah', lastName: 'Winter', age: 20),
  User(firstName: 'James', lastName: 'Summer', age: 21),
  User(firstName: 'Lorita', lastName: 'Wilcher', age: 18),
  User(firstName: 'Anton', lastName: 'Wilbur', age: 32),

];

my user class that retrieves all the data above is:
class User {
  final String firstName;
  final String lastName;
  final int age;

  const User({
    required this.firstName,
    required this.lastName,
    required this.age,
  });

  User copy({
    String? firstName,
    String? lastName,
    int? age,
  }) =>
      User(
        firstName: firstName ?? this.firstName,
        lastName: lastName ?? this.lastName,
        age: age ?? this.age,
      );

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is User &&
          runtimeType == other.runtimeType &&
          firstName == other.firstName &&
          lastName == other.lastName &&
          age == other.age;

  @override
  int get hashCode => firstName.hashCode ^ lastName.hashCode ^ age.hashCode;
}

A: Try this:
    return DataTable(
        columns: const <DataColumn>[
          DataColumn(
            label: Text(
              'First Name',
              style: TextStyle(fontStyle: FontStyle.italic),
            ),
          ),
          DataColumn(
            label: Text(
              'Last Name',
              style: TextStyle(fontStyle: FontStyle.italic),
            ),
          ),
          DataColumn(
            label: Text(
              'Age',
              style: TextStyle(fontStyle: FontStyle.italic),
            ),
          ),
        ],
        rows: allUsers
            .map(
              (user) => DataRow(
                cells: <DataCell>[
                  DataCell(Text(user.firstName)),
                  DataCell(Text(user.lastName)),
                  DataCell(Text(user.age.toString())),
                ],
              ),
            )
            .toList());
       }

Full Project:
import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  final allUsers = <User>[
    User(firstName: 'Emma', lastName: 'Field', age: 37),
    User(firstName: 'Max', lastName: 'Stone', age: 27),
    User(firstName: 'Sarah', lastName: 'Winter', age: 20),
    User(firstName: 'James', lastName: 'Summer', age: 21),
    User(firstName: 'Lorita', lastName: 'Wilcher', age: 18),
    User(firstName: 'Anton', lastName: 'Wilbur', age: 32),
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: DataTable(
            columns: const <DataColumn>[
          DataColumn(
            label: Text(
              'First Name',
              style: TextStyle(fontStyle: FontStyle.italic),
            ),
          ),
          DataColumn(
            label: Text(
              'Last Name',
              style: TextStyle(fontStyle: FontStyle.italic),
            ),
          ),
          DataColumn(
            label: Text(
              'Age',
              style: TextStyle(fontStyle: FontStyle.italic),
            ),
          ),
        ],
            rows: allUsers
                .map(
                  (user) => DataRow(
                    cells: <DataCell>[
                      DataCell(Text(user.firstName)),
                      DataCell(Text(user.lastName)),
                      DataCell(Text(user.age.toString())),
                    ],
                  ),
                )
                .toList()));
  }
}

class User {
  final String firstName;
  final String lastName;
  final int age;

  const User({
    required this.firstName,
    required this.lastName,
    required this.age,
  });

  User copy({
    String? firstName,
    String? lastName,
    int? age,
  }) =>
      User(
        firstName: firstName ?? this.firstName,
        lastName: lastName ?? this.lastName,
        age: age ?? this.age,
      );

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is User &&
          runtimeType == other.runtimeType &&
          firstName == other.firstName &&
          lastName == other.lastName &&
          age == other.age;

  @override
  int get hashCode => firstName.hashCode ^ lastName.hashCode ^ age.hashCode;
}

A: When you get to extracting the data from excel, then I suggest that you look at:
https://pub.dev/packages/spreadsheet_decoder


text:
Q: Calling a function for a generate button I have a page where a user can search a database for a given condition, then the data is returned with another button that the user can use to add information back to the database.  However whenever I click on the second button, the page reloads.  I can't get so much as a console.log to go in.  I'm new to react and could use any help at all.
import React , { Component } from 'react';
import { database } from '../firebase';

const byPropKey = (propertyName, value) => () => ({
    [propertyName]: value,
});

class Search extends Component{
    constructor(props) {
        super(props);
        this.state={
            users: null,
            searchCondition: "",
            friend: ""
        }
        // this.setState = this.setState.bind(this);
    }
    onSubmit = (event) => {
        let {
            searchCondition,
            friend
        } = this.state;
        database.searchConditions(searchCondition).then(snapshot =>
            this.setState(() => ({ users: snapshot.val() }))
        );

        event.preventDefault();
    }
    messageSubmit = (event) => {
        console.log("Click")
    }

    render(){
        let {
            users,
            searchCondition,
            friend
        } = this.state;
        return(

Search for conditions

                <form onSubmit={this.onSubmit}>

                        <input
                        value={searchCondition}
                        onChange={event => this.setState(byPropKey('searchCondition', event.target.value))}
                        type="text"
                        placeholder="Condition to Search For"
                        />
                        <button className="friendButton"
                        onClick="x"
                        type="submit">
                            Search
                        </button>

                    </form>

                    {!!users && <UserList users={users} />}

                )
            }
        }
        let UserList = ({ users, message }) =>

List of Usernames and Conditions of your Search

                            {Object.keys(users).map(key =>

{users[key].username} : {users[key].condition}
                        <form>

                                <input
                                    value={message}
                                    onChange={console.log("test")}
                                    type="text"
                                    placeholder="Message for this User"
                                />
                                <button className="messageButton"
                                    onClick={console.log(message)}
                                    type="submit">
                                    Message
                        </button>

                        </form>

                            )}

export default Search;

A: Have you tried to place the event.preventDefault() at the beginning of the event handler?
It should prevent the default behaviour imediately as the event gets fired.
Hope it works!

A: a couple things i can see, youre even.preventDefault() should be at the top of the page, you said it was reloading so thats unwanted behavior. second you should set state within the then, generally speaking in my experience that doesnt work- i believe due to setState being asynchronous or something of that nature.
i would rewrite your submit like this
onSubmit = (event) => {
    event.preventDefault();
    let {
        searchCondition,
        friend
    } = this.state;
    let value;
    database.searchConditions(searchCondition).then(snapshot =>
        value = snapshot.val
    );
    this.setState(() => ({ users: value) }))
}

also likely the reason your "messageSubmit()" was not console logging is because youre using a submit handler not a click handler so everytime your clicked you were reloading the page.
cheers


text:
Q: Hausdorff locally compact and second countable is $\sigma$-compact I want to show that every Hausdorff, locally compact and second countable is $\sigma$-compact.
I'm having trouble writing this rigorously. Can we proceed as follows:
Let $X$ be a locally compact Hausdorff space. Let $\mathcal{B}=\{B_{n}: n \in \mathbb{N}\}$ be a countable basis, then for each $x \in X$ find $U \subseteq X$ open such that $x \in U$ and $\overline{U}$ is compact. Then choose $B_{n} \in \mathcal{B}$ such that $x \in B_{n} \subseteq U$. Since $\overline{U}$ is compact then $\overline{B_{n}}$ is compact. So it seems that $X$ is the countable union of the closure of $B_{n}'s$. Can we simply write this as:
$X= \bigcup_{n \in \mathbb{N}} \{\overline{B_{n}}: B_{n} \in \mathcal{B}, \overline{B_{n}} \ \textrm{is compact}\}$

A: The argument is basically just fine, but the notation in that last line is a bit off: when you write $\bigcup_{n\in\mathbb{N}}$, you're saying that you want to take the union of some sets indexed by natural numbers. What follows $\bigcup_{n\in\mathbb{N}}$ should be a typical one of these sets with index $n$. If you knew that every member of $\mathcal{B}$ was compact, for instance, you could write $X = \bigcup_{n\in\mathbb{N}}\operatorname{cl}B_n$. What you want here is simply $X = \bigcup \{\operatorname{cl}B:B \in \mathcal{B}\text{ and}\operatorname{cl}B\text{ is compact}\}$.
If fact, you never needed to index $\mathcal{B}$ in the first place. It's perfectly fine to say this:

*

*Let $\mathcal{B}$ be a countable base. Since $X$ is locally compact, for each $x\in X$ there is an open nbhd $U_x$ of $x$ with compact closure, and since $\mathcal{B}$ is a base for $X$, there is some $B_x \in \mathcal{B}$ such that $x \in B_x \subseteq U_x$. Clearly each $B_x$ has compact closure, and $X = \bigcup\limits_{x\in X}\operatorname{cl}B_x$. There are only countably many distinct members of $\mathcal{B}$, so there are only countably many different sets $B_x$, and we have therefore expressed $X$ as the union of countably many compact subsets, as desired.

Or you could replace that last sentence with something like this:

*

*$\{B_x:x\in X\} \subseteq \{B \in \mathcal{B}:\operatorname{cl}B\text{ is compact}\} \subseteq \mathcal{B}$, so $\{B_x:x\in X\}$ is countable, and $X = \bigcup\limits_{x\in X}\operatorname{cl}B_x$ therefore expresses $X$ as a countable union of compact subsets.

There are many other perfectly good ways to do it; I'm just trying to give you some idea of what's possible, since you're working on the proof-writing as much as you are on the mathematics itself.


text:
Q: Rename df values using R I have a dataframe as following :
df <- data.frame(month = c("mazda miata 2017", "honda civic 2017"),
                 april = c(.1,.2),
                 may = c(.1,.2))

        month april may
1     miata     0.1 0.1
2     civic     0.2 0.2

I would like to rename mazda 3 as mazda and honda civic as honda. How can this be done using dplyr

A: Since you mention dplyr
library(dplyr)
library(tidyr)
df%>%tidyr::separate(month, c("month","Drop"), " ")%>%select(-Drop)
  month april may
1 mazda   0.1 0.1
2 honda   0.2 0.2

A: Do you need to use dplyr?
Easy enough with gsub:
df$month <- gsub("honda civic", "honda", df$month)

A: You can use the following solution to solve your problem:
levels(df$month)[levels(df$month )=="mazda 3"] <- "mazda"
levels(df$month)[levels(df$month )=="honda civic"] <- "honda"

A: Try a simple regular expression with str_replace.
In the example below, replace "mazda " and "honda" with anything else you'd like to eliminate. Separate with the OR symbol |:
 df %>%
   mutate(month = str_replace(month, "mazda |honda ", "") )

       month april may
1 miata 2017   0.1 0.1
2 civic 2017   0.2 0.2


text:
Q: How can I show that this is a martingale? Let $\{X_n:n \geq 1\}$ be a sequence of random variables. Let $S_n = \sum_{i=1}^{n} (X_i-E(X_i|X_1,...,X_{i-1})).$ Show that $\{S_n\}$ is a martingale.
This is what I have so far:
To show it's martingale then : $E(S_{n+1}|F_n)$
=$E(S_{n+1}|S_1,S_2,..,S_n) \rightarrow E(S_{n+1}-S_n|X_1,X_2,..,X_n) =$
$\rightarrow E(X_{n+1}-E(X_n+1|X_1,...,X_n])$ am I going in the right path?

A: I will write $\mathcal{F}_n = \sigma(X_1,...,X_n)$. Then you're given that $S_n = \sum_{i=1}^{n} X_i-E(X_i \mid \mathcal{F}_{i-1})$. We now have
\begin{align}
E(S_{n+1} \mid \mathcal{F}_n) &= E\Big(\sum_{i=1}^{n+1} (X_i-E(X_i \mid \mathcal{F}_{i-1})) \mid \mathcal{F}_n \Big) \\
&= \sum_{i=1}^{n+1} E(X_i \mid \mathcal{F}_n) - E( E(X_i \mid \mathcal{F}_{i-1}) \mid \mathcal{F}_n) \\
&= \sum_{i=1}^n \Big[ E(X_i \mid \mathcal{F}_n) - E( E(X_i \mid \mathcal{F}_{i-1}) \mid \mathcal{F}_n) \Big] + E(X_{n+1} \mid \mathcal{F}_n) - E( E(X_{n+1} \mid \mathcal{F}_n) \mid \mathcal{F}_n) \\
&= \sum_{i=1}^n X_i - E(X_i \mid \mathcal{F}_{i-1}) = S_n.
\end{align}
Do you see how to justify each step?


text:
Q: How to find the unix 'host' from the aws 'Endpoint' I'm looking for the 'host' of an aws database server to use in this configuration option:
-h host
--host=host

Specifies the host name of the machine on which the server is running.
If the value begins with a slash, it is used as the directory for the
Unix domain socket. The default is taken from the PGHOST environment
variable, if set, else a Unix domain socket connection is attempted.

But all I can find is this 'Endpoint':
Endpoint: foobar.ab12cd34ef.eu-west-1.rds.amazonaws.com:5432

Is that related?  Is there any way to extract the 'host' from the 'Endpoint'?

A: Use the endpoint as your host, it's what you should be using to connect to RDS. 5432 is the port it's running on.
RDS provides you an endpoint because by design it can have multiple backend "hosts" (database instances) serving data such as in a multi-AZ environment. By providing you with the endpoint you don't have to change your connection string when your master fails and the slave is promoted to master, etc.


text:
Q: Akka Http singleRequest stream is hanging after multiple requests I'm trying to request multiple links, one at a time using akka-https Http().singleRequest. In my demo code below however the foldLeft only ever loops four times and the application never reaches the println statements or terminates.
Im using the default akka config, but I'm thinking that the Http().singleRequest is consuming my threads and not releasing them. If I change the link list to only include 4 links the application terminates and I can see the println. However five and the app will hang during the fifth loop.
Has anyone seen this before or is there a fault with my impl. of the ActorSystem in this specific usecase.
val links = List(
  "https://www.google.com/",
  "https://www.google.com/",
  "https://www.google.com/",
  "https://www.google.com/",
  "https://www.google.com/",
  "https://www.google.com/",
  "https://www.google.com/",
  "https://www.google.com/"
)

implicit val as: ActorSystem = ActorSystem()
implicit val mat: ActorMaterializer = ActorMaterializer()

import as.dispatcher

def get(url: String): Future[Either[Throwable, Unit]] = {
  Http().singleRequest(HttpRequest(uri = url)) transformWith {
    case Success(_) =>
      Future.successful(Right(()))
    case Failure(e) =>
      Future.successful(Left(e))
  }
}

def getLinks(): Future[Seq[Unit]] = {
  links.foldLeft(Future.successful(Seq.empty[Unit])){
    case (f, e) => f.flatMap { ls =>
      get(e) map {
        case Right(i) => ls :+ i
        case Left(_) => ls
      }
    }
  }
}

getLinks() transformWith{
  case Success(ls) =>
    println("terminated")
    println(ls.length)
    Future.successful(())
  case Failure(e) =>
    println("terminated")
    println(e.getMessage)
    Future.successful(())
}

A: Consuming (or discarding) the Entity of a request is mandatory (from https://doc.akka.io/docs/akka-http/current/implications-of-streaming-http-entity.html).
Try to add response.discardEntityBytes() to your code.


text:
Q: Is there a bug about StructField in SPARK Structured Streaming When I try this :
cfg = SparkConf().setAppName('MyApp')
spark = SparkSession.builder.config(conf=cfg).getOrCreate()

lines = spark.readStream.load(format='socket', host='localhost', port=9999,
                              schema=StructType(StructField('value', StringType, True)))
words = lines.groupBy('value').count()
query = words.writeStream.format('console').outputMode("complete").start()

query.awaitTermination()

Then I get some error :

AssertionError: dataType should be DataType

And I search the source code in ./pyspark/sql/types.py at line 403:
assert isinstance(dataType, DataType), "dataType should be DataType"

But StringType based on AtomicType not DataType
class StringType(AtomicType):
    """String data type.
    """

    __metaclass__ = DataTypeSingleton

So is there a mistake?

A: In Python DataTypes are not used as singletons. When creating StructField you have have to use an instance. Also StructType requires a sequence of StructField:
StructType([StructField('value', StringType(), True)])

Nevertheless this is completely pointless here. Schema of TextSocketSource is fixed and cannot be modified with schema argument.


text:
Q: android how to draw a bitmap on canvas semi transparent I have tried to modify a Paint variable, but have been unsuccessful - how can I make a bitmap appear "semi-transparent"?

A: canvas.drawColor(Color.WHITE);
BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.loading);
Bitmap bm = bd.getBitmap();
Paint paint = new Paint();
paint.setAlpha(60);                             //you can set your transparent value here
canvas.drawBitmap(bm, 0, 0, paint);

A: Paint p = new Paint();
p.setAlpha(70);

Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.wallpaper);
canvas.drawBitmap(image, xPosition, yPosition, p);


text:
Q: Enable installation location chooser when installing an application published on Azure blob storage I have a .Net desktop application published to Azure blob storage I followed this link to do so. The user can install the application by accessing a public blob link e.g.: https://root.blob.core.windows.net/appcontainer/publish.htm
By default, the application is installed to

C:\Users\username\AppData\Local\Apps\2.0

My question is, how to change the default installation path? or how can I make the user choose the installation location if applicable?
I'm using visual studio 2015 to publish the desktop application

A:
My question is, how to change the default installation path? or how can I make the user choose the installation location if applicable?

As far as I know, for privilege and security concern, ClickOnce always install an application in the user Application Cache per user, and it does not enable user to choose the installation location. If you'd like to enable user to install application with a user specified installation location, you could use other installer technology.


text:
Q: Control middle value colours with scale_colour_continuous using R/ggplot2 I have a set of data and would like to map the colour aesthetic around a sort of "reference value" like so:

*

*values below are red

*values near are blue

*values above are green

I still want to show the fact that values are on a continuoum, so simply using a function like cut() and using scale_colour_discrete is  not what I'm looking for. Here's some example data:
set.seed(123)
x <- runif(100, min = 1, max = 10)
y <- runif(100, min = 1, max = 10)
test <- data.frame(x = x, y = y)
test$colour <- runif(100, min = 1, max = 10)
ggplot(test, aes(x = x, y = y, colour = colour)) + geom_point(size = 3)

That produces the following:

I'm familiar with scale_colour_gradient(low = "red", high = "green"), however I was hoping to more deliberately transition my colours along desired value mapping to make the regions "pop" a bit more visually. Spacing would not necessarily be linear. in other words, for a reference value of 3, the mapping would be something like this:
value:  1     3      10
colour: red   blue   green

Is this possible? I'd also take alternative solutions to accomplish a good visualization to highlight "desirable" values easily among a sea of points. For example, I considered replacing values near the reference such that (ref - tol < colour < ref + tol) <- NA, and then using scale_colour_gradient's option for na.value.
Or should I truly be considering the cut() option, just with a very small cut size and then figure out how to gradually change the colours along the resultant breaks?

A: From http://docs.ggplot2.org/0.9.2.1/scale_gradient2.html:
scale_color_gradient2(low = "red", midpoint = 3, mid = "blue", high = "green")

UPDATE:
Concerning OP's comment - playing around with midpoints and space="Lab" helps:
# Using the Lab colour space also improves perceptual properties
# at the price of slightly slower operation
d + scale_colour_gradient2(space="Lab")

Back from the graveyard - given the newest comment I realized that one should put the two lines of code together:
scale_color_gradient2(low = "red",
midpoint = 3,
mid = "blue",
high = "green",
space="Lab")

A: It is possible to define three or more colours and to specify how the data values map to the colour scale with scale_colour_gradientn(). You want to define your colours and use the values= option to define the mapping from data to colour.
The following would implement the three-colour scheme that you suggest:
set.seed(123)
x <- runif(100, min = 1, max = 10)
y <- runif(100, min = 1, max = 10)
test <- data.frame(x = x, y = y)
test$colour <- runif(100, min = 1, max = 10)
test.plot <- ggplot(test, aes(x = x, y = y, colour = colour)) +
  geom_point(size = 3) +
  scale_colour_gradientn(colours=c("red","blue","green"),
                         values=rescale(c(1,3,10)),
                         space = "Lab")
test.plot

This produces a graph as illustrated here (sorry; I don't have the reputation points to embed the image).
Regarding the second part of your question, to highlight specific values, one option is to re-plot in a different colour. Going back to your original plot with the dark- to light-blue colour gradient, we can replot points near a colour value of 3 in red. To avoid any visual artifacts from the overlaid points, we can use differently-sized points, either by specifying size = or by using a larger shape via shape = (as is done in the qcc package).
test2 <- test[test$colour > 2.5 & test$colour < 3.5,]
test2.plot <- ggplot(test, aes(x = x, y = y, colour = colour)) +
  geom_point(size = 3, shape = 20) +
  geom_point(data = test2, aes(x = x, y = y),
             colour = "red", size = 3, shape = 19)
test2.plot

Here's the sample graph.
Since this overplotting doesn't show up on the legend, some additional work would be needed to label the highlighted points.


text:
Q: Canvas On Draw Method I am new to android programming and I am trying to create a green circle image out of the screen. I tried using canvas to draw but it always show an error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Paint.setColor(int)' on a null object reference
            at com.example.jordanong09.handeyegame.GameActivity.onDraw(GameActivity.java:61)
            at com.example.jordanong09.handeyegame.GameActivity.onCreate(GameActivity.java:47)

Below are my codes for my programme:
public class GameActivity extends Activity {
    TextView textViewTime, textViewScore;
    int timeLeft,score;
    float xcoord,ycoord,radius = 100;
    Paint paint;
    Canvas canvas1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

        String timeData = getIntent().getExtras().getString("timeDuration");
        if(timeData == "30sec"){
            timeLeft = 30;
        }

        textViewTime = (TextView)findViewById(R.id.textViewTime);
        textViewScore = (TextView)findViewById(R.id.textViewScore);
        textViewTime.setText(timeData);
        final CounterClass timer = new CounterClass (30000, 1000);
        timer.start();
        onDraw(canvas1);

    }

    protected void onDraw (Canvas canvas)
    {
        Display display = getWindowManager().getDefaultDisplay();
        Point screenSize = new Point();
        display.getSize(screenSize);
        int width = screenSize.x;
        int height = screenSize.y;
        Random random = new Random();
        xcoord = random.nextFloat() * width;
        ycoord = random.nextFloat() * height;
        paint.setColor(Color.GREEN);
        paint.setStyle(Paint.Style.STROKE);
        canvas.drawCircle(xcoord, ycoord, radius, paint);
    }

I really dunno what is wrong with it because I have been researching online for solutions. Hope I could hear some advice. Thanks

A: The Paint object is not initialised correctly. You should call
paint = new Paint();

before calling
paint.setColor();

Otherwise paint is null, and you can't call methods on null.

A: You should go by creating a custom view and adding it as a child to one of your view group. Here is an example code. Hope this will help.
/**
 * Created by sanjeet on 2/2/16.
 */
public class GameActivity extends AppCompatActivity {
    TextView textViewTime, textViewScore;
    int timeLeft, score;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);
        textViewTime = (TextView)findViewById(R.id.textViewTime);
        textViewScore = (TextView)findViewById(R.id.textViewScore);
        /*Create a ViewGroup in your layout to contain this custom GameView instance */
        LinearLayout gameViewContainer = (LinearLayout)findViewById(R.id.custom_view_container);
        gameViewContainer.addView(new GameView(this));

    }

    class GameView extends View {

       Paint paint;
       int width;
       int height;
       private float radius=100;
       Random random;
       public GameView(Context context) {
           super(context);
           paint = new Paint();
           paint.setColor(Color.GREEN);
           paint.setStyle(Paint.Style.STROKE);
           Display display = getWindowManager().getDefaultDisplay();
           Point screenSize = new Point();
           display.getSize(screenSize);
           width = screenSize.x;
           height = screenSize.y;
           random = new Random();
       }

       @Override
       protected void onDraw(Canvas canvas) {
           super.onDraw(canvas);
           float xcoord = random.nextFloat() * width;
           float ycoord = random.nextFloat() * height;
           canvas.drawCircle(xcoord, ycoord, radius, paint);

       }

   }

}


text:
Q: maximizing income and quadratic function
The manager of a $1000$ seat concert hall knows from experience that all seats will be occupied if the price of the ticket is $50$ dollars. A market survey indicates that $10$ additional seats will remain empty for each $5$ dollar increase of the ticket price. What is the ticket price which maximizes the manager's revenue? How many seats will be occupied at that price?

To solve this problem, I think I have to maximize $f(t)=(50+5t)(1000-10t)$ where $t$ ranges from $0$ to $100$. Therefore the answer is $275$ dollars and $550$ seats. Am I correct? Could anyone please check for me?

A: $ f(t)\,=(50\,+5t)\,(1000-\,10t) $
Now f'(t)=5(1000 - 10t) - 10 (50 + 5t),
Where f'(t)=0 at t= 45 and  f''(t)=-50-50 <0.
Hence has maximum at t =45 i.e cost of ticket
Is 275 and seats will be 550.


text:
Q: dbFailOnError SQL Server datetime bug for time-only values I have a linked table in SQL Server with a datetime column where I store a time-only value*.  If I execute an UPDATE query without dbFailOnError it translates that command into a SELECT followed by individual UPDATE statements that execute one row at a time:
exec sp_executesql N'UPDATE "dbo"."Appeals" SET "HearingTime"=@P1
                     WHERE "AppealID" = @P2'
                  ,N'@P1 datetime,@P2 int','1899-12-30 09:00:00',1
...
exec sp_executesql N'UPDATE "dbo"."Appeals" SET "HearingTime"=@P1
                     WHERE "AppealID" = @P2'
                  ,N'@P1 datetime,@P2 int','1899-12-30 09:00:00',4

If I execute the exact same UPDATE query, but with dbFailOnError, I get this translation:
UPDATE "dbo"."Appeals" SET HearingTime={t '09:00:00'}

It is interesting that the dbFailOnError forces a more efficient UPDATE on the back end, but my real concern is with the time value itself.
In the first example, Access correctly sets the datetime to 12/30/1899 (MS Access's magic "zero" day).  In the second case, that does not happen.  The end result is that the first example "works" and the second one does not.
What I mean by that, is that if I view the HearingTime field in datasheet view, Access shows the first one as:
9:00:00 AM

And the second one shows as (as of this writing, 9/3/16 is today's date):
9/3/2016 9:00:00 AM

I have to assume this is a bug on Microsoft's part.  Or am I missing something here?  Do I have a better option than reporting the bug and just hoping that Microsoft fixes it someday?

*Yes I am aware there is a time datatype in SQL Server.  It is not compatible with the MS Access datetime type, so it's of little use to me in an MS Access linked table.

A: I was able to reproduce your issue using queries with Access SQL Date/Time literals. Both
Dim cdb As DAO.Database
Set cdb = CurrentDb
cdb.Execute "UPDATE dbo_Appeals SET HearingTime=#10:00:00#", dbFailOnError

and
Dim cdb As DAO.Database
Set cdb = CurrentDb
cdb.Execute "UPDATE dbo_Appeals SET HearingTime=#1899-12-30 11:00:00#", dbFailOnError

resulted in [HearingTime] values with the current date (2016-09-03), not the "zero" date.
However, passing the full date/time as a string seems to work
Dim cdb As DAO.Database
Set cdb = CurrentDb
cdb.Execute "UPDATE dbo_Appeals SET HearingTime='1899-12-30 12:00:00'", dbFailOnError

(Omitting the date part in the string value results in [HearingTime] values with the SQL Server DATETIME "zero" date of 1900-01-01.)
And, even better, a parameterized query with a DAO.QueryDef object also appears to work correctly
Dim cdb As DAO.Database
Set cdb = CurrentDb
Dim qdf As DAO.QueryDef
Set qdf = cdb.CreateQueryDef("", _
        "PARAMETERS prmHearingTime DateTime;" & _
        "UPDATE dbo_Appeals SET HearingTime=[prmHearingTime]")
qdf!prmHearingTime = #10:00:00 AM#
qdf.Execute dbFailOnError

A: That's a good question, and I can reproduce it.
It seems to be a bug in the ODBC driver, because the behaviour you demonstrate is that of SQL Server which the ODBC driver should compensate for, as it does in your first example by providing the full date-time string that will translate correctly when read back in Access.
I can see no way to work around it other than, when you read back the data, to apply TimeValue to the date-time values. This, however, will cease any use of an index of your time field.
And data type Time of SQL Server cannot be used for many things as the ODBC driver reads these as text.


text:
Q: Boolean returns false first time in activity I have a method that returns true if a child is present in the database and false if not. It looks like this:
boolean subscriber;
public boolean checkChatRoomMembership(String chatRoomUid) {
    mChatRoomMembers.child(chatRoomUid).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.hasChild(mAuth.getUid())) {
                subscriber = true;
            } else {
                subscriber = false;
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
    return subscriber;
}

Even though the the node is present in the database it returns false the first time the method is ran. The following times it returns true as it should. It is always the first time the activity is started that it returns false. Any ideas why?

A: When the function is called the first time, callbacks inside the function has not been called. Yet data is not retrieved and your function return default value of "subscriber" variable. After the first call to this function "subscriber" value updates when the callback is called.
public void checkChatRoomMembership(String chatRoomUid) {
mChatRoomMembers.child(chatRoomUid).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (dataSnapshot.hasChild(mAuth.getUid())) {
            // true, do you work here
        } else {
            // false, do you work here
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

}
Hope this will help you.


text:
Q: Grails retrieve custom query to Mapped List i'm new in grails...
I want to create a Controller for my jquery autocomplete
def arrSong = Song.executeQuery("select id, title as value, concat(artist, ' - ', title) as label from ${Song.name} where title like concat('%', :paramTitle, '%')", [paramTitle:params.term?.toString()])
render arrSong as JSON

with this code i get this JSON :
[[1,"Mr. Brightside","The Killers - Mr. Brightside"]]

my expectation is like :
[{"id":1,"value":"Mr. Brightside","label":"The Killers - Mr. Brightside"}]

anyone can help ?

A: executeQuery the way you have written would return a list of unnamed results which has to be retrieved by using the index.
For example:
[[1,"Mr. Brightside","The Killers - Mr. Brightside"]]

arrSong.each{println it[0]}
//Prints 1, similarly it[1] for "Mr. Brightside" and so on

What you need is a map representation of your result set as below, then you should be able to render the map effortlessly as a JSON.
def query = """
             select new map(id as id,
                            title as value,
                            concat(artist, ' - ', title) as label)
             from ${Song.name}
             where title like concat('%', :paramTitle, '%')
            """

def arrSong = Song.executeQuery(query, [paramTitle: params.term?.toString()])

render arrSong as JSON

should return
[{"id":1,"value":"Mr. Brightside","label":"The Killers - Mr. Brightside"}]


text:
Q: How to change html shorthand to html tag when adding content dynamically var encodedHtml =  "

Test data is data
which has been specifically identified for use in tests, typically of a computer program. Some data may be used in a confirmatory way, typically to verify that a given set of input to a given function produces some expected result.

";
I want to change this content to html tags , so i can add it to some div using js.

A: This should get you sorted out:
What's the right way to decode a string that has special HTML entities in it?
A few answers down it has a jQuery version:
function htmlDecode(value) {
    return $("<textarea/>").html(value).text();
}

A: var encodedHTML = "<ol style="color: rgb(34, 34, 34); font-family: arial, sans-serif;"><li class="mod" style=""> <div class="_oDd" style=""><span class="_Tgc" style="font-size: 16px;"><b>Test data</b> is <b>data</b> which has been specifically identified for use in <b>tests</b>, typically of a computer program. Some <b>data</b> may be used in a confirmatory way, typically to verify that a given set of input to a given function produces some expected result.</span></div> </li></ol>";
$("
").html(encodedHTML ).text();

this also works.


text:
Q: If I can use SQLite 3 to organize data in python, why should I use classes? I am going to create a project for my university called Criminal Record System in which I will manage criminal's data and history. Now I stumbled upon the term class. Going through some videos and articles I realized that it is used to save data. So I am confused that if we can use sqlite 3 then why are using classes to organize data.

A: Database scope is to store data. You use Classes to better organize your data in your program.
Think of the database as a warehouse where you store your library and your books. When you need to get some of these books you retrieve them (read from database) and use a Class to organize them when you use it at 'home' (in your program).
Without database when the program is closed you lose all your books. Without classes you have all your books in a mess.
So there is no a 'better' or 'worse'. One does not exclude the other.
You can read this: https://python.swaroopch.com/oop.html


text:
Q: Ordering by formula fields in NHibernate Suppose that I have the following mapping with a formula property:
<class name="Planet" table="planets">
    <id name="Id" column="id">
        <generator class="native" />
    </id>

    <!-- somefunc() is a native SQL function -->
    <property name="Distance" formula="somefunc()" />
</class>

I would like to get all planets and order them by the Distance calculated property:
var planets = session
    .CreateCriteria<Planet>()
    .AddOrder(Order.Asc("Distance"))
    .List<Planet>();

This is translated to the following query:
SELECT Id as id0, somefunc() as formula0 FROM planets ORDER BY somefunc()

Desired query:
SELECT Id as id0, somefunc() as formula0 FROM planets ORDER BY formula0

If I set a projection with an alias it works fine:
var planets = session
    .CreateCriteria<Planet>()
    .SetProjection(Projections.Alias(Projections.Property("Distance"), "dist"))
    .AddOrder(Order.Asc("dist"))
    .List<Planet>();

SQL:
SELECT somefunc() as formula0 FROM planets ORDER BY formula0

but it populates only the Distance property in the result and I really like to avoid projecting manually over all the other properties of my object (there could be many other properties).
Is this achievable with NHibernate? As a bonus I would like to pass parameters to the native somefunc() SQL function. Anything producing the desired SQL is acceptable (replacing the formula field with subselects, etc...), the important thing is to have the calculated Distance property in the resulting object and order by this distance inside SQL.

A: These 2 are 100% identical in SQL. Why does it matter?
SELECT Id as id0, somefunc() as formula0 FROM planets ORDER BY somefunc()
SELECT Id as id0, somefunc() as formula0 FROM planets ORDER BY formula0

Edit, still the same:
The ORDER BY clause will simply repeat the SELECT func call whether aliased or not
SELECT Id as id0, somefunc(1, 'fish') as formula0 FROM planets ORDER BY somefunc(1, 'fish')
SELECT Id as id0, somefunc(1, 'fish') as formula0 FROM planets ORDER BY formula0


text:
Q: Hide side-bar when a concrete page is displayed I'm trying to hide a side-bar menu that I've implemented, but just in a concrete page, I'm using plain Javascript, but not succeed, now I'm gonna try it with Jquery. Anybody can give a tip or some doc. danke

A: .hide haha
you really need to upload some code so we can fix your prob.

A: Let's say you side bar consists in one element which id is "sidebar".
In the page you want to hide, you link a .js page in which you write :
//Javascript
window.onload = function() {
    document.getElementById("sidebar").style.visibility = "hidden";
};

A: If the page has its own javascript attached to it, you could try something like this
$( document ).ready(function() {
    $('#side_bar_id').hide();
});

or if a general javascript file should handle it
$( document ).ready(function() {
    var path = window.location.pathname;
    path = path.split('/');
    if(path[0] == "concretepage") {
        $('#side_bar_id').hide();
    }
}

A:

$('button').toggle(

function() {
    $('#B').css('left', '0')
}, function() {
    $('#B').css('left', '200px')
})
html, body {
    margin: 0;
    padding: 0;
    border: 0;
}
#A, #B {
    position: absolute;
}
#A {
    top: 0px;
    width: 200px;
    bottom: 0px;
    background:orange;
}
#B {
    top: 0px;
    left: 200px;
    right: 0;
    bottom: 0px;
    background:green;
}

<button>toggle</button>


text:
Q: Internal Url Redirection to new urls as website redesigned Old URL: https://www.abc.in/browse/handpiece
New Url: https://www.abc.in/denrtal-handpiece
When I tried following:
Redirect 301 /browse/handpiece https://www.abc.in/denrtal-handpiece
this redirect on - https://www.abc.in/denrtal-handpiece?route=product/handpiece
How to fix it with .htaccess?

A: redirectMatch 301 ^/browse/handpiece$ /denrtal-handpiece


text:
Q: Is there anyone who could fix what happened in Captain America: Civil War? Near the end of Civil War,

Tony destroys the majority of Bucky's metal arm in a fight.

The post credits scene shows the extent of the damage.
The Winter Soldier has been operating for decades, therefore the technology to build his arm has clearly been around for a while.
However, seeing as the majority of HYDRA's operations have been taken down at this point, anyone with the knowledge of it's original construction would likely be unavailable.
It would probably be quite easy to

build Bucky a new arm from scratch

using Stark tech or something similar. However, unless it can be reverse engineered it appears to be quite unique among anything that we see within the scope of the MCU in the modern day.
My question is: Is there anyone alive who has the ability to restore it to its original design, so that it would be identical to before?

A: Yes*
Spoilers for Infinity War:

 *Wakanda builds a new arm for Bucky but it is not exactly identical to the old one, its color being the primary difference seen so far.  It is given to him by T'Challa in Infinity War.  The new arm is likely to be Vibranium and therefore superior to the old arm. (The images are links to preserve the spoiler tag)

A: Who could build such an advanced prosthetic?

*

*Leopold 'Leo' Fitz - Agent of SHIELD

*Carlo Mancini - Ex Cybertek employee (Project Deathlok)

*Holden Radcliffe - Transhumanist Scientist

*Helen Cho - World-renowned Geneticist

Who is most likely to build such a prosthetic?
In Agents of SHIELD season 2 episodes 21-22 (the season finale),

 Director Coulson loses his hand.

It was cut off by Mack to stop the spread of Terrigenesis when Gordon dropped a Terrigen crystal.
Leo Fitz produces a cybernetic hand to replace it.

Prosthetic capabilities
This hand has displayed remarkable abilities beyond super-strength. Such as the ability to project an energy shield (season 3 episode 18):

The prosthetic can also (as seen in season 3 episode 13):

*

*Take complete handprint model from handshakes

*Jam communications

*Generate a local EMP (not demonstrated)

There may be more capabilities that have not yet been shown, we'll have to wait and see.

Conclusion
It is fair to posture that Fitz could create a full arm, of a similar standard if the situation called for it. It's also fair to assume that any of the other mentioned scientists could create a similar prosthetic.
As Bucky's arm is really very basic compared to the prosthetic hand, it is reasonable to think that Fitz (or another listed scientist) could accurately recreate it. Though in all likelihood whoever does (if it ever happens!) create a new prosthetic for Bucky, will most likely add some new stuff.


text:
Q: is There a way to separate the progress bar from the content story using react-insta-stories I am working on a web app with react js
I want to achieve this result :

is there a way to separate the progress bar from the image like the screen using the package react-insta-stories
Thanks for help


text:
Q: Tables relationship logic I have a logic question, I have two tables, Doctor and Specialty, and I don´t know who belong to who. Doctors can have more than one specialty, but I´m not sure how to set it up.
A doctor can have multiple specializations, so my logic says that a table named specialty should belong to a table doctor. Does this makes sense?

A: You should have all the doctors in one table, say Doctor and all specialties in another table Specialty. Then you should have a linking table that contains the list of specialties for a given doctor.

*

*Doctor

*

*DoctorId

*Name

*Degree etc.,

*Specialty

*

*SpecialtyId

*Name etc.,

*SpecializedDoctors

*

*SpecialtyId

*DoctorId

This would help you identify the specialties of a doctor or doctors with a specialty.


text:
Q: Remote Desktop audio desync I have a pretty simple problem, I do the opposite of most people - I remote home while at work (I really don't like the software environment at work). Everything works fine except the audio lags by about 3 seconds (video lags by like 30ms I'm guessing). Sometimes the audio will be synced but then the whole setup will lag a bit - the video will jump to the current spot but the audio will stay delayed. Even if I let it idle, it doesn't 'catch up'. I'm not playing games or anything, but I do some work with audio files for work and it can be frustrating trying to scrub through with such a delay. Any suggestions on how to fix this? Thanks a bunch!
Setup:
HOME : 125mbps down 10 mbps up. WIN 10 Pro
WORK : 100mbps down 100 mbps up. WIN 7 Pro
I have a 3 monitor setup but again - not heavy on the video, mostly static images.

A: This might not be what you wanted and is very hacky - but I got it working and is definitely better than 3 seconds of delay
Use SoundWire.
It's a freemium software that broadcasts your system sounds to android device.
Download and install server on Windows, launch client on android phone or use android emulator.
If you purchase the premium version, you can set buffer size to very low for example 100ms. And set "Latency steering amount" to tight. Resulting latency might fluctuate between 80ms and 130ms. I used it with bluetooth headphones so end to end latency becomes something like 100ms(SoundWire) + 200ms(BT SBC) + some overhead by server and client.
For me, this reduced the audio lag to roughly .5 sec from 1 sec before.


text:
Q: epoch with milliseconds to timestamp with milliseconds conversion in Hive How can I convert unix epoch with milliseconds to timestamp with milliseconds In Hive?
Neither cast() nor from_unixtime() function is working to get the timestamp with milliseconds.
I tried .SSS but the function just increases the year and doesn't take it as a part of millisecond.
scala> spark.sql("select from_unixtime(1598632101000, 'yyyy-MM-dd hh:mm:ss.SSS')").show(false)
+-----------------------------------------------------+
|from_unixtime(1598632101000, yyyy-MM-dd hh:mm:ss.SSS)|
+-----------------------------------------------------+
|52628-08-20 02:00:00.000                             |
+-----------------------------------------------------+

A: I think you can just cast():
select cast(1598632101000 / 1000.0 as timestamp)

Note that this produces a timestamp datatype rather than a string, as in from_unixtime().

A: from_unixtime works with seconds, not milliseconds. Convert to timestamp in seconds from_unixtime(ts div 1000), concatenate with '.'+ milliseconds (mod(ts,1000)) and cast as timestamp. Tested in Hive:
with your_data as (
select stack(2,1598632101123, 1598632101000) as ts
)

select cast(concat(from_unixtime(ts div 1000),'.',mod(ts,1000)) as timestamp)
from your_data;

Result:
2020-08-28 16:28:21.123
2020-08-28 16:28:21.0

A: Here's another way in pure Spark Scala using UDF to wrap the Java function to return new Timestamp(ms)
import java.sql.Timestamp
val fromMilli = udf((ms:Long) => new Timestamp(ms))

#Test
val df = Seq((1598632101123L)).toDF("ts")
df.select(fromMilli($"ts")).show(false)

Result
+-----------------------+
|UDF(ts)                |
+-----------------------+
|2020-08-28 16:28:21.123|
+-----------------------+


text:
Q: Find multiple object values in array This is my object:
function Plane (x,z) {
    this.x = x;
    this.z = z;
}

var plane = new Plane(0,50000);

I have an array with these objects:
planesArray.push(plane);

I have a point object:
function Point (x,z) {
    this.x = x;
    this.z = z;
}

var point = new Point(0,-50000);

I need to check if in planesArray exist an object with the specific point, so to check if the values x and y of the point are equal to any of the planes in the array and, if NOT, to perform an action.
I am still a novice, I apologize if this question sounds dumb.

A: Loop through the array and return a boolean indicating whether or not there was found a Point object with those attributes. This example uses the .some method to perform this operation.
var found = planesArray.some(function(plane) {
    return plane.x === x && plane.y === y;
});

if (found) {

}

Update: Here is the same code as a function.
function found(list, x, y) {
    return list.some(function(plane) {
        return plane.x === x && plane.y === y;
    });
}

A: var point = new Point(0,-50000);
for(var i = 0; i < planesArray.length; i++) {
    var plane = planesArray[i];
    if(plane.x != point.x || plane.z != point.z) {
        //perform action
        //break; //optional, depending on whether you want to perform the action for all planes, or just one
    }
}


text:
Q: Zip folder is corrupted after editing content I am trying to copy a zipped bytes array to another one using ZipOutputStream/ZipIntputStream, but it seems that the result array is not equal the original one, why is that wrong?
public static void main(String[] args) throws IOException {
    File file = new File("folder.zip");
    byte[] bFile = new byte[(int) file.length()];

    FileInputStream fileInputStream = new FileInputStream(file);
    fileInputStream.read(bFile);
    fileInputStream.close();
    byte[] aFile = copyZippedFileBytes(bFile);
    System.out.println(Arrays.equals(aFile, bFile));
}

public static byte[] copyZippedFileBytes(byte[] arr) throws IOException {

    ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(arr));

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zipOutputStream = new ZipOutputStream(baos);

    ZipEntry entry;
    while ((entry = zipStream.getNextEntry()) != null) {
        zipOutputStream.putNextEntry(entry);
        // assume files are small
        byte[] indexFileByte = new byte[(int) entry.getSize()];
        zipStream.read(indexFileByte);

        zipOutputStream.write(indexFileByte);
        zipOutputStream.closeEntry();
    }
    zipOutputStream.close();
    zipStream.close();
    return baos.toByteArray();
}

Solved by updated CRC of the modified entry as follow:-
CRC32 crc = new CRC32();
        crc.reset();
    BufferedInputStream bis = new BufferedInputStream
        (new ByteArrayInputStream(data));

    int bytesRead;
    byte[] buffer = new byte[1024];

    while ((bytesRead = bis.read(buffer)) != -1) {
        crc.update(buffer, 0, bytesRead);
    }

    entry.setMethod(ZipEntry.STORED);
    entry.setCompressedSize(data.length);
    entry.setSize(data.length);
    entry.setCrc(crc.getValue());


text:
Q: Gradle "offline work" removed from gradle android studio setting I use Android Studio Version 4.0 RC version, and it seems it removed the offline work mode.

Where can I find this item in the android studio?

A: You can find the gradle offline mode toggle in the gradle tab on the right side of the Android Studio,

A: You can activate/deactivate this from Gradle Tab (Top Right) by clicking the icon to toggle offline mode

A: Outside android-studio you can also use settings.gradle file:
startParameter.offline=true


text:
Q: Declare class inside exported factory function / closure Say I have the following TypeScript code:
export const makeMyClass = function(a: string, b: boolean){

   const MyClass = function(){

   };

   MyClass.prototype.foo = function(){};

   MyClass.prototype.bar = function(){};

   return MyClass;

}

I am having trouble figuring out how to convert the code inside the exported factory function into TypeScript.
For example, if I do this:
 export const makeMyClass = function(a: string, b: boolean): MyClass {

       class MyClass {

       }

      // ...

      return MyClass;

  }

TypeScript complains saying that it can't find name 'MyClass'. Please assume that I need to use the exported closure makeMyClass for the sake of the question.

A: If you want to give a name to the type of the return value of makeMyClass() which is visible outside of the function, then you have to describe its structure as a type of interface in an outer scope.  At least that's how I understand TypeScript's implementation of class expressions.
Here's how I would do it in your case.  A class has an instance type (which describes instance properties and class methods) and a constructor type (which describes the constructor and any static methods), so we need to describe both:
export interface MyClassInstance {
  foo(): void;
  bar(): void;
  // define the rest of the public interface here
}
export interface MyClassConstructor {
  new(): MyClassInstance;
  readonly prototype: MyClassInstance;
  // define any static methods here
}

Now you can declare that makeMyClass() returns the constructor type:
export const makeMyClass = function(a: string, b: boolean): MyClassConstructor {

  // implement the MyClassInstance/MyClassConstructor interfaces
  class MyClass {
    foo() {
      // ...
    }
    bar() {
      // ...
    }
  }

  return MyClass;
}

Note that this is repetitive, in that you declare the class structure both inside and outside the function.  If you add a property or method to the interfaces, you will need to add a corresponding property to the class implementation.  This seems to be unfortunately unavoidable, since you can't export types from inside functions.
Anyway, hope that helps; good luck!


text:
Q: Need meta-programming magic to define a mother lode of bit fields in an error-free way The goal is to control which types of users are allowed to perform which operations at the UI level. This code has been in place for a while; I just want to improve it a bit.
The file which I am trying to improve should probably be auto-generated, but that would be too big of a change, so I seek a simpler solution.
A file which we shall call PermissionBits.h has a bunch of these:
// Here names are mangled; for example XYZ_OP_A is:
// permission to operation A in category/context XYZ
// SCU64 = static const unsigned __int64
// Some namespaces utilize all 64 bits
// The actual values (as long as they are proper bit fields)
// do not matter - they are always used by name
namespace XYZPermissionBits
{
    SCU64 XYZ_OP_A = 1UI64 <<  0; //    1 = 0x0000000000000001
    SCU64 XYZ_OP_B = 1UI64 <<  1; //    2 = 0x0000000000000002
    SCU64 XYZ_OP_C = 1UI64 <<  2; //    4 = 0x0000000000000004
    SCU64 XYZ_OP_C = 1UI64 <<  3; //    8 = 0x0000000000000008
    SCU64 XYZ_OP_D = 1UI64 <<  4; //   16 = 0x0000000000000010
    SCU64 XYZ_OP_E = 1UI64 <<  5; //   32 = 0x0000000000000020
    SCU64 XYZ_OP_F = 1UI64 <<  6; //   64 = 0x0000000000000040
    SCU64 XYZ_OP_G = 1UI64 <<  7; //  128 = 0x0000000000000080
    SCU64 XYZ_OP_H = 1UI64 <<  8; //  256 = 0x0000000000000100
    SCU64 XYZ_OP_I = 1UI64 <<  9; //  512 = 0x0000000000000200
    SCU64 XYZ_OP_J = 1UI64 << 10; // 1024 = 0x0000000000000400
    SCU64 XYZ_OP_K = 1UI64 << 11; // 2048 = 0x0000000000000800
    SCU64 XYZ_OP_L = 1UI64 << 12; // 4096 = 0x0000000000001000
}

Even with the help of 1UI64 << <numBits>; shortcut there are still problems, as coders create flags with duplicate values, make typos, etc.
Ideally I would like a macro which can be nicely formatted and look like:
BITFIELDS_FOR_NAMESPACE(
    //*************** <<== I want to make the namespace name more vivid
    XYZPermissionBits,
    //*************** <<== somehow if that is possible. It is not a must-have.
    XYZ_OP_A, // Being able to add a comment here would be nice, but not critical
    XYZ_OP_B,
    XYZ_OP_C,
    XYZ_OP_D,
    XYZ_OP_E,
    XYZ_OP_F,
    XYZ_OP_G,
    XYZ_OP_H,
    XYZ_OP_I,
    XYZ_OP_J,
    XYZ_OP_K,
    XYZ_OP_L
)

I would like this macro be flexible and prevent me from entering less than 2 or more than 65 arguments - namespace name + 64 flags. Is it possible to do what I want or close to it, or should I resort to generated code? What other advice do you have?

A: Tested example using Boost.PreProcessor:
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/comparison/greater.hpp>
#include <boost/preprocessor/comparison/less.hpp>
#include <boost/preprocessor/debug/assert.hpp>
#include <boost/preprocessor/seq/size.hpp>

#define CHECK_SIZE(size) \
  BOOST_PP_ASSERT_MSG(BOOST_PP_GREATER(size, 1), "<  2 :(") \
  BOOST_PP_ASSERT_MSG(BOOST_PP_LESS(size, 65),   "> 64 :(") \

#define DO_MAKE_BITFIELDS(a, b, i, elem) \
  SCU64 elem = 1UI64 << i;

#define BITFIELDS_FOR_NAMESPACE(name, seq) \
  CHECK_SIZE(BOOST_PP_SEQ_SIZE(seq)) \
  namespace name { \
    BOOST_PP_SEQ_FOR_EACH_I(DO_MAKE_BITFIELDS, _, seq) \
  }

Usage:
BITFIELDS_FOR_NAMESPACE(
    XYZPermissionBits,
    (XYZ_OP_A)
    (XYZ_OP_B)
    // ...
);

A: IFAIK, The boost preprocessor library http://www.boost.org/doc/libs/1_43_0/libs/preprocessor/doc/index.html has all the primitives you need.

A: If you do decide to go the code generation route then I suggest taking a look at Cog.
Cog lets you embed python code as comments in the C++ (or any other language) source file, and when run through Cog the python output is inserted as source code, so the generator code and generated output are all managed in the same file.  This keeps maintenance simple. and the python code documents how the generated code was created.
Here is your example using cog, including the generated code:
namespace XYZPermissionBits
{
    /* [[[cog
    import cog
    operations = ["A", "B", "C", "D",
                  "E", "F", "G", "H",
                  "I", "J", "K", "L"]

    assert 2 <= len(operations) <= 64

    for idx,op in enumerate(operations):
        cog.outl("SCU64 XYZ_OP_%s = 1UI64 << %s;" % (op, idx))

    ]]] */
    SCU64 XYZ_OP_A = 1UI64 << 0;
    SCU64 XYZ_OP_B = 1UI64 << 1;
    SCU64 XYZ_OP_C = 1UI64 << 2;
    SCU64 XYZ_OP_D = 1UI64 << 3;
    SCU64 XYZ_OP_E = 1UI64 << 4;
    SCU64 XYZ_OP_F = 1UI64 << 5;
    SCU64 XYZ_OP_G = 1UI64 << 6;
    SCU64 XYZ_OP_H = 1UI64 << 7;
    SCU64 XYZ_OP_I = 1UI64 << 8;
    SCU64 XYZ_OP_J = 1UI64 << 9;
    SCU64 XYZ_OP_K = 1UI64 << 10;
    SCU64 XYZ_OP_L = 1UI64 << 11;
// [[[end]]]
}

A: Instead of macros/preprocessors/etc I'd stick with a static text file similar to the original.  It seems much easier to understand and expand or maintain.  I might define each value as a shift of the previous value, but that might seem more confusing to some readers.  To help prevent typos by users, I'd probably use a more verbose abbreviation for each "op" instead of A, B, C (defined twice), D...

A: I've done something like this.  Create a macro called MAKE_THINGS that looks like:

#define MAKE_THINGS \
  MAKE_THING(NAME1) \
  MAKE_THING(NAME2) \
  MAKE_THING(NAME3) \
  /* Include semantically-blank line after list */

One can then define MAKE_THING, start a declaration, call MAKE_THINGS, end the declaration, and undefine MAKE_THING.  If desired, each thing can include more than one attribute:
For example:

#define MAKE_THINGS \
  MAKE_THING(HAPPY,"Happy") \
  MAKE_THING(SAD_AND_BLUE,"Sad and blue") \
  MAKE_THING(SLEEPY,"Sleepy") \
  /* Include semantically-blank line after list */

#define MAKE_THING(x,y) NUMBER_##x,
typedef enum {MAKE_THINGS LAST_THING} THING_NUMBER;
#undef MAKE_THING

#define MAKE_THING(x,y) FLAG_##x = (1L << NUMBER##x),
typedef enum {MAKE_THINGS ALL_FLAGS = (1 << LAST_THING)-1} THING_FLAGS;
#undef MAKE_THING

#define MAKE_THING(x,y) const char *MSG_##x = y;
MAKE_THINGS
#undef MAKE_THING

#define MAKE_THING(x,y) MSG_##x,
const char *thing_names[] = {MAKE_THINGS 0};
#undef MAKE_THING

Note that all of the declarations are automatically kept parallel.  Each thing gets a number (0..N-1), an flag (bit corresponding to its number), a message string, and a place in an array of message strings.


text:
Q: PerformFiletering gets null parameter I have AutoCompletTextView and i want do apply some customize filetring to it for this i have this code
public class ATCAdapter extends ArrayAdapter<String> implements Filterable {

    ArrayList<String> _items = new ArrayList<String>();
    ArrayList<String> orig = new ArrayList<String>();

    public ATCAdapter(Context context, int resource, ArrayList<String> items) {
        super(context, resource, items);

        for (int i = 0; i < items.size(); i++) {
            orig.add(items.get(i));
        }
    }

    @Override
    public int getCount() {
        if (_items != null)
            return _items.size();
        else
            return 0;
    }

    @Override
    public String getItem(int arg0) {
        return _items.get(arg0);
    }

    @Override

    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                if(constraint != null) {
                    Log.d("Constraints", constraint.toString());
                }

                FilterResults oReturn = new FilterResults();

                /*  if (orig == null){
                    for (int i = 0; i < items.size(); i++) {
                        orig.add(items.get(i));
                    }
                  }*/
                String temp;
                int counters = 0;
                if (constraint != null){

                    _items.clear();
                    if (orig != null && orig.size() > 0) {
                        for(int i=0; i<orig.size(); i++)
                        {
                            temp = orig.get(i).toUpperCase();

                            if(temp.startsWith(constraint.toString().toUpperCase()))
                            {

                                _items.add(orig.get(i));
                                counters++;

                            }
                        }
                    }
                    Log.d("REsult size:" , String.valueOf(_items.size()));
                    if(counters != 0)
                    {
                        _items.clear();
                        _items = orig;
                    }
                    oReturn.values = _items;
                    oReturn.count = _items.size();
                }
                return oReturn;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if(results != null && results.count > 0) {
                    notifyDataSetChanged();
                }
                else {
                    notifyDataSetInvalidated();
                }

            }

        };

        return filter;

    }

}

and this is how i am setting adapter for
AutoCompleteTextView    autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);

        ArrayAdapter adapter = new ATCAdapter(this, android.R.layout.simple_list_item_1, new ArrayList<>(Arrays.asList(languages)));
        autoCompleteTextView.setThreshold(1);
        autoCompleteTextView.setAdapter(adapter);

Now the problem is i always get null parameter in performFiletring(), Any reason why it's happening ?

A: IHMO, your code has a problem at
if(counters != 0)
{
    _items.clear();
    _items = orig;
}

I suggest you update your code as the following:
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                if (constraint != null) {
                    Log.d("Constraints", constraint.toString());
                }
                FilterResults oReturn = new FilterResults();
                String temp;
                int counters = 0;
                if (constraint != null && constraint.length() > 0) {
                    _items.clear();
                    if (orig != null && orig.size() > 0) {
                        for (int i = 0; i < orig.size(); i++) {
                            temp = orig.get(i).toUpperCase();
                            if (temp.startsWith(constraint.toString().toUpperCase())) {
                                _items.add(orig.get(i));
                                counters++;
                            }
                        }
                    }
                    Log.d("Result size:", String.valueOf(_items.size()));
                    if (counters == 0) {
                        _items = new ArrayList<>(orig);
                    }
                    oReturn.values = _items;
                    oReturn.count = _items.size();
                } else {
                    _items = new ArrayList<>(orig);
                    oReturn.values = _items;
                    oReturn.count = _items.size();
                }
                return oReturn;
            }

and the constructor:
   public ATCAdapter(Context context, int resource, ArrayList<String> items) {
        super(context, resource, items);

        for (int i = 0; i < items.size(); i++) {
            orig.add(items.get(i));
        }
        _items = new ArrayList<>(orig); // ADD THIS LINE
    }


text:
Q: Suppressing unnecessary @throws annotations when new DateTime() should never throw when called without arguments? So, the question itself is pretty simple, but I want to discuss it and find out other people's opinion about it.
As far as I can understand, DateTime constructor throws when you pass invalid arguments and it fails to make something meaningful with them, but what about the case, when you don't pass anything and it uses it's default values? Seems like there will never be an error in that case.
$date = new DateTime();

The problem is that PHPDocs adds unnecessary @throws, even if this will never throw. Would it be safe to create some kind of a helper-function to avoid unnecessary @throws in PHPDocs, that would just suppress this exception, which is never thrown anyway, and make code cleaner? Or is there another way to suppress this elegantly?
/**
 * Suppresses exception on current DateTime
 * creation, which is anyway never thrown.
 *
 * @return DateTime
 */
function getCurrentDateTime(): DateTime
{
    try {
        return new DateTime();
    } catch (Exception $e) {}
}

So, what's your experience on this and do you have any similar function on your project?
P.S: I understand that there are a lot of frameworks and libraries like Carbon that allow you never face this kind of problems, but I'm still curious about finding a good way of handling them without any third party solutions :)


text:
Q: ViewPager fragment with nested RecyclerView fragments using Android design support library I want to use Android design support library to implement the following UI:

*

*Activity with a NavigationView for section navigation.

*When a section is selected, a new (parent) Fragment will be swapped into the container space (FrameLayout).

*The (parent) Fragment is always a CoordinatorLayout. In the layout, a ViewPager may be used. (*problem)

*If ViewPager is used for the (parent) Fragment, it will almost always accompanied by multiple child Fragment with RecyclerView. (*problem)

Problem

*

*When swiping on ViewPager, it doesn't swipe properly (eg. not 1 page per swipe).

*RecyclerView items are not shown (at all).
Activity layout
In Activity, there is a DrawerLayout with NavigationView and a FrameLayout for content fixing as follows:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

Fragment swap
Every time when a navigation item (section) is selected, new (parent) fragment is swapped into FrameLayout (R.id.container) with the following code:
getSupportFragmentManager()
    .beginTransaction()
    .replace(R.id.container, new ParentFragment())
    .commit();

Parent fragment (ViewPager)
In parent fragment, CoordinatorLayout is used together with AppBarLayout and ViewPager as follows:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.test.nestedviewpager.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true" />

</android.support.design.widget.CoordinatorLayout>

The code below initializes the ParentFragment with random number of pages.
package com.test.nestedviewpager;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class ParentFragment extends Fragment {
    private static final int MAX_PAGE_COUNT = 5;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_parent, container, false);

        AppCompatActivity activity = (AppCompatActivity) getActivity();
        activity.setSupportActionBar((Toolbar) root.findViewById(R.id.toolbar));

        final ActionBar actionBar = activity.getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        ViewPager viewPager = (ViewPager) root.findViewById(R.id.view_pager);
        viewPager.setAdapter(new MyPagerAdapter(activity.getSupportFragmentManager(), generatePages()));

        TabLayout tabLayout = (TabLayout) root.findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(viewPager, true);

        return root;
    }

    private static Page[] generatePages() {
        Random rng = new Random();
        int size = rng.nextInt(MAX_PAGE_COUNT);
        if (size <=0 ) { size = 1; }
        Page[] pages = new Page[size];
        for (int pos = 0; pos < size; pos++) {
            pages[pos] = new Page("Page " + (pos + 1));
        }
        return pages;
    }

    private static class MyPagerAdapter extends FragmentPagerAdapter {
        private final List<Page> mPageList = new ArrayList<>();

        MyPagerAdapter(FragmentManager fm, Page[] pages) {
            super(fm);
            if ((pages != null) && (pages.length > 0)) {
                mPageList.addAll(Arrays.asList(pages));
            }
        }

        @Override
        public int getCount() {
            return mPageList.size();
        }

        @Override
        public Fragment getItem(int position) {
            return new ChildFragment();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mPageList.get(position).title;
        }
    }

    private static class Page {
        final String title;

        Page(String title) {
            this.title = title;
        }
    }
}

Child fragment (RecyclerView)
In each child fragment, there consists of a RecyclerView as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

The code below initializes the ChildFragment with random number of items.
package com.test.nestedviewpager;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class ChildFragment extends Fragment {
    private static final int MAX_ITEM_COUNT = 15;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_child, container, false);

        RecyclerView recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view);
        recyclerView.setAdapter(new MyRecyclerAdapter(generateItems()));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        return root;
    }

    private static Item[] generateItems() {
        Random rng = new Random();
        final int size = rng.nextInt(MAX_ITEM_COUNT);
        if (size > 0) {
            Item[] items = new Item[size];
            for (int pos = 0; pos < size; pos++) {
                items[pos] = new Item("Item " + (pos + 1));
            }
            return items;
        }
        return null;
    }

    private static class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder> {
        private final List<Item> mItemList = new ArrayList<>();

        MyRecyclerAdapter(Item[] items) {
            if ((items != null) && (items.length > 0)) {
                mItemList.addAll(Arrays.asList(items));
            }
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View itemView = inflater.inflate(R.layout.recycler_item, parent, false);
            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            holder.bind(mItemList.get(position));
        }

        @Override
        public int getItemCount() {
            return mItemList.size();
        }

        static class MyViewHolder extends RecyclerView.ViewHolder {
            private TextView mTitleView;

            MyViewHolder(View itemView) {
                super(itemView);
                mTitleView = (TextView) itemView.findViewById(R.id.content);
            }

            void bind(Item item) {
                mTitleView.setText(item.title);
            }
        }
    }

    private static class Item {
        final String title;

        Item(String title) {
            this.title = title;
        }
    }
}

I couldn't understand what is wrong with the code written at all. Any help would be very much appreciated.
Thank you.

A: I can't see a reason why the ViewPager would be skipping swipes, but for the Child Fragments, you should return root instead of the super call. That would explain why you see nothing
Maybe instead of activity.getSupportFragmentManager() try to use getChildFragmentManager() from the Fragment class


text: Q: degree of determinant line bundle of pullback in terms of Chern class I have a holomorphic map $f: C \to X$ where $\dim_\mathbb{C}C=1$ and $\dim_\mathbb{C}X=2$. Why is $\text{deg}\det f^*TX=-c_1(X)\cdot[C]$? I'm really curious to how that negative sign shows up.


text:
Q: How do I get this If statement to run once until it comes back round (the condition is constantly true until slide changes) I've created a Flickity slider through Jquery and require a little assitance.
I'm using the selectedIndex as a condition to check what slider is visable. See code below:
    $carousel.on( 'select.flickity', function() {
    if (flkty.selectedIndex === 0) {
        hideAllText();
        text0.fadeIn('slow');
    }
});

This is saying, when slider 0 (initial slide) fade in var text0.
I want to do this for 6 sliders but as the slide doesn't change until 4 seconds has been the if statement keeps running so it keeps hiding and showing text.
Any ideas how I can make this a one time run until the slide comes round again.
Thanks :)

A: This should result in the relevant code only being executed once:
text0Shown = false;

$carousel.on('select.flickity', function() {
  if (!text0Shown && flkty.selectedIndex === 0) {
    text0Shown = true;
    hideAllText();
    text0.fadeIn('slow');
  }
});


text:
Q: Activity view is differnet than emualtor and not showing toolbar I've suddenly noticed that my activity view got messed up somehow until recently it was ok, meaning the toolbar was visible and no gap was under the 'end with' textbox.
what's weird is that I have another activity where I do see the toolbar and the view is fine.
So, in conclusion, my main problem with this view is that the toolbar is missing, there is an unwanted gap under the 'end with' textbox. As you can see in the attached pictures there is no correlation between the XML viewer and the activity view on the emulator.
What could be the reason for that? I ran out of ideas.
<?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="corp.blayzer.randomit.SubmitNumbersActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<LinearLayout
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="56dp"
    android:background="@color/mainBackGroundHalf1"
    android:gravity="center"
    android:orientation="vertical"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/minVal_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:gravity="center"
        app:layout_constraintEnd_toEndOf="@+id/linearLayout"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/linearLayout">

        <EditText
            android:id="@+id/minVal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:backgroundTint="@color/inputText"
            android:ems="10"
            android:hint="@string/minValue"
            android:inputType="number"
            android:maxLength="9"
            android:selectAllOnFocus="false"
            android:singleLine="true"
            android:textAlignment="center"
            android:textAppearance="@android:style/TextAppearance.Material"
            android:textColorHint="@color/inputText"
            app:layout_constraintHorizontal_bias="0.502"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/maxVal_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:gravity="center"
        app:layout_constraintEnd_toEndOf="@+id/linearLayout"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/minVal_layout">

        <EditText
            android:id="@+id/maxVal"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="8dp"
            android:backgroundTint="@color/inputText"
            android:ems="10"
            android:hint="@string/maxValue"
            android:imeOptions="actionDone"
            android:inputType="number"
            android:maxLength="9"
            android:selectAllOnFocus="false"
            android:singleLine="true"
            android:textAlignment="center"
            android:textAppearance="@android:style/TextAppearance.Material"
            android:textColorHint="@color/inputText"
            app:layout_constraintBottom_toBottomOf="@+id/linearLayout"
            app:layout_constraintHorizontal_bias="0.502"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            />

    </android.support.design.widget.TextInputLayout>

</LinearLayout>

<TextView
    android:id="@+id/textChoiceView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:layout_marginTop="16dp"
    android:lineSpacingExtra="8sp"
    android:text="@string/instructionsMainAct"
    android:textAppearance="@android:style/TextAppearance"
    android:textColor="@color/choicesOfNum"
    android:textSize="18sp"
    android:textStyle="bold"
    app:layout_constraintHorizontal_bias="0.506"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/linearLayout"
    app:layout_constraintVertical_chainStyle="packed" />

<FrameLayout
    android:id="@+id/layOutBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="16dp"
    android:orientation="horizontal"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textChoiceView">

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginStart="16dp"
        android:clickable="true"
        android:focusable="true"
        app:fabSize="normal"
        android:src="@drawable/ic_change_history_black_24dp"
        tools:text="@string/GoButton" />
</FrameLayout>
 </android.support.constraint.ConstraintLayout>

A: You need to change height attribute for Toolbar element:
android:layout_height="?attr/actionBarSize"

A: If you use ConstraintLayout as your root container, each widgets should be constrained correctly. The Outermost layer should be CoordinatorLayout . Here is a example.

A: Apparently, I had another layout v26/activity_send_numbers for that activity, that for some reason my emulator kept on using although my device APK was lower. I've Updated/Deleted that layer and all my issues went away. I realized that my code is ok once I've added another FAB and it was not displayed.


text:
Q: Generate two series of random numbers with condition How to generate 1000 sets consisting of 5 random numbers each (buy and sell prices) with the following requirements:
Prices do not have dependencies between sets only within a set.
Prices should be positive numbers with 2 decimal places.
E.g. drawn from a normal distribution with mean 40 and sd 4
Example
set_id 1

buy_prices: 23, 22, 21, 20, 19 -> buy prices should be sorted in desc order
sell_prices: 24, 25, 26, 27, 28 -> sell prices should be sorted in ascending order

Conditions:
buy prices: 1st > 2nd > 3rd > 4th > 5th
sell prices: 1st < 2nd < 3rd < 4th < 5th
In each set the first buy price should be < first sell_price

A: Maybe you can try the code as follows:
BuySell <- function(m = 40, s = 4) {
    S <- pmax(round(rnorm(10, m, s),2), 0)
    S.sorted <- sort(S)
    data.frame(buy = rev(head(S.sorted, 5)),sell = tail(S.sorted, 5))
}

lst <- replicate(1000,BuySell(),simplify = FALSE)

which gives output like below
> head(lst)
[[1]]
    buy  sell
1 38.94 39.12
2 38.93 40.36
3 38.72 42.03
4 38.54 42.58
5 34.86 43.07

[[2]]
    buy  sell
1 42.00 42.20
2 40.01 43.07
3 38.38 44.02
4 36.44 45.56
5 35.23 46.63

[[3]]
    buy  sell
1 41.12 41.26
2 41.01 41.44
3 40.70 41.74
4 36.28 43.04
5 34.97 44.33

[[4]]
    buy  sell
1 39.40 40.39
2 36.78 40.79
3 36.69 42.83
4 35.76 43.02
5 34.57 46.47

[[5]]
    buy  sell
1 38.60 39.03
2 37.90 40.65
3 37.13 43.17
4 35.36 43.74
5 29.99 47.76

[[6]]
    buy  sell
1 39.04 39.29
2 38.41 39.37
3 38.38 41.01
4 34.72 41.55
5 32.92 45.36