text:
Q: Python Two Lists from One list with Tab I have a list:
data = ['Other stuff',186.797\t-48',
 '187.272\t-48',
 '187.747\t-48',
 '188.222\t-45',
 '188.697\t-43',
 '189.172\t6',
 '189.646\t-23',
 '190.121\t12',...]

How do I create two lists one with value before the "/t" and another with the value afterwards.
However, I only want to do this from data[1] to len(data) skipping the first value because it is just descriptive text.
For example:
L1 = [186.797,...,190.121]
L2 = [-48,..., 12]

A: You can use regex:
import re
s = ['186.797\t-48',
 '187.272\t-48',
 '187.747\t-48',
 '188.222\t-45',
 '188.697\t-43',
 '189.172\t6',
 '189.646\t-23',
 '190.121\t12']

L1, L2 = map(list, zip(*[[float(re.findall('[\d\.]+', i)[0]), int(re.findall('[\-\d]+$', i)[0])] for i in s]))

Output:
[186.797, 187.272, 187.747, 188.222, 188.697, 189.172, 189.646, 190.121]
[-48, -48, -48, -45, -43, 6, -23, 12]

A: An easy, clear way would be to use list comprehension and describe where you want to get all the data from. You can use .split("\t") to break each element into a tuple with two values, split by the tab. Then use float and int to convert the element you want.
# Iterate over the list and grab everything before the \t and convert to a float
L1 = [float(val.split("\t")[0]) for val in values]
#: [186.797, 187.272, 187.747, 188.222, 188.697, 189.172, 189.646, 190.121]

# Iterate over the list and grab everything after the \t and convert to an int
L2 = [int(val.split("\t")[1]) for val in values]
#: [-48, -48, -48, -45, -43, 6, -23, 12]

A: Use a list comprehension and separate the values using .split()
l = ['186.797\t-48', '187.272\t-48', '187.747\t-48', '189.172\t6']

[x.split('\t')[0] for x in l]
['186.797', '187.272', '187.747', '189.172']

[x.split('\t')[1] for x in l]
['-48', '-48', '-48', '6']

Edit: If you need number values in your new lists then cast the values to float() or int()
l = ['186.797\t-48', '187.272\t-48', '187.747\t-48', '189.172\t6']

[float(x.split('\t')[0]) for x in l]
[186.797, 187.272, 187.747, 189.172]

[int(x.split('\t')[1]) for x in l]
[-48, -48, -48, 6]


text:
Q: netplan - Network with DHCP configured, but no internet I am trying to configure my Ubuntu Server 20.04 LTS to use DHCP in its network configuration.
Many tutorials on the internet recommend that I create the following file with the following settings...
root@sinj:/home/brlight# cat /etc/netplan/99_config.yaml
network:
  version: 2
  renderer: networkd
  ethernets:
    ens3:
      dhcp4: true

... and run the following commands...
root@sinj:/home/brlight# netplan --debug generate
root@sinj:/home/brlight# netplan apply

PROBLEM: The server is obtaining its settings via DHCP, but is unable to access the internet.

PLUS:
Unlike other servers on the same network, it appears that the server is unable to obtain the gateway settings.
No problem server...
[root@ssh_brl ~]# ip route show
default via 10.0.0.1 dev eth0 proto dhcp metric 100
10.0.0.0/24 dev eth0 proto kernel scope link src 10.0.0.6 metric 100
10.2.0.0/24 via 10.0.0.7 dev eth0 proto dhcp metric 100

Server with problem ...
root@sinj:/home/brlight# ip route show
10.0.0.0/24 dev ens3 proto kernel scope link src 10.0.0.17
10.2.0.0/24 via 10.0.0.7 dev ens3 proto dhcp src 10.0.0.17 metric 100

OTHER INFORMATION:
I
root@sinj:/home/brlight# ip route show
10.0.0.0/24 dev ens3 proto kernel scope link src 10.0.0.17
10.2.0.0/24 via 10.0.0.7 dev ens3 proto dhcp src 10.0.0.17 metric 100

II
root@sinj:/home/brlight# lshw -C network
  *-network
       description: Ethernet controller
       product: Virtio network device
       vendor: Red Hat, Inc.
       physical id: 3
       bus info: pci@0000:00:03.0
       version: 00
       width: 32 bits
       clock: 33MHz
       capabilities: msix bus_master cap_list rom
       configuration: driver=virtio-pci latency=0
       resources: irq:11 ioport:c060(size=32) memory:fc056000-fc056fff memory:fc000000-fc03ffff
     *-virtio0
          description: Ethernet interface
          physical id: 0
          bus info: virtio@0
          logical name: ens3
          serial: 52:54:00:6c:ec:1f
          capabilities: ethernet physical
          configuration: autonegotiation=off broadcast=yes driver=virtio_net driverversion=1.0.0 ip=10.0.0.17 link=yes multicast=yes

III
root@sinj:/home/brlight# networkctl status ens3
● 2: ens3
             Link File: /usr/lib/systemd/network/99-default.link
          Network File: /run/systemd/network/10-netplan-ens3.network
                  Type: ether
                 State: routable (configured)
                  Path: pci-0000:00:03.0
                Driver: virtio_net
                Vendor: Red Hat, Inc.
                 Model: Virtio network device
            HW Address: 52:54:00:6c:ec:1f
                   MTU: 1500 (min: 68, max: 65535)
  Queue Length (Tx/Rx): 1/1
      Auto negotiation: no
                 Speed: n/a
               Address: 10.0.0.17 (DHCP4)
                        fe80::5054:ff:fe6c:ec1f
                   DNS: 10.0.0.1

Mar 06 01:47:12 sinj systemd-networkd[641]: ens3: IPv6 successfully enabled
Mar 06 01:47:12 sinj systemd-networkd[641]: ens3: Link UP
Mar 06 01:47:12 sinj systemd-networkd[641]: ens3: Gained carrier
Mar 06 01:47:12 sinj systemd-networkd[641]: ens3: DHCPv4 address 10.0.0.17/24 via 10.0.0.1
Mar 06 01:47:13 sinj systemd-networkd[641]: ens3: Gained IPv6LL

IV
root@sinj:/home/brlight# dig www.google.com

; <<>> DiG 9.16.1-Ubuntu <<>> www.google.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 10647
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;www.google.com.                        IN      A

;; ANSWER SECTION:
www.google.com.         41      IN      A       172.217.30.36

;; Query time: 48 msec
;; SERVER: 127.0.0.53#53(127.0.0.53)
;; WHEN: Sat Mar 06 04:37:04 UTC 2021
;; MSG SIZE  rcvd: 59

V
root@sinj:/home/brlight# dhclient -v ens3
Internet Systems Consortium DHCP Client 4.4.1
Copyright 2004-2018 Internet Systems Consortium.
All rights reserved.
For info, please visit https://www.isc.org/software/dhcp/

Listening on LPF/ens3/52:54:00:6c:ec:1f
Sending on   LPF/ens3/52:54:00:6c:ec:1f
Sending on   Socket/fallback
DHCPREQUEST for 10.0.0.17 on ens3 to 255.255.255.255 port 67 (xid=0x601d9dc1)
DHCPACK of 10.0.0.17 from 10.0.0.5 (xid=0xc19d1d60)
RTNETLINK answers: File exists
bound to 10.0.0.17 -- renewal in 933 seconds.

VI
root@sinj:/home/brlight# cat /var/lib/dhcp/dhclient.leases
lease {
  interface "ens3";
  fixed-address 10.0.0.17;
  option subnet-mask 255.255.255.0;
  option dhcp-lease-time 4000;
  option routers 10.0.0.1;
  option dhcp-message-type 5;
  option dhcp-server-identifier 10.0.0.5;
  option domain-name-servers 10.0.0.1;
  option dhcp-renewal-time 1000;
  option rfc3442-classless-static-routes 24,10,2,0,10,0,0,7;
  option dhcp-rebinding-time 2000;
  option host-name "sinj";
  renew 6 2021/03/06 05:20:33;
  rebind 6 2021/03/06 05:38:40;
  expire 6 2021/03/06 06:12:00;
}
lease {
  interface "ens3";
  fixed-address 10.0.0.17;
  option subnet-mask 255.255.255.0;
  option dhcp-lease-time 4000;
  option routers 10.0.0.1;
  option dhcp-message-type 5;
  option dhcp-server-identifier 10.0.0.5;
  option domain-name-servers 10.0.0.1;
  option dhcp-renewal-time 1000;
  option rfc3442-classless-static-routes 24,10,2,0,10,0,0,7;
  option dhcp-rebinding-time 2000;
  option host-name "sinj";
  renew 6 2021/03/06 18:50:24;
  rebind 6 2021/03/06 19:10:57;
  expire 6 2021/03/06 19:44:17;
}

VII
root@sinj:/home/brlight# ip route
10.0.0.0/24 dev ens3 proto kernel scope link src 10.0.0.17
10.2.0.0/24 via 10.0.0.7 dev ens3
10.2.0.0/24 via 10.0.0.7 dev ens3 proto dhcp src 10.0.0.17 metric 100

[Refs.: https://ubuntu.com/server/docs/network-configuration ,
http://manpages.ubuntu.com/manpages/cosmic/man5/netplan.5.html , https://www.krizna.com/ubuntu/setup-network-ubuntu-18-04/ ,
https://websiteforstudents.com/configure-static-ip-addresses-on-ubuntu-18-04-beta/ ,
https://www.linuxtechi.com/assign-static-ip-address-ubuntu-20-04-lts/ ]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Play Scala Framework : type mismatch scala.concurrent.Future[Object] [error] required: scala.concurrent.Future[play.api.mvc.Result] I have one compilation error that I cannot solved yet. It's about an action adding a new patient into mongo if he is not already in the database. First the model :
 case class PatientData(id : String)

 object PatientData {
    implicit val PatientDataFormat = Json.format[PatientData]
  }

The function searching the patient in mongo :
 def findPatientById(mode : String, id : String) : Future[Option[PatientData]] = {
    val collection = getPatientCollection(mode)
    collection.find(Json.obj("id" -> id)).one[PatientData]
  }

The Play action :
def create(patientId: String) = Action.async(parse.json) { request =>
    val token = "dummy"
    isAuthorized(token) match { // always return Some(thing)
      case None => Future.successful(Unauthorized("Invalid token " + token))
      case Some(_) =>
        request.body.validate[PatientData] map {
          patientData =>
          findPatientById(mode,patientId) map { finded =>
            finded match {
              case Some(_) => Future.successful(NotAcceptable("The patient is already exist."))
              case None =>
                Logger.info("Create the patient .. ")
                Future.successful(Created)
            }
          }
        } getOrElse {
          Future.successful(BadRequest)
        }
    }

I know that I can solve this problem using a call to Await.result in the function findPatientById but I want avoid this solution and let the Future doing his job. The problem is that I get a compilation error :
[error] /home/afk/git/bioserenity/bioserenity-backend/app/controllers/MedataController.scala:90: type mismatch;
[error]  found   : scala.concurrent.Future[Object]
[error]  required: scala.concurrent.Future[play.api.mvc.Result]
[error]         } getOrElse {
[error]           ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed

Anyone have an idea to solve this issue ?

A: You should probably try to use
findPatientById(mode,patientId) flatMap { ...

instead of original line. Here, the map call is replaced by flatMap so that the instance returned by that block of code is Future[Something] rather than Future[Future[Something]].


text:
Q: Plotting attributes of vertices in WattsStrogatzGraphDistribution[n, p, k] I have a graph WS = RandomGraph[WattsStrogatzGraphDistribution[n, p, k]].
I need to plot several characteristics of each v: the clustering coefficient, number of triples at v, eccentricity, vertex centrality, closeness, and betweenness.
I'm relatively inexperienced with Mathematica and quite lost on how to achieve this.
I don't expect the exact lines of the solution, I'd just like some pointers on how to approach this. First of all, how do I get a set of all the vertices of WS? Then, how do I get the values of the different measures for each v in WS?

A: Update: Using GraphComputation`GraphPropertyChart for displaying vertex attributes:
SeedRandom[777]
ws = RandomGraph[WattsStrogatzGraphDistribution[6, 0.6, 2]];
centralities = {LocalClusteringCoefficient, EccentricityCentrality,
   VertexDegree, ClosenessCentrality, BetweennessCentrality,  EigenvectorCentrality};
Through[centralities[ws]] //
 Style[TableForm[Round[#, .001], TableHeadings -> {centralities, VertexList[ws]}],
   FontFamily -> "Calibri", 24] &

Legended[GraphComputation`GraphPropertyChart[RemoveProperty[ws, VertexLabels],
 Automatic -> (#[ws] + .1),
 ImageSize -> 300, ChartStyle -> 63],
 Placed[Style[#, 20, "Panel"], {1/2, 97/100} ]] & /@
    centralities /. False -> True //
Partition[#, 3] & // Grid

Original answer:
Using the built-in functions mentioned in @Oska's comment:
ws = RandomGraph[WattsStrogatzGraphDistribution[6, 0.1, 2]];
centralities = {LocalClusteringCoefficient,  EccentricityCentrality,
    VertexDegree, ClosenessCentrality, BetweennessCentrality};
Through[centralities[ws]] // Style[TableForm[Round[#, .001],
      TableHeadings -> {centralities, VertexList[ws]}], FontFamily -> "Calibri", 24] &

A: There's one measure you were asking for missing from the existing answer:

number of triples at v

This can be obtained efficiently using IGraph/M's IGAdjacentTriangleCount function.
?IGAdjacentTriangleCount

IGAdjacentTriangleCount[graph] counts the triangles each vertex
  participates in. Edge directions are ignored.
IGAdjacentTriangleCount[graph, vertex] counts the triangles vertex
  participates in.
IGAdjacentTriangleCount[graph, {vertex1, vertex2, ...}] counts the triangles the specified vertices participate
  in.

It can also be implemented in pure Mathematica very concisely (though less efficiently) using the fact that if $A$ is the graph's adjacency matrix, then $(A^k)_{ij}$ contains the number of ways we can get from vertex $i$ to vertex $j$ in $k$ hops.  Thus $(A^3)_{ii}$ gives twice the number of triangles that $i$ participates in (twice because the triangle, i.e. 3-loop, can be traversed in two directions).

g = RandomGraph[{10, 20}];

IGAdjacentTriangleCount[g]
(* {0, 4, 3, 7, 5, 6, 0, 9, 0, 2} *)

With[{am = AdjacencyMatrix[g]},
 Normal@Diagonal[am.am.am]/2
 ]
(* {0, 4, 3, 7, 5, 6, 0, 9, 0, 2} *)

As for visualizing these, these days I much prefer doing this with IGraph/M (disclosure: I'm the author). Here's a simple example:
RandomGraph[WattsStrogatzGraphDistribution[20, 0.2]] //
 IGVertexMap[ColorData["SolarColors"], VertexStyle -> Rescale@*BetweennessCentrality]

The measures you are asking for are available as the following builtin an IGraph/M functions:

*

*clustering coefficient: LocalClusteringCoefficient, IGLocalClusteringCoefficient

*number of triples: IGAdjacentTriangleCount

*eccentricity: VertexEccentricity (for one vertex), EccentricityCentrality (inverse), IGEccentricity

*vertex centrality: I don't know what you mean

*closeness: ClosenessCentrality, IGCloseness, IGClosenessEstimate (for big graphs)

*betweenness: BetweennessCentrality, IGBetweenness, IGBetweennessEstimate (for big graph)
Here's a nicer plot of all of them, also showing off IGWattsStrogatzGame, which supports some additional features not available with WattsStrogatzGraphDistribution.
g = IGWattsStrogatzGame[20, 0.2, GraphLayout -> "CircularEmbedding", VertexSize -> Large, GraphStyle -> "BasicBlack"]

Labeled[IGVertexMap[ColorData["Rainbow"], VertexStyle -> Rescale@*#, g], #] & /@
     {LocalClusteringCoefficient, IGAdjacentTriangleCount, IGEccentricity, ClosenessCentrality, BetweennessCentrality}


text:
Q: MyIsam engine transaction support I was testing transaction support in innoDB tables, and just for the curriosity I tried to run the same transaction on MyIsam table, and surprisingly it worked. I am assuming that on myIsam table queries are executed one after another not in one atomic operation and I don't get any errors from START TRANSACTION and COMMIT and ROLLBACK operations. I am interested, is MyIsam engine just ignoring this operations or does it perform some actions?

A: MyIsam tabels were not built for this. Not even in the 5+ versions. It only was meant to store data. It gives you no guarantee for transactions or data recovery. You should use InnoDB for this and, if needed, use MyIsam for replication purposes (it's faster to retrieve data with MyIsam tables since there's no cross-table checks).
You may read this post from MySQL
http://forums.mysql.com/read.php?21,68686,69229#msg-69229

A: MyISAM effectively works in auto-commit mode (as it's not a transactional engine), and it just ignores the commit/rollback.
Actually storage engine is a different layer in the MySQL architecture, separated from the SQL parser, the SQL layer communicates to the storage engine with lower-level API, and that's the reason there is a common SQL and engines, supporting different subset of featured. You can see very high-level overview of the architecture here


text: Q: react native view shot how to make something visible only in screenshot I'm using react native view shot to make screenshot and share it to social. I also want to add something to the footer like 'Get this app from playstore and appstore with logo. It should not visible in actual app. How can I do that?


text:
Q: Dictionary comprehensions(?) in F# (converting from C#) OK, so, I'm just starting out learning F#. I have some exposure to functional languages from university etc, but still I'm quite green when it comes to real world programming in languages such as F#.
On a day-to-day basis I work in C#, but today I had the opportunity to spend some time with my company's code base, and look at it from an F# perspective. I decided to try to rewrite some of our C# code in F#, to get a feel for the language in a realistic business setting.
Here's a paraphrase of some C# code that I struggled to translate:
// MyData is a class with properties Id, Analysis, and some other relevant properties
// Each pair of (Id, Analysis) is (should be) distinct
IEnumerable<MyData> data = // fetch from DB...

// dataDict[id[analysis]] = MyData object (or "row") from DB
var dataDict = new Dictionary<String, Dictionary<String, MyData>> ();
foreach(var d in data)
{
    if(!dataDict.ContainsKey(d.Id))
        dataDict.Add(d.Id, new Dictionary<string, MyData>());

    if (dataDict[d.Id].ContainsKey(d.Analysis))
    {
        logger.Warn(String.Format("Id '{0}' has more than one analysis of type '{1}',
            rows will be ignored", d.Id, d.Analysis));
    }
    else
    {
        dataDict[d.Id].Add(d.Analysis, d);
    }
}

My attempt at rewriting the loop in a "functional" manner resulted in the following code, but I don't feel all that good about it.
let dataDict =
      dict [
        for d in data
          |> Seq.distinctBy(fun d -> d.Id) -> d.Id,
             dict [
                 for x in data |> Seq.filter(fun a -> a.Id = d.Id) -> x.Analysis, x
             ]
      ]

A couple of issues with this code:

*

*It does not log a warning in case of duplicate (Id, Analysis) pairs, and, even worse

*I run through the data (at least) twice with the for and the Seq.filter.

How can I improve this? Am I doing it all wrong?

A: What I would consider a more functional approach:
let intoMap (data: seq<MyData>) =
    Seq.fold (fun (datamap, dups) (data: MyData) ->
        match datamap |> Map.tryFind data.Id with
        | Some submap when submap |> Map.containsKey data.Analysis ->
            datamap, data :: dups
        | Some submap ->
            let ext = Map.add data.Analysis data submap
            (Map.add data.Id ext datamap), dups
        | None ->
            let submap = Map.ofArray [| (data.Analysis, data) |]
            (Map.add data.Id submap datamap), dups
        ) (Map.empty, List.empty) data

It's a fold over the data, so it traverses the sequence once. It's also more functional in that it's not side-effecting - instead of logging duplicates, they're collected and made part of the output. You can do whatever you like with them later.
Also, I use the immutable Map instead of Dictionary - I find Dictionary to be a kind of code smell in F# code. The mutability it provides has its uses in some more esoteric scenarios, but for actually holding and passing around data, I would use Map exclusively.
That's the answer to your immediate question - but to be honest, I would probably go for a separate function for finding and splitting out duplicates, and a separate function that would build up a map without caring for potential duplicates - even if that would mean multiple passes over the data.

A: Given your requirements, what you have is probably best. You can tighten the code a bit using pattern matching.
let dataDict = Dictionary<_,Dictionary<_,_>>()
for d in data do
    match dataDict.TryGetValue(d.Id) with
    | true, m when m.ContainsKey(d.Analysis) ->
        (d.Id, d.Analysis)
        ||> sprintf "Id '%s' has more than one analysis of type '%s', rows will be ignored"
        |> logger.Warn
    | true, m ->
        m.Add(d.Analysis, d)
    | _ ->
        let m = Dictionary()
        m.Add(d.Analysis, d)
        dataDict.Add(d.Id, m)


text:
Q: .htaccess redirect domain.com to domain.com/ Is it possible to use a .htaccess file to redirect mydomain.com to mydomain.com/
I tried:
RewriteRule ^(.*)/$ http://%{HTTP_HOST}/$1

which should work for any URL on the domain however it only works for non-root URLs (Above code removes trailing slash rather than adds it, however I wanted to see if it'd work for root URLs).
There was also the solution from here which is:
RewriteCond %{THE_REQUEST} ^([A-Z]{3,9})\ (.*)//([^\ ]*)
RewriteRule ^ %2/%3 [R=301,L]

This removes multiple trailing slashes (ie mydomain.com// becomes mydomain.com/) but still doesn't work for mydomain.com -> mydomain.com/
I'd even accept a way to do it with PHP if that's available.

A: http://mydomain.com and http://mydomain.com/ look exactly the same to the webserver, the URI is / for both of them. You're not going to be able to force the browser's address bar to have a trailing slash after the domain from .htaccess or php.

A: Try:
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L]


text:
Q: python web scraping with missing source code I am trying to scrape the pricing information from these two websites: site1 and site2
I am using Python and packages BeautifulSoup and requests.
What I realized is that the pricing section is not available in the source code for both sites. So I am wondering how I can scrape the data.
Any advice would be appreciated. Thank you

A: The problem is that first you need to select a country to see the prices.
In technical sense, you need to make a POST request to http://www.strem.com/catalog/index.php to select a country, then you can get the prices:
from bs4 import BeautifulSoup
import requests

URL = "http://www.strem.com/catalog/v/29-6720/17/copper_1300746-79-5"
session = requests.session()
p = session.post("http://www.strem.com/catalog/index.php", {'country': 'USA',
                                                            'page_function': 'select_country',
                                                            'item_id': '7211',
                                                            'group_id': '17'})

response = session.get(URL)
soup = BeautifulSoup(response.content)
print [td.text.strip() for td in soup.find_all('td', class_='price')]

This prints:
[u'US$85.00', u'US$285.00', u'US$1,282.00', u'US$3,333.00']

A more elegant solution would be to submit a form using mechanize package:
import cookielib
from bs4 import BeautifulSoup
import mechanize

URL = "http://www.strem.com/catalog/v/29-6720/17/copper_1300746-79-5"
browser = mechanize.Browser()
cj = cookielib.LWPCookieJar()
browser.set_cookiejar(cj)
browser.open(URL)
browser.select_form(nr=1)
browser.form['country'] = ['USA']
browser.submit()

data = browser.response().read()
soup = BeautifulSoup(data)
print [td.text.strip() for td in soup.find_all('td', class_='price')]

Prints:
[u'US$85.00', u'US$285.00', u'US$1,282.00', u'US$3,333.00']


text:
Q: Delete a component from the NavBar I am trying to remove the Contacts button on the NavBar NavBar Pic. I have tried everything I know and am stuck. I am new to Angular/Typescript, so any help would be appreciated. The code listed below is from the contacts.components.ts file. Also, I have looked through the navbar.component.html page and there is no mention of Contacts anywhere within in.
From contacts.components.ts file:
import { IProductConfig } from 'app/interfaces/interfaces';
import { BaseComponent } from './../base.component';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-contacts',
  templateUrl: './contacts.component.html',
  styleUrls: ['./contacts.component.css']
})
export class ContactsComponent extends BaseComponent implements OnInit {
  productOptions: IProductConfig;
  queryUrl: String;
  getContactsContentViewFields: JSON;

  ngOnInit() {
    this.productOptions = this.product_config

    this.getContactsContentViewFields = JSON.parse(`{
      "Description" : {"title":"", "type":"string"}
    }`);

  }
}

From navbar.component.html

           0 ? 'collapse': null"
            [attr.aria-expanded]="(level1Item.isExpanded == true) ? 'true' :
'false'" [attr.target]="level1Item?.OpenInNewTab ? '_blank': '_blank'">

{{level1Item.Level1Title}}
               0" class="caret">

A: If you want to restrict access to the Contacts page, there are quite a few ways of doing it.

*

*If removing or disabling the Contacts button in the navbar is fine,
then you will just have to tinker with the HTML code of the navbar.

*If removing or disabling the Contacts button in the navbar is not
fine then you could try using angular route gaurds.
You may return false in the canActivate() function of the guard file in order to always restrict access to the user.

A: Sorry I can't comment, but I have found that sometimes setting the *ngIf to check for equality instead of null checks works better for whatever reason when running into UI updating. Like :
*ngIf="level1Item == "aValueYouAreLookingFor"
If it's just change detection check out this and ngZone ngZone has played a big part in updating the UI in larger operations on my current project so it's worth a look.
I've been working with Angular 4+ since it came out and like Angular JS it can take a few hacks to get things done :-) Good luck!!


text:
Q: Probability of getting exactly one correct card when distributing n cards among n people If I distribute n cards among n people and each person can get one correct card matched his identity.
What is the probability that only one person would get the correct card?

A: Choose one person to get the correct card, done in n ways.
Then distribute the remaining cards such that the (n-1) people do not have their correct cards. You will then need to apply the formula for derangements here I think.
After that, divide by n! to obtain the required probability.


text:
Q: Sporadic unusually slow performance for inserting a single row into PostgreSQL database table I am using a combination of Amazon Aurora (Aurora PostgreSQL    11.6) and Entity Framework Core to perform (among other Db operations) a very simple 1 row insert into a relatively small (33k) record table.
A majority of the time the insert takes in the single digit ms, but occasionally I notice the insert takes around 950ms. I don't really understand what is causing this? Whenever I try reviewing an EXPLAIN/ANALYZE it shows me nothing much, as its just an insert with a returning id. I can't see any obvious issues here. It's also strange that no other inserts seem affected by this sporadic 'slowness'. Can anyone assist?
Table:
CREATE TABLE request_to_print (
    request_internal_id UUID NOT NULL DEFAULT uuid_generate_v4(),
    card_number VARCHAR(100),
    customer_internal_id UUID NOT NULL,
    requested_date TIMESTAMP,
    requesting_store VARCHAR(10),
    request_sent_date TIMESTAMP,
    PRIMARY KEY ("request_internal_id")
);

Sample statement:
INSERT INTO request_to_print (card_number, customer_internal_id, request_sent_date, request_type, requested_date, requesting_store)
VALUES (@p0, @p1, @p2, @p3, @p4, @p5)
RETURNING request_internal_id;

Output from an explain/analyze
[
  {
    "Plan": {
      "Node Type": "ModifyTable",
      "Operation": "Insert",
      "Parallel Aware": false,
      "Relation Name": "request_to_print",
      "Schema": "public",
      "Alias": "request_to_print",
      "Startup Cost": 0,
      "Total Cost": 0.01,
      "Plan Rows": 1,
      "Plan Width": 422,
      "Actual Startup Time": 0.072,
      "Actual Total Time": 0.073,
      "Actual Rows": 1,
      "Actual Loops": 1,
      "Output": [
        "request_internal_id"
      ],
      "Shared Hit Blocks": 3,
      "Shared Read Blocks": 0,
      "Shared Dirtied Blocks": 0,
      "Shared Written Blocks": 0,
      "Local Hit Blocks": 0,
      "Local Read Blocks": 0,
      "Local Dirtied Blocks": 0,
      "Local Written Blocks": 0,
      "Temp Read Blocks": 0,
      "Temp Written Blocks": 0,
      "I/O Read Time": 0,
      "I/O Write Time": 0,
      "Plans": [
        {
          "Node Type": "Result",
          "Parent Relationship": "Member",
          "Parallel Aware": false,
          "Startup Cost": 0,
          "Total Cost": 0.01,
          "Plan Rows": 1,
          "Plan Width": 422,
          "Actual Startup Time": 0.02,
          "Actual Total Time": 0.02,
          "Actual Rows": 1,
          "Actual Loops": 1,
          "Output": [
            "uuid_generate_v4()",
            "''::character varying(100)",
            "'5687afea-52cd-4e11-8278-9a71fb9f5982'::uuid",
            "'2021-05-14 06:24:17.424055'::timestamp without time zone",
            "''::character varying(10)",
            "'2021-05-14 06:24:17.424055'::timestamp without time zone",
            "''::character varying(50)"
          ],
          "Shared Hit Blocks": 0,
          "Shared Read Blocks": 0,
          "Shared Dirtied Blocks": 0,
          "Shared Written Blocks": 0,
          "Local Hit Blocks": 0,
          "Local Read Blocks": 0,
          "Local Dirtied Blocks": 0,
          "Local Written Blocks": 0,
          "Temp Read Blocks": 0,
          "Temp Written Blocks": 0,
          "I/O Read Time": 0,
          "I/O Write Time": 0
        }
      ]
    },
    "Planning Time": 0.02,
    "Triggers": [],
    "Execution Time": 0.087
  }
]

Additional information:
"Insert on request_to_print  (cost=0.00..0.01 rows=1 width=422) (actual time=0.070..0.071 rows=1 loops=1)"
"  ->  Result  (cost=0.00..0.01 rows=1 width=422) (actual time=0.020..0.020 rows=1 loops=1)"
"Planning Time: 0.021 ms"
"Execution Time: 0.094 ms"

A: There is a possibility that is the uuid_generate_v4() field that is causing the issue. We have a column using that as the default, and now for some unknown reason it's slowed our inserts by a factor of 10. We used to get 25000 inserts a second, and now it's 2000. If I drop the column the speed returns, if I add it back it slows back down. Why the performance all of a sudden degraded is beyond me, but it might explain your sporadic performance.


text:
Q: How to have XF86Audio* keys work with alsa? I am running Ubuntu on my Chromebook.  I have remapped keys so that the dedicated keys (e.g., brightness, back, forward, etc.) all do the desired function (thank you FascinatingCaptain).  I have audio working but this device does not use pulseaudio but only alsa with the SOF.  I can use amixer to adjust the volume but the dedicated keys don't affect the volume -- assumedly because the XF86Audio* directives are trying to do something other than affect axmixer.
How do I get the XF86Audio* directivces to work with alsa?  I think it involves getting into the XF86Audio directives and tell them to do something different?  Or, is it a matter of mapping these keys to something else?
I tried this: I created custom key shortcuts that run the appropriate amixer commands and selected the respective key.  In the short cut, it shows "AudioRaiseVolume" and "AudioLowerVolume".  But hitting those keys do not change the volume.  Running the exact same command in the terminal works fine; the volume raises and lowers as expected.  So, I removed those shortcut and created new ones of Ctrl-UpArrow and Ctrl-DnArrow.  These shortcuts worked.  But I prefer to have the designated audio volume keys change the volume.


text:
Q: Newly added translation is not shown On a Typo3 4.4.2 with existing translations I wanted to add a new one. But the text element is only displayed on the default language and not on the English page. Then I tried to add a content element on the English page. Here it will be shown but only in English. It seems that the translations are completely separated from each other ...
Here is the TS:
config {
  linkVars = L
  sys_language_mode = content_fallback
  sys_language_overlay = hideNonTranslated
  sys_language_uid =
  language = de
  locale_all = de_DE
  doctype = xhtml_trans
  htmlTag_langKey = de
}

[globalVar = GP:L = 1]
config.sys_language_uid = 1
page.config.language = en
page.config.locale_all = en_EN
[global]

What is here wrong? Deleting the cache had no success so it is another problem.

A: Please use the "Copy default content elements" option for translating default content elements to English language.

A: Make sure to translate the page with the content element too. Otherwise the content element can not be saved.
If the mapping between the translation is lost, then you have to fix this in the database or with the extension languagevisibility.


text:
Q: Cube.dev - how to have the parameter "today date" in rolling window? I have a PostgreSQL database in which users can order from a start date to an end date.
I want to know, for each day, how many users would be able to order.
Let's make an example, given:

id
from
to

A
2023-01-01
2023-01-03

B
2023-01-02
2023-01-07

C
2023-01-02
2023-01-09

D
2023-01-10
2023-01-12

For the first two weeks (let's suppose that the 01/01/2023 were on Monday), I would have (the third column is not needed):

day
n_of_users_that_can_order
who

2023-01-01
1
A

2023-01-02
3
A, B, C

2023-01-03
3
A, B, C

2023-01-04
2
B, C

2023-01-05
2
B, C

2023-01-06
2
B, C

2023-01-07
2
B, C

2023-01-08
1
C

2023-01-09
1
C

2023-01-10
1
D

2023-01-11
1
D

2023-01-12
0

2023-01-13
0

2023-01-14
0

My end result should be the above table aggregated per week:

week
total

2023-01-01 to 2023-01-07
15

2023-01-08 to 2023-01-14
4

I don't know how to do it with cube.dev, this is the idea I had for now:
ube(`Users`, {
  sql: `SELECT * FROM public.users`,

  measures: {
    usersPerDayThatCanOrder: {
      type: `count`,
      sql: `id`,
      rollingWindow: {
        trailing: `1 day`,
        offset: `start`
      },
      filters: [
        { sql: `${CUBE}.can_order_from >= ${TODAY} AND ${CUBE}.can_order_to <= ${TODAY}` }, // NOTE: today doesn't exist
      ]
    }
  },

  dimensions: {
    id: {
      sql: `id`,
      type: `number`,
      primaryKey: true
    },

    canOrderFrom: {
      sql: `can_order_from`,
      type: `time`
    },

    canOrderTo: {
      sql: `can_order_to`,
      type: `time`
    },
  },

  dataSource: `default`
});

But it does not work because I do not know how to have the real ${TODAY} value and also how to aggregate per week.

A: Here is a sql query which provides your expected result assuming that your table is named test :
SELECT d.week AS "week start"
     , (d.week + interval '6 days') :: date AS "week end"
     , sum( upper(daterange(d.week, (d.week + interval '1 week') :: date, '[)') * daterange(t."from", t."to", '[]'))
          - lower(daterange(d.week, (d.week + interval '1 week') :: date, '[)') * daterange(t."from", t."to", '[]'))
          )
  FROM
     ( SELECT generate_series(min(date_trunc('week', "from")), max("to"), interval '1 week') :: date AS week
         FROM test
     ) AS d
 INNER JOIN test AS t
    ON daterange(d.week, (d.week + interval '1 week') :: date, '[)') && daterange(t."from", t."to", '[]')
 GROUP BY d.week
 ORDER BY d.week

*

*The subquery calculates the weeks start date covered by table test

*The INNER JOIN clause intersects the weeks with the user date ranges

*Then rows are concatenated by weeks and the number of days are summed for all the users

By the way, the 2023/01/01 seems not to be Monday but Sunday.
Result :

week start
week end
sum

2022-12-26
2023-01-01
1

2023-01-02
2023-01-08
15

2023-01-09
2023-01-15
4

see test result in dbfiddle


text:
Q: CakePHP 2.4: Escaping Javascript within the confirmation message of html->link? This is what I have :
<?php
$textDelete = __('Delete' . ($index ? '' : ' This ' . $identifier));
$linkDelete = array('controller' => 'students', 'action' => 'delete', $id);
$confirmDelete = 'You are about to delete student:\n\n\x22'
                   . $student['Student']['last_name'] . ', '
                   . $student['Student']['first_name'] . ' '
                   . $student['Student']['middle_initial']
                   . '\x22\n\n  Are you sure?';

echo $this->Html->link(
                       $textDelete,
                       $linkDelete,
                       array('escape' => false),
                       $confirmDelete
                    );
 ?>

It was working fine, till we upgraded to CakePHP 2.4! Now the confirmation message (all of them) of the link shows the \n\n and \x22 instead of quotes symbol or new lines, any ideas?

A: Honestly I was going to delete the question! But I thought its too silly for someone else to waste half a day on it!
Just replace single quotes with double quotes and everything back to normal again! (embarrassing)


text:
Q: I am trying to hold value of document.getElementById("image").src=UserInput +".gif" first I want to hold the value of
document.getElementById("image").src = UserInput + ".gif";
in (var filepath) then I want to convert that value to if filepath is true or false
var FilePath === document.getElementById("image").src = UserInput + ".gif";

if(Filepath==true){
    #do something
}
else{
    #print user input is wrong
}

A: send ajax request to check if file exists on your server:
var file_name = document.getElementById("image").src = UserInput + ".gif";
var url_to_file = "http://www.example.com/"+file_name;
$.ajax({
  url: url_to_file,
  type:'HEAD',
  error: function()
  {
    //file doesnt exist
  },
  success: function()
  {
    //file exists
  }
});

Its worth to mention this:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD
setting type: 'head' in ajax request won't download file itself.

A: You can use the image's load and error events to detect whether the image can be loaded successfully or not.
var image = document.getElementById("image");
image.addEventListener("load", function() {
    # do something
});
image.addEventListener("error", function() {
    # print user input is wrong
});
image.src = UserInput + ".gif";


text:
Q: Make EC2 Autoscaling scale-out more quickly for customMetric I'm setting up an AWS EC2 Autoscaling Group (ASG) and it's using TargetTrackingScaling that is tracking a custom metric. This metric is published by each instance in the ASG every 30 seconds.
It's working fine, but I'd like the scale-out action to happen more quickly. The source of this looks to be due to the ASG Alarm that gets auto generated. To me it looks like it's waiting for at least 3 datapoints over 3 minutes before ringing the alarm.
Is there a way I can configure the ASG/Scaling policy such that the alarm only needs 1 datapoint (or less time) before deciding to ring the alarm? Or if that's not possible, can I create a custom alarm and use that instead of the alarm that the ASG auto generated.


text:
Q: What is a dc reset? I read this sentence from a book: "MR is a dc reset". It said about master reset leg in a counter IC.
I have been searching but found nothing related to this terminology. I wonder what a dc reset is?

A: Without any context in your question other than "a book" the best that can be said is that it refers to the counter reset input on a digital counter chip. A defined logic 1 or 0 on this pin will reset the counter to a predefined count value - almost always zero.
The DC (capitals?) refers to direct current. This is a bit confusing as DC gives the impression that the voltage is constant whereas for the reset signal it will typically be a pulse. Again, without context, the best that can be said is that the author intends to convey the impression that the signal is DC coupled as in standard electronic logic.

A: I will assume that the reset operates on a high input here.  If it's low to reset, just reverse high and low in the description below.
A reset signal could be edge-triggered, or not.  If it's edge triggered, then the reset will happen when the MR goes from low to high, but then it will come out of reset, even if MR remains high.
By specifying that it's DC reset, then the system will reset when the MR pin goes from low to high, and remain reset until that pin goes low again.

A: My WAG:  Likely, since it is a IC, this is a "power-on reset", which conceptually, in ICs, is a reset that places all registered logic (that has a reset attached) to a known value.  The fact that the author refers to it as "dc reset" is probably a pedantic detail he uses to make it clear that the reset is(/should be) sourced from the DC portion of whatever CCA/PCB the IC is instantiated upon.


text:
Q: How to add entity via spring and hibernate in many to one relation the first time? I have a User class and a Business class which Business has OneToMany Relation to User. When the first time user wants to create an account, it does not have any business, thus I need to create user first, then create a business for it.
I am using kotlin, spring, hibernate and jpa.
As you can see in the code, business field for User is optional, however it fails when I try to add a user without having a business.
How should I add an entity in many to one relation where the other side of the many-to-one relation (business) does not exist?
@Entity
@Table(name = "users")
class User(
    @Id
    @Column(nullable = false, updatable = false, columnDefinition = "uuid")
    override val id: UUID = UUID.randomUUID(),
    @ManyToOne(fetch = FetchType.LAZY, cascade = [CascadeType.ALL])
    @JoinColumn(name = "business_id")
    @JsonIgnore
    var business: Business? = null,
)

@Entity
class Business(
    @Id
    @Column(nullable = false, updatable = false, columnDefinition = "uuid")
    override var id: UUID = UUID.randomUUID(),
@OneToMany(mappedBy = "business", fetch = FetchType.LAZY, cascade = [CascadeType.ALL], orphanRemoval = false)
    @JsonIgnore
    var users: MutableSet<User>? = HashSet()
)

data class AddUserRequest(
    val businessId: UUID?
)

@Service
class UserServiceImpl(
    @Autowired private val userDAO: UserDAO,
    @Autowired private val businessDAO: BusinessDAO
) : UserService {
    override fun save(addUserRequest: AddUserRequest): User? {
        return userDAO.save(addUserRequest.toUser())
    }
    fun AddUserRequest.toUser(): User {
        return User(
            /*** different codes I tried: ***/
            business = null
            business = businessId
                ?.let { businessDAO.getReferenceById(it) }
                ?.let { businessDAO.save(Business.default(UUID.randomUUID())) }
            business = businessId?.let { businessDAO.getReferenceById(businessId) }
            business = businessId?.let { businessDAO.getById(businessId) }
            business = businessId?.let { businessDAO.getOne(it)}?.let { null }
            business = businessId?.let { businessDAO.getById(businessId) }?.let {businessDAO.save(Business.default())}
        )

}


text:
Q: File written 3 times C# I have this code that is being repeated 3 times:
private static void convert(object source, FileSystemEventArgs f)
{
    string FileName;
    FileName = f.FullPath;

    string destinationFile = @"Y:\test\test.xml";
              System.Threading.Thread.Sleep(2000);
   try
   {

        Encoding utf8 = new UTF8Encoding(false);
        Encoding ansi = Encoding.GetEncoding(1256);
        System.Threading.Thread.Sleep(2000);

        string xml = File.ReadAllText(FileName, ansi);
       XDocument xmlDoc = XDocument.Parse(xml);
            **Console.WriteLine("1st");**
            File.WriteAllText(
               destinationFile,
                @"<?xml version=""1.0"" encoding=""utf-8""?>" + xmlDoc.ToString(),
               utf8
            );
    }

Check the above in bold. It writes out 3 times. I have just put that to test. But why does it write out 3 times.. Meaning the file being written is also written 3 times.
I'm calling this function from a filesystemwatcher function to watch a folder if it has changed then take the file convert it to utf-8 and put it in the destination file.
EDIT 1:
Here is my watcher. Can you please check if this is fine:
private static void WatchFile()
    {
                watcher.Path = @"C:\project";

                   watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Filter = "*.xml";

        watcher.Changed += new FileSystemEventHandler(convert);
        watcher.Error += new ErrorEventHandler(WatcherError);
        Console.WriteLine("2nd");
        watcher.EnableRaisingEvents = true;

    }

Still don't have a clue why it gets repeated 3 times.
EDIT 2:
Here goes' my complete code:
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Linq;

class Test
{
 class Class1
{
    private static FileSystemWatcher watcher =
       new FileSystemWatcher();

    public static void Main()
    {
        WatchFile();
      Console.ReadLine();
     }

    private static void WatchFile()
    {
        watcher.Path = @"C:\project";

                    watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Filter = "*.xml";

        watcher.Changed += new FileSystemEventHandler(convert);
        watcher.Error += new ErrorEventHandler(WatcherError);
        Console.WriteLine("2nd");
        watcher.EnableRaisingEvents = true;

    }

    public static string CrL = "\r\n";

    private static void convert(object source, FileSystemEventArgs f)
    {
        string FileName;
        FileName = f.FullPath;

               string destinationFile = @"Y:\test\OnAirNow.xml";

                 System.Threading.Thread.Sleep(2000);
       try
       {

            Encoding utf8 = new UTF8Encoding(false);
            Encoding ansi = Encoding.GetEncoding(1256);
            System.Threading.Thread.Sleep(2000);

            string xml = File.ReadAllText(FileName, ansi);
           XDocument xmlDoc = XDocument.Parse(xml);
                Console.WriteLine("1st");
                File.WriteAllText(
                   destinationFile,
                    @"<?xml version=""1.0"" encoding=""utf-8""?>" + xmlDoc.ToString(),
                   utf8
                );

        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }

    }

    private static void WatcherError(object source, ErrorEventArgs e)
    {

        Exception watchException = e.GetException();
                   watcher = new FileSystemWatcher();
        while (!watcher.EnableRaisingEvents)
        {
            try
            {
                                   WatchFile();
                Console.WriteLine("I'm Back!!");
            }
            catch
            {
                                    System.Threading.Thread.Sleep(2000);
            }
        }
    }

  }
 }

A: A common pattern using FileSystemWatcher is to set EnableRaisingEvents to false when starting processing the event:
this.fileSystemWatcher = new FileSystemWatcher()
{
    Path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
    NotifyFilter = NotifyFilters.LastWrite,
    Filter = Path.GetFileName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
};

this.fileSystemWatcher.Changed += this.ConfigChanged;
this.fileSystemWatcher.EnableRaisingEvents = true;

and
public void ConfigChanged(object sender, FileSystemEventArgs e)
{
    try
    {
        this.fileSystemWatcher.EnableRaisingEvents = false;
        s_logger.Info("Configuration file changed.");
        // reload config here
        s_logger.Info("Configuration settings reloaded.");
    }
    catch (Exception exception)
    {
        s_logger.Error(exception.Message);
        s_logger.Error("Failed to reload configuration settings.");
    }
    finally
    {
        this.fileSystemWatcher.EnableRaisingEvents = true;
    }
}

A: The FileSystemWatcher might raise more than one event for one file change, check it out:

Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.

FileSystemWatcher Class in MSDN


text:
Q: Using Passport.js and express-session, every route but the login route sends a cookie that does not include user information I'm trying to build an app with Node.js and Passport.js, but I don't want to continue if I can't nail down authentication. Right now I have passport-local set up and once I log in, by all accounts I should be getting an authenticated user on other routes. But I'm not. It looks like the session cookie being sent when logged in has the user info, but every other route sends a cookie that lacks the user info. I can't for the life of me figure out what I'm doing wrong.
here is how app is set up:
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: true,
    cookie: {
      secure: false,
    },
    store: new FirestoreStore({
      dataset: new Firestore(),
      kind: "express-sessions",
    }),
  })
);
app.use(passport.initialize());
app.use(passport.session());

My route:
userRouter
  .route("/api/v1/signup")
  .post(jsonParser, async (req, res, next) => {
    // console.log(req.body);
    addUser(req.body);
    res.status(200).json({ message: "success" });
  });

userRouter.route("/api/v1/login").post(
  jsonParser,
  passport.authenticate("local", {
    session: true,
  }),
  async (req, res, next) => {
    res.status(200).json({ message: "success" });
  }
);

and my passport.js
const LocalStrategy =
  require("passport-local").Strategy;
const argon2 = require("argon2");
const {
  getUserByEmail,
  getUserById,
} = require("../database/users");

const initialize = (passport) => {
  const authenticateUser = async (
    email,
    password,
    done
  ) => {
    const user = await getUserByEmail(email);

    if (user === null) {
      return done(null, false, {
        message: "No user with that email",
      });
    }

    // argon2.verify(user.email, password);

    try {
      const verifiedPassword =
        await argon2.verify(
          user.password,
          password
        );
      if (verifiedPassword) {
        // password match
        console.log("success");
        return done(null, user);
      } else {
        // password did not match
        console.log("failure");
        return done(null, false, {
          message: "Password incorrect",
        });
      }
    } catch (error) {
      // internal failure
      console.log(error, "error");
      return done(error);
    }
  };

  passport.use(
    new LocalStrategy(
      {
        usernameField: "email",
      },
      authenticateUser
    )
  );

  passport.serializeUser((user, done) => {
    done(null, user.id);
  });
  passport.deserializeUser((id, done) => {
    return done(null, getUserById(id));
  });
};

module.exports = initialize;

When I login, my session gets this cookie:
Session {
  cookie: {
    path: '/',
    _expires: null,
    originalMaxAge: null,
    httpOnly: true,
    secure: false
  },
  passport: { user: 1657255017610 }
}

On every other route when I want to check if the user is authenticated or not, I get this:
Session {
  cookie: {
    path: '/',
    _expires: null,
    originalMaxAge: null,
    httpOnly: true,
    secure: false
  }
}


text:
Q: $X$ and $Y$ are independent Poisson distributed values with means $θ$ and $2θ$. Consider the combined estimator $\gamma = k_1\cdot X + k_2\cdot Y$ $X$ and $Y$ are independent Poisson distributed values, means are $θ$ and $2θ$.
Consider the combined estimator $$\gamma = k_1\cdot X + k_2\cdot Y$$ where $k_1$ and $k_2$ are arbitrary constants.
(a) Find the condition on $k_1$ and $k_2$ such that $\gamma$ is an unbiased estimator.
To solve this I let $\theta = E[k_1X + k_2Y] = k_1E[X] + k_2E[Y]$
$\theta = k_1\theta + 2k_2\theta$, $k_1 + 2k_2 = 1$
However I'm stuck when it comes to the next 2 parts:
(b) For $\gamma$ unbiased, show that the variance of the estimator is minimized by taking
$k_1 = 1/3$ and $k_2 = 1/3$.
(c) Given observations x and y find the maximum likelihood estimate of θ. and
hence show that $\gamma$ is also the maximum likelihood estimator.
I'm not sure where to even start for part (b) and part (c). Any help would be appreciated!


text:
Q: Retrieve Android Market mylibrary with curl I am trying to retrieve this page using curl in php. This page of course requires you to log in because it displays different apps for each user. I have been following the work done on this page, however am not having much success.
So far, in his example I am able to successfully populate the auth variable with the auth token. In the next step however (Below the comment for logging into Android Market) I run into troubles. The output variable that he says should have a 302 code results in a "The document has moved" page which links me back to the Google log in page.
Here is a pastebin to show exactly what I am trying. http://pastebin.com/9Fs9GWxk
Additionally if anyone knows what steps I need to do after this to actually get the page I need that would be amazing. Thanks

A: Here is something I came up with today for this question that has been modified to work for you:
<?php

$USERNAME = 'you@gmail';
$PASSWORD = 'yourpasswd';

$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Ubuntu; X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, COOKIEJAR);
curl_setopt($ch, CURLOPT_COOKIEFILE, COOKIEJAR);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);

curl_setopt($ch, CURLOPT_URL,
  'https://accounts.google.com/ServiceLogin?hl=en&continue=https://market.android.com/mylibrary');
$data = curl_exec($ch);

$formFields = getFormFields($data);

$formFields['Email']  = $USERNAME;
$formFields['Passwd'] = $PASSWORD;
unset($formFields['PersistentCookie']);

// var_dump($formFields);

$post_string = '';
foreach($formFields as $key => $value) {
    $post_string .= $key . '=' . urlencode($value) . '&';
}

$post_string = substr($post_string, 0, -1);

curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/ServiceLoginAuth');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);

$result = curl_exec($ch);
//var_dump($result);

if (preg_match('/^2\d{2}/', curl_getinfo($ch, CURLINFO_HTTP_CODE)) == false) {
    die("Login failed");
    var_dump(curl_getinfo($ch), $result);
} else {
    curl_setopt($ch, CURLOPT_URL, 'https://market.android.com/mylibrary');
    curl_setopt($ch, CURLOPT_POST, 0);
    curl_setopt($ch, CURLOPT_HTTPGET, true);

    $result = curl_exec($ch);
    echo $result;
}

function getFormFields($data)
{
    if (preg_match('/(<form id=.?gaia_loginform.*?<\/form>)/is', $data, $matches)) {
        $inputs = getInputs($matches[1]);

        return $inputs;
    } else {
        die('didnt find login form');
    }
}

function getInputs($form)
{
    $inputs = array();

    $elements = preg_match_all('/(<input[^>]+>)/is', $form, $matches);

    if ($elements > 0) {
        for($i = 0; $i < $elements; $i++) {
            $el = preg_replace('/\s{2,}/', ' ', $matches[1][$i]);

            if (preg_match('/name=(?:["\'])?([^"\'\s]*)/i', $el, $name)) {
                $name  = $name[1];
                $value = '';

                if (preg_match('/value=(?:["\'])?([^"\'\s]*)/i', $el, $value)) {
                    $value = $value[1];
                }

                $inputs[$name] = $value;
            }
        }
    }

    return $inputs;
}


text:
Q: Maxima keyboard input from batch If I copy and paste in wxMaxima these lines
assume(omega>0);
damp_vib:'diff(x,t,2)+2*'xi*'omega*'diff(x,t)+'omega^2*x=0;
ode2(damp_vib,x,t);
negative;

the last line correctly answers to Maxima asking if a parameter is negative, zero, or positive (the solution depends on that).
But if I put the same lines in a text file and run it using the batch command, the last line is not taken as answer and I have to enter it manually from keyboard. How can this be avoided?

A: I don't know a way to get Maxima to read the 'asksign' response from the file. I think the best way to resolve this problem is to put assume(xi^2 < 1) (or whatever it should be) before the function call which triggers 'asksign'.


text:
Q: Groupby Percentage from total I am trying to group by the region and finding the percentage of product1 , product2, and product3 from the total product.
Here is the code
a = df_2018.groupby(['ISIC4_ARABIC']).agg({'product1': ['sum'], 'product2': ['sum'], 'product3': ['sum']})

So in the end i will have product1 , product2, and product3 as percentage of total product and the total product as the number.
below is the image of the data frame

A: Use:
cols=['produc1','product2','product3']
a[cols]=a[cols]/a[cols].sum(axis=1)

A: IIUC:
s = a.iloc[:, 1:]
a.iloc[:, 1:] = s.div(s.sum(1), axis='rows')

Output (a):
  region  product1  product2  product3
0     CA  0.333333  0.333333  0.333333
1     MN  0.500000  0.250000  0.250000
2     OH  1.000000  0.000000  0.000000
3     NY  0.714286  0.142857  0.142857


text:
Q: What is the necessary and sufficient conditions for a quadratic equation to have one positive root? the equation $ax^2 + bx + c = 0$ has positive roots if

*

*$b^2-4ac > 0$

*$-b/a > 0$

*$c/a > 0$

I would like to know is there any necessary and sufficient conditions for it to have exactly one positive root?

A: Assuming $a,b,c$ are reals, the following conditions guarantee that out of the two real roots one is negative and one is positive:
$$b^2-4ac>0 \text{ and } c/a<0.$$
The first condition guarantees that the equation has two distinct real roots. Since the product of the roots is equal to $c/a$, and we want only one of them to be positive, the other one has to be negative, hence the second condition.
Note that if we treat the case of repeated roots as a single root (as opposed to thinking of it as two equal roots), then the answer should also include the second case:
$$b^2-4ac=0 \text{ and } b/a<0.$$
The second inequality comes from the fact that the $x$-coordinate of the vertex is $x_0=-\frac{b}{2a}$, and we want it to be a positive number.
UPDATE. After sleeping on it, in the morning I realized that I had a number of inaccuracies in my own answer:

*

*We implicitly assumed that the equation is indeed a quadratic one, i.e. that $a\neq0$, even though it wasn't stated anywhere. So to be completely rigorous, we should account for the case of $a=0$ too.

*I was wrong when I said that when one root is positive, "the other one has to be negative". The correct statement is that the other one has to be non-positive, i.e. negative or zero.

*Not a mistake, but rather a comment: for nonzero numbers, $c/a<0$ is equivalent to $ac<0$. Same for $b/a$.

*As implicitly indicated in other great answers, if $ac<0$, then $b^2-4ac>0$ automatically, so we don't have to include this condition in the first case.
Taking all of that into account, I believe the following should be a complete answer, consisting of several possible cases:

The equation $ax^2+bx+c=0$, where $a,b,c$ are reals, has exactly one positive root iff:

*

*$ac<0$ (two real roots, one positive and one negative); or

*$c=0$ and $ab<0$ (two real roots, one positive and one zero); or

*$a=0$ and $bc<0$ (linear equation whose only root is positive); or

*$b^2-4ac=0$ and $ab<0$ (repeated root which is positive; only include this case if treating it as one root rather than two equal roots).

A: It depends on whether you count the special case of a double root in the positive reals. This happens iff $$b^2=4ac\land ab<0.$$
Apart from that, you have exactly one simple positive root iff the sign at $x=0$ differs from the sign as $x\to\pm\infty$, i.e., $$ac<0.$$

A: The roots are $\frac {-b \pm \sqrt{b^2 - 4ac}}{2a}$.  If $b^2 - 4ac=0$ then there is a single double root which is positive if $b$ and $a$ are negative signs.
Otherwise to have one positive root there must be second negative root (or zero depending on how you feel about zero).  So $- b + \sqrt{b^2 - 4ac}$ and $-b - \sqrt{b^2 - 4ac}$ must be different signs.
That means $\sqrt{b^2 - 4ac} > |b|$ ($\ge$ if you accept a zero root as non-positive).  But if $4ac$ is positive and $b^2 - 4ac \ge 0$ then $\sqrt{b^2 - 4ac} < \sqrt{b^2} = |b|$.  But if $4ac$ is negative then $\sqrt{b^2 - 4ac} > \sqrt {b^2} = |b|$.
So if $a$ and  $c$ are opposite signs (and there are any roots at all) then one root will be positive and one negative.

A: The roots of quadratic equation, $$ax^2+bx+c=0$$ are
$$x=\frac {-b\pm \sqrt {b^2-4ac}}{2a}$$
If you multiply the roots of a quadratic equation you get $ \frac {c}{a}$
Thus in order for a negative root, all you need is  $$ \frac {c}{a} <0 $$


text:
Q: Algorithm to generate possible combinations of players from all players of team Let's say I have 3 postions [goalkeeper, midfilder, striker] and 6 players
[{"name":A, "position":goalkeeper, "salary":300, "rating" : 9},
{"name": B, "position":goalkeeper, "salary":200, "rating" : 8 },
{"name": C, "position":midfilder, "salary":400 , "rating" : 9},
{"name": D, "position":midfilder, "salary":300 , "rating" : 7},
{"name": E, "position":striker, "salary":400, "rating" : 9 },
{"name": F, "position":striker, "salary":200 ,"rating" : 7}]

Now I need to build all possible combinations of teams with all 3 positions from 6 player with maximum ratings and within my total budget salary of 1100.
Output should be like this
[{ "team" : [A,C,E],
    "total_salary" : 1100,
    "total_rating" : 27
  },
 { "team" : [B,C,E],
    "total_salary" : 1000,
    "total_rating" : 26
  },
  { "team" : [A,D,E],
    "total_salary" : 1000,
    "total_rating" : 25
  }.. all possible combinations. Players will be choosed based on position. there can't be 2 players with same position.]

I found bit of solution here : combinations of players for a team in C
But it seems in C but seems not feasible and I need it in JAVASCRIPT.


text:
Q: xampp php laravel routing with character . not working I use an old laravel lumen 5.8 and tried to make a route like :
http://localhost:8001/url/api/v1

and its working fine, but when I want to make route like
http://localhost:8001/url/api/v1.0

its return some error, i think this is on xampp / apache / php  level
because when we input the wrong endpoint with env debug=true, laravel will return error as normally laravel error page. But this route return error like

A: as mentioned here This is a limitation on PHP's built-in server, not with Lumen
It works fine on a real web server, and then I use xampp as my local web server and access the route like this :
http://localhost/project-folder/public/url/api/v1.0


text:
Q: C# counter to count up to a target number I'm trying to find out if anyone knows about an already existing c# plugin that will count up to a target number at a specified speed.
I'd like to be able to specify:

*

*The start number

*The end number

*The amount of time it should take to get from start to end.

*A custom callback function that can execute when a counter is
finished.

I found these plugins one for javascript and one for asp.net:

https://inorganik.github.io/countUp.js/
https://www.nuget.org/packages/Wisej-2-CountUp/

I am making an application with asp.net core and blazor, I need something that fits blazor since it is a new technology and there is not much information on how to implement javascript plugins

if they had any example of how to implement countup.js in asp.net core
they would help me a lot

A: You can create a timer service that can serve you on many occasions:
Create the service class:
public class BlazorTimer
    {
        private Timer _timer;

        internal void SetTimer(double interval)
        {
            _timer = new Timer(interval);
            _timer.Elapsed += NotifyTimerElapsed;
            _timer.Enabled = true;
            _timer.Start();
        }

        private void NotifyTimerElapsed(object sender, ElapsedEventArgs e)
        {
            OnElapsed?.Invoke();
        }

        public event Action OnElapsed;
    }

Add the service to the DI container, in the Program.Main method, as transient:
builder.Services.AddTransient(config =>
        {
            var blazorTimer = new BlazorTimer();
            blazorTimer.SetTimer(1000);
            return blazorTimer;
        });

Usage
@page "/"

@implements IDisposable
@inject BlazorTimer Timer

@count.ToString()

@code{
private int count = 0;

protected override void OnInitialized()
{
    Timer.OnElapsed += NotifyTimerElapsed;

    base.OnInitialized();
}

private void NotifyTimerElapsed()
{
    // Note: WebAssembly Apps are currently supporting a single thread, which
    // is why you don't have to call
    // the StateHasChanged method from within the InvokeAsync method. But it
    // is a good practice to do so in consideration of future changes, such as
    // ability to run WebAssembly Apps in more than one thread.
    InvokeAsync(() => { count++; StateHasChanged(); });
}

public void Dispose()
{
    Timer.OnElapsed -= NotifyTimerElapsed;
}

}


text:
Q: PHP Excel: Saving created PDF to remote server and not user downlaod This is similar to my previous question re (DOMPDF), the difference is that now i am using PHPExcel, to create the PDF.
I have tried the file_put method but it downloads an empty PDF. SO where am i going wrong or can this not be done?
below is my end code that outputs the fiel and what i have tried
  header('Content-Type: application/pdf');
  header('Content-Disposition: attachment;filename="TestSheet.pdf"');
  header('Cache-Control: max-age=0');

  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
  $objWriter->save('php://output');

  $file_location = $save_Path;
  file_put_contents($file_location,$objWriter);
  exit;

It seems that once its been saved its clearing the data so hence the blank PDF
Thanks

A: Discard the headers.... they're all about telling the web browser to expect a PDF file, but you're not sending anything back to the browser (let alone a PDF file).
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
$objWriter->save('php://output');

is telling PHPExcel to send the generated PDF directly to the web browser.... you say you don't want to do that, but to save to a remote server instead.
You'll need to intercept the results from $objWriter->save() so it doesn't go to the browser. Capture it using output buffering:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
ob_start();
$objWriter->save('php://output');
$myPdfData = ob_get_contents();
ob_end_clean();

Then you've captured the PDF datastream in $myPdfData and can then do:
file_put_contents($file_location, $myPdfData);

Note that this is likely to be memory-hungry


text:
Q: How to assign annotation value from application.properties in Spring Boot? I have an entity/model with discriminator formula and now I'm assigning a discriminator formula like the following sample,
@Entity
@DiscriminatorFormula("type")
class Student {
    // code
}

In the same case, how can I assign discriminator value from application.properties in Spring Boot?

A: The expression in the class level annotation should be a constant, i.e., final and static. What you are trying to achieve is not possible. The best you can do is read it from a constant file rather than application.properties.


text:
Q: RealmResults Query Returns Partial Results - Android I am having a very strange behavior while querying data from my Realm table.
Example
I have an object called OrderItem defined like this:
public class OrderItem extends RealmObject{

   @PrimaryKey
   @Index
   private long id;

   //the rest of the fields here
   //then getters and setters as usual
}

The issue is quite unpredictable; because sometimes:
RealmResults<OrderItem> items = realm.where(OrderItem.class)
       .equalTo("order_id", order_id)
       .findAllSorted("id");

returns incomplete results - especially by 1 row;
This has been driving me nuts because I cannot exactly find out how it returns such partial results; doesn't matter how many rows I have in the said table!
NOTE
A while back, I was using a String type as the primary key in my table until I learned how bad an idea that was when trying to increment values; so I switched to long type which is fine; except now I get partial results from the query above!
I will truly appreciate your help on this! Any ideas, tips that could help me mitigate this issue.
Thanks in advance!
Eenvincible!

A: Have you cleared the database after switching primary key type?
You can do this with:
Realm.deleteRealm();

I had some similar troubles with Realm database. Deleting and creating new database helped.


text:
Q: react-native - createBottomTabNavigator initial render height problem I use bottom-tab-navigator https://reactnavigation.org/docs/bottom-tab-navigator in my app, I took example from official web site here: Try this example on Snack but on starting app it has strange height visual effect, which you can see here:
https://www.youtube.com/watch?v=gxKUlkP0eJ4
I tried to set bottom tab height to 50, it's bit better, but there is still icons jump down effect (it's visible if you set height to 150)
<Tab.Navigator
      initialRouteName="Feed"
      screenOptions={{
        tabBarActiveTintColor: '#e91e63',
        tabBarStyle:[
          {
            height:50
          }
        ]
      }}

How to fix that strange visual effect? Appreciate any help.


text:
Q: Rails issue with paperclip I installed the gem paperclip and set it up. I put this piece of code in one of my controllers
@pictures = Picture.near([latitude, longitude], 6.8) #im also using geocoder
@picturethumbs = @pictures
@picturethumbs.each do |thumb|
      thumb.photo = thumb.photo(:thumb)
 end
when i do this in my view
<% @picturethumbs.each do |picture| %>

    <p> <%= link_to image_tag(picture.photo), picture_path(picture) %>

</p><% end %>

i get regular sized images.
If i dont resize in my controller, but i do picture.photo(:thumb) in the view i get the right thumbs. Could you help me resize the image independently of modifying it in the view. Maybe another model which corresponds to pictures but contains automatically thumbs (not resizing in view)

A: Can you please post more details on how your Model is set up, which uses paperclip?
You will need this in your model :
class User < ActiveRecord::Base
  # ...
  has_attached_file :picture, :styles => { :small => "150x150>" }

end

and then in your view:
<%= image_tag @user.picture.url(:small) %>

Check this RailsCast:

*

*http://railscasts.com/episodes/134-paperclip

*http://asciicasts.com/episodes/134-paperclip


text:
Q: How to set a value for each row without showing the value in java I have a string array and that is what is shown on the listView; however, I want each of those rows to be assigned an int array so when it is clicked, it will subtract from the users "total_pts" and then be displayed on the totalPoints textview IF they have enough points to begin with
here is the TextView and total point variable:
int total_pts =0;
TextView totalPoints = (TextView)findViewById(R.id.totalP);

here is the ListView:
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, redeem);

//assign to listview
list.setAdapter(adapter);

//click listener
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {

        //ListView Clicked item index
        int itemPosition     = position;

        int[] points = new int[]{120,150,200,200,300,400,600};

        if (total_pts >= points){
            //where I am stuck...the conditional statement won't work because I
            //am unsure how to say the points(value) at a certain index
            //(the index clicked) and then subtract them and then display them
            total_pts-=points;
            totalPoints.text = "Total Points: \(Total_Points)"

        }
    }
});

A: You can use the position to fetch the value from points array
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
        // move it outside oncreate
        // no need to recreate this array everytime on click
        int[] points = new int[]{120,150,200,200,300,400,600};

        if(total_pts>=points[position]){
            total_pts-=points[position];
            totalPoints.setText("Total Points "+String.valueOf(total_pts));
         }//else{ // optional
            //totalPoints.setText("Not enough points");
         //}
    }
});


text:
Q: Is it possible to skip parallax effect preparation to load page faster? I try to optimize this page: https://tikex-dev.com Using codrop template: http://themes.framework-y.com/codrop/music/
It applies a special parallax effect https://pixelcog.github.io/parallax.js/
When loading the page I can see a black splash screen first, but also when I measure with Google Page Speed there is a significant slowness loading a the page.
How can I speed up loading?
One thing I noticed I see a rendered extra
 under :

Div has screen specific infos like width and height of the screen. Is the rendering of div makes the black splash, and so slows down loading?
I do not have that div in my page when rendering with Next.js. There is nothing between body and navbar rendered by server.
const Layout = ({ children, isNavbarTransparent }: Props) => {
    return (
        <>
            <Navbar transparent={isNavbarTransparent} />
            {children}

How can be faster loading?


text:
Q: launching skype on desktop keeps asking for admin user rights then reinstalls every time I use Skype in a networked institution. Anytime I try to open Skype, there is a popup to enter network administrator credentials before I can launch. After entering these credentials and moving on, the app then reinstalls all over again. It reinstalls every time one tries to launch it. The account is not wiped though. This usually happens with the new versions (Skype 8 and above). The older versions also give a "skype cannot connect" error. Only a user with admin privileges can run Skype without having to enter credentials.
Can I please have some help with this issue? All of us have this issue.


text:
Q: "Activity has been destroyed" error on Fragment testing with Robolectric I'm trying to make Fragment testing on Android with Robolectric and I know there's been some other posts about problems with FragmentActivity when it hasn't been stored in some variable.
However, I was trying to make this post work and you can see in this case the FragmentActivity object reference is kept so there shouldn't be a problem with that. Here is the base class:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

import org.junit.After;
import org.robolectric.Robolectric;
import org.robolectric.util.ActivityController;

public class FragmentTestCase<T extends Fragment> {

private static final String FRAGMENT_TAG = "fragment";

private ActivityController controller;
private FragmentActivity activity;
private T fragment;

public void startFragment(T fragment) {
    this.fragment = fragment;
    controller = Robolectric.buildActivity(FragmentActivity.class);
    activity = (FragmentActivity) controller.create().start().visible().get();
    activity.getSupportFragmentManager()
            .beginTransaction()
            .add(fragment, FRAGMENT_TAG).commit();
}

@After
public void destroyFragment() {
    if (fragment != null) {
        activity.getSupportFragmentManager()
                .beginTransaction()
                .remove(fragment)
                .commit();

        fragment = null;
    }
}

public void pauseAndResumeFragment() {
    controller.pause().resume();
}

public T recreateFragment() {
    activity.recreate();
    fragment = (T) activity.getSupportFragmentManager()
            .findFragmentByTag(FRAGMENT_TAG);

    return fragment;
 }
}

And here is the implementation of the test:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import static org.assertj.core.api.Assertions.*;

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants=BuildConfig.class, sdk=21)
public class MainActivityFragmentTest extends FragmentTestCase<MainActivityFragment> {

private MainActivityFragment fragment;

@Before
public void setUp() throws Exception {
    fragment = new MainActivityFragment();
}

@Test
public void createsAndDestroysFragment() throws Exception {
    startFragment(fragment);
    assertThat(fragment).isNotNull();
}

@Test
public void pausesAndResumesFragment() throws Exception {
    startFragment(fragment);
    pauseAndResumeFragment();
    assertThat(fragment).isNotNull();
}

@Test
public void recreatesFragment() throws Exception {
    startFragment(fragment);
    fragment = recreateFragment();
    assertThat(fragment).isNotNull();
  }
 }

Once I run the test this is the error that I get:
java.lang.IllegalStateException: Activity has been destroyed
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1399)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:637)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:616)
at com.feyserflabs.musync.FragmentTestCase.destroyFragment(FragmentTestCase.java:36)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:33)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:245)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:185)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:149)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

It seems that at some point the Activity is destroyed before entering the destroyFragment method, but I can't find where o why. Any help would be much appreciated.

A: When you call activity.recreate() you actually destroy your current activity and the reference you keep becomes invalid. You then try to use the FragmentManager of a destroyed activity and it crashes.