text:
Q: Is this proof of a topology not having a countable base correct? Let $X = \mathbb{R}$ and consider the topology $\tau = \{\emptyset\}\cup\{A\subseteq X: A^c = X-A\text{ is finite}\}$.  I want to show that $\tau$ does not have a countable base. Here is my attempt.
Let $\mathbb{B}$ be a base for $\tau$. Note that any interval $(-\infty,r)\cup (r, \infty)$ where $r$ is irrational is open. So there must be a $B\in \mathbb{B}$ such that $r\notin B$. This $B$ is 'missing' only finitely many real numbers. We can find another irrational $r'$ that is different from $r$ and all the other things $B$ is missing. Then we can find $B'\in \mathbb{B}$ such that $r'\notin B'$. Again this $B'$ is missing only finitely many numbers, so we can repeat this process again. We end up with a different element in $\mathbb{B}$ for every number in the set of irrationals minus a union of finite sets. So we have found an uncountable number of elements in $\mathbb{B}$. Is this correct?

A: Let $\mathbb B$ be a base of the cofinite topology on an uncountable set $X$.
Then for every $x\in X$ we can find some cofinite $B\in\mathbb B$ with $x\notin B$.
For this just let $y\in X$ with $y\neq x$ and choose some $B\in\mathbb B$ with $y\in B\subseteq X-\{x\}$.
This implies that the intersection of all elements of $\mathbb B$ must be empty.
However, if $\mathbb B$ is a countable collection of cofinite sets then the complement of the intersection is a countable set hence does not coincide with $X$.
This tells us directly that base $\mathbb B$ cannot be countable.

A: The idea of your proof is correct. However your proof relies on the induction for infinite objects. Your proof is inductive, that is, in each step of your proof relies on previous steps, and you have to generate uncountable collection
of open sets chosen from $\mathbb{B}$.
Here is a point the problem comes. Assume that you have chosen $B_1$, $B_2$, $\cdots$ by your construction. The proof is not ended because you need to choose more open sets. How to continue? You should mention about the limit case.
You can make your proof rigorously by introducing transfinite induction. However there is another proof that does not require the transfinite induction:
For each countable collection $\mathbb{B}$ of open sets in $\mathbb{R}$ with your topology, consider $X=\bigcup\{\mathbb{R}\setminus B : B\in\mathbb{B}\}$. $X$ is a countable union of countable sets, so $X$ is countable. Hence we can find some $r\in\mathbb{R}\setminus X$.
If $\mathbb{B}$ is really a basis, then $\mathbb{R}\setminus \{r\}$ is a union of some elements of $\mathbb{B}$. Equivalently, $\{r\}$ is an intersection of sets $X\setminus B_i$, $i=1,2,\cdots$, for some $B_i\in\mathbb{B}$. However $\bigcap_i (X\setminus B_i)\subseteq X$, whereas $r\notin X$, so $\{r\}$ can't be an intersection of sets of the form $X\setminus B_i$.

A: The easiest way is the direct proof (no iterations etc.) as follows:
Suppose that $(B_n)_{n \in \mathbb{N}}$ is a countable base of non-empty sets.
Then for each $n$ the set $F_n = \mathbb{R}\setminus B_n$ is finite.
Then $F = \cup_n F_n$ is at most countable and the reals are uncountable so pick $x \in \mathbb{R}\setminus F$.
Then $X \setminus \{x\}$ is open but no $B_n$ is a subset of it, as
$B_n \subset X \setminus \{x\}$ iff $x \in X \setminus B_n = F_n$. But $x$ is in none of the $F_n$. So we cannot write some open subset as the union of base elements, contradiction. A countable base thus does not exist.

redpajama_set_name: RedPajamaStackExchange


text:
Q: textutil convert PDF to txt producing garbled output I am trying to convert PDF files to text files using textutil.  I don't if there are special types of PDFs that can and cannot be converted.  The files I am trying to convert are in a searchable format, which I assume is a minimum requirement.  When I convert the file, the text document is completed garbled output.  Here is my code:
textutil -convert txt example.pdf

Here are some of the first lines, in case that helps to identify where I am going wrong:
%PDF-1.3
%ƒÂÚÂÎßÛ†–ƒ∆
4 0 obj
<< /Length 5 0 R /Filter /FlateDecode >>
stream
xÌõYè‹∏«flı)8>2""å,R%Ÿªõ¯fixs9ôM'<YÅ`"Ô‰W,J¢'íF3"@^2Z›<ädˇ:(ˇl>òüçuπ´Í¶ñ¶nõº.⁄⁄
4>~˘œ?Ã_ÕøÕ"W_≠˘Ù'·fl◊OL.ò´øÂKI5ÖÀª∫*≥O_ÃÀk"'aH|\1OØØù
±Ê˙'sqv0◊ˇ2oÆ√Vñ©˘÷Êmy2jæ»;P+Ú¢(*s˝ikó3>z¸ãõæ8;èè˙΄·ê—z~=|
¯D˝rËî)WÈå<˝¡ÒˇnÆfl/3¿'UnõÆ4~∫Á;Ú"µ≠J˙4‰JWùîgz8€]êªA@g¸≠kRŸ¯‹÷ùàëeÁÔπUŸÓ÷Ü´≤Œ

I'm guessing it has to do with some encoding feature -- not my area of expertise, so any assistance would be greatly appreciated!

A: With reference to TEXTUTIL(1) manual page  it seems pdf is not between formats managed by this utility:

fmt is one of:  txt, html, rtf, rtfd, doc, docx, wordml, odt, or webarchive

On Linux/Unix installing a scriptable product like XPDF/pdftotext  may be a valid solution like some comment already suggested.
For those on OS X it's possible extract text from PDF by a native OS X automator action  ( ..see this answer or last 4' of this tutorial) then consider that automator's workflow can be "scripted" via CLI automator command


text:
Q: MySQL data integrity? In various PostgreSQL vs. MySQL comparisons I've seen many mentions of problems with data integrity in MySQL. Is this currently still an issue?
Particularly for web applications using MySQL, are there tricks to making sure data integrity is maintained? Or with new versions is this true 'out of the box' with no additional configuration required?

A: MySQL has a feature to support multiple storage backends (storage engine). The most prominent ones are MyISAM and InnoDB. MyISAM is the default, in many situations quite fast but provides no data integrity. InnoDB supports full data integrity. When creating a table you can set the type.
CREATE TABLE foo (...) ENGINE=innodb;

See also http://dev.mysql.com/doc/refman/5.1/en/storage-engines.html for more details.

A: By default MySQL created myisam engine tables, which does not support transactions or foreign keys, you need to explicitly force transactional innodb engine while creating a table.
By default MySQL accepts invalid data, like date '2010-02-30', silently truncates too long textual data, too big numbers etc. But you can change it for INNODB tables using SET sql_mode = 'STRICT_TRANS_TABLES'; on mysql 5.0.2 and up - see "Constraints on Invalid Data".
MySQL does not support check constraints at all, so you can not for example:

*

*force integer data to be at some
range;

*force text data to be at some format (for example valid e-mail
address or valid url);

*limit text data to valid characters (only ASCII, only ISO-8859-1, only
numbers and minus etc.);

*disallow spaces, newlines, double-spaces, spaces at the end etc.
or empty text data.

So all data validation has to be done in client application. Which is harder to do and more error-prone.
All of this is not a problem in PostgreSQL.

A: No storage engine for MySQL supports CHECK constraints. Nuff said.
"For other storage engines, the clauses are parsed but ignored. The CHECK clause is parsed but ignored by all storage engines." "The reason for accepting but ignoring syntax clauses is for compatibility, to make it easier to port code from other SQL servers, and to run applications that create tables with references" - http://dev.mysql.com/doc/refman/5.1/en/alter-table.html No enhancements for this in MySQL 5.4 or 5.5 according to the manual.
Please note that InnoDB does support FOREIGN KEYs.


text:
Q: unexplained variations in postgresql insert performance I have a processing pipeline generates two streams of data, then joins the two streams of data to produce a third stream. Each stream of data is a timeseries over 1 year of 30 minute intervals (so 17520 rows). Both the generated streams and the joined stream are written into a single table keyed by a unique stream id and the timestamp of each point in the timeseries.
In abstract terms, the c and g series are generated by plpgsql functions which insert into the timeseries table from data stored elsewhere in the database (e.g. with a select) and then return the unique identifiers of the newly created series. The n series is generated with a join between the timeseries identified by c_id and g_id by the calculate_n() function which returns the id of the new n series.
To illustrate with some pseudo code:
-- generation transaction
begin;
c_id = select generate_c(p_c);
g_id = select generate_g(p_g);
end transaction;
-- calculation transaction
begin;
n_id = select calculate_n(c_id, g_id);
end transaction;

I observe that generate_c() and generate_g() typically run in a lot less than a second however the first time calculate_n() runs, it typically takes 1 minute.
However if I run calculate_n() a second time with exactly the same parameters as the first run, it runs in less than a second. (calculate_n() generates a completely new series each time it runs - it is not reading or re-writing any data calculated by the first execution)
If I stop the database server, restart it, then run calculate_n() on c_id and g_id calculated previously, the execution of calculate_n() also takes less than a second.
This is very confusing to me. I could understand the second run of calculate_n() is taking only a second if, somehow, the first run had warmed a cache but if that is so, then why does the third run (after a server restart) still run quickly when any such cache would have been cleared?
It appears to me that perhaps some kind of write cache, generated by the first generation transaction, is (unexpectedly) impeding the first execution of calculate_n() but once calculate_n() completes, that cache is purged so that it doesn't get in the way of subsequent executions of calculate_n() when they occur. I have had a look at the activity of the shared buffer cache via pg_buffercache but didn't see any strong evidence that this was happening although there were certainly evidence of cache activity across executions of calculate_n().
I may be completely off-base about this being the result of an interaction with a write-cache that was populated by the first transaction, but I am struggling to understand why the performance of calculate_n() is so poor immediately after the first transaction completes but not at other times, such as immediately after the first attempt or after the database server is restarted.
I am using postgres 11.6.
What explains this behaviour?
update:
So further on this. Running the vacuum analyze between the two generate steps and the calculate step did improve the performance of the calculate step, but if I found that if I repeated the steps again, I needed to run vacuum analyze in between the generate steps and the calculate step every time I executed the sequence which doesn't seem like a particularly practical thing to do (since you can't call vacuum analyze in a function or a procedure). I understand the need to run vacuum analyze at least once with a reasonable number of rows in the table. But do I really need to do it every time I insert 34000 more rows?


text:
Q: Dependency Issue, React DnD Beautiful I'm trying to install the following package, which is well known.
However, I'm a little confused as to how to diagnose this issue. I'd like to use this package as it's a core concept of my site, drag and drop.
Is this saying I need react @16.14.0? How would I go about bumping the entire project up correctly? Will this cause issues with other packages?
I am quite new to React and specifically this concept of tree dependencies? I also know my packages may be messed up, and if I need to, I'm happy to try resolve with tips.
npm i react-beautiful-dnd

However I get these errors:
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: new@0.1.0
npm ERR! Found: react@16.8.0
npm ERR! node_modules/react
npm ERR!   peer react@">=16.8.0" from @emotion/react@11.7.0
npm ERR!   node_modules/@emotion/react
npm ERR!     peer @emotion/react@"^11.0.0-rc.0" from @emotion/styled@11.6.0
npm ERR!     node_modules/@emotion/styled
npm ERR!       peerOptional @emotion/styled@"^11.3.0" from @mui/material@5.2.3
npm ERR!       node_modules/@mui/material
npm ERR!         peer @mui/material@"^5.0.0" from @mui/icons-material@5.2.4
npm ERR!         node_modules/@mui/icons-material
npm ERR!         1 more (the root project)
npm ERR!       3 more (@mui/styled-engine, @mui/system, the root project)
npm ERR!     peerOptional @emotion/react@"^11.5.0" from @mui/material@5.2.3
npm ERR!     node_modules/@mui/material
npm ERR!       peer @mui/material@"^5.0.0" from @mui/icons-material@5.2.4
npm ERR!       node_modules/@mui/icons-material
npm ERR!         @mui/icons-material@"^5.2.4" from the root project
npm ERR!       1 more (the root project)
npm ERR!     3 more (@mui/styled-engine, @mui/system, the root project)
npm ERR!   peer react@">=16.8.0" from @emotion/styled@11.6.0
npm ERR!   node_modules/@emotion/styled
npm ERR!     peerOptional @emotion/styled@"^11.3.0" from @mui/material@5.2.3
npm ERR!     node_modules/@mui/material
npm ERR!       peer @mui/material@"^5.0.0" from @mui/icons-material@5.2.4
npm ERR!       node_modules/@mui/icons-material
npm ERR!         @mui/icons-material@"^5.2.4" from the root project
npm ERR!       1 more (the root project)
npm ERR!     peerOptional @emotion/styled@"^11.3.0" from @mui/styled-engine@5.2.0
npm ERR!     node_modules/@mui/styled-engine
npm ERR!       @mui/styled-engine@"^5.2.0" from @mui/system@5.2.3
npm ERR!       node_modules/@mui/system
npm ERR!         @mui/system@"^5.2.3" from @mui/material@5.2.3
npm ERR!         node_modules/@mui/material
npm ERR!     2 more (@mui/system, the root project)
npm ERR!   22 more (@material-ui/core, @material-ui/icons, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! react-beautiful-dnd@"*" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: react@16.14.0
npm ERR! node_modules/react
npm ERR!   peer react@"^16.8.5 || ^17.0.0" from react-beautiful-dnd@13.1.0
npm ERR!   node_modules/react-beautiful-dnd
npm ERR!     react-beautiful-dnd@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

It's worth noting my package.json looks:
{
  "name": "new",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.7.0",
    "@emotion/styled": "^11.6.0",
    "@fontsource/roboto": "^4.5.1",
    "@material-ui/icons": "^4.11.2",
    "@mui/icons-material": "^5.2.4",
    "@mui/material": "^5.2.3",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "framer-motion": "^4.1.17",
    "gsap": "^3.9.1",
    "material-ui-search-bar": "^1.0.0",
    "react": "^16.8.0",
    "react-dom": "^16.8.0",
    "react-draggable": "^4.4.4",
    "react-intersection-observer": "^8.33.1",
    "react-scripts": "4.0.3",
    "react-typewriter-effect": "^1.1.0",
    "styled-components": "^5.3.3",
    "typewriter-effect": "^2.18.2",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Is this saying I need react @16.14.0? How would I go about bumping the entire project up correctly? Will this cause issues with other packages?

A: Maybe your problem could be solved by removing the node_modules folder and running npm -g install npm, like this tutorial suggest: Unable to install react-beautiful-dnd package


text:
Q: Referencing EJB Local home from a POJO class of a separate web application I am trying to port 2 EJB modules in my application from EJB2.1 to EJB3.0. I am using the Eclipse Kepler IDE and regenerated the session beans using an EJB3.0 configuration. I am not using an ejb-jar.xml because in EJB 3.0 that is supposed to be redundant. I have instead used annotations for marking my bean as Stateless and specifying the Local and Local Home Interfaces. I have still kept the Local Home interface since I wanted the basic structure of my project to be similar to what it was in EJB2.1. I have also done away with the xml bindings for the EJB while migrating.
We are using a WAS 7 application server for deployment and while the EJB is getting successfully deployed without errors, I am getting a naming Exception while looking up my Local Home interface from a separate POJO class of a different web application it is required in. I basically want to call the create() method of the Local Home interface after referencing the EJB Local Home. Adding code samples below:
Session Bean:
@Stateless
@Local(AccessLDAPSessionLocal.class)
@LocalHome(AccessLDAPSessionLocalHome.class)
public class AccessLDAPSessionBean implements AccessLDAPSessionLocal {
//Business Logic
}

Local Interface:
public interface AccessLDAPSessionLocal {
//business Interface
}

Local Home Interface:
public interface AccessLDAPSessionLocalHome extends EJBLocalHome {

public AccessLDAPSessionLocal create() throws CreateException;

}

Pojo class referencing the Local Home interface:
public static AccessLDAPSessionLocal getAccessLDAPSessionBean() throws NamingException, CreateException {
    if (accessLDAPSessionBean == null) {
    InitialContext context = new InitialContext();
    Object obj = context.lookup("java:global/AccessLDAP/AccessLDAPSessionBean!com.ibm.asset.hrportal.core.ejb.ldap.AccessLDAPSessionLocalHome");
        accessLDAPSessionBean = ((AccessLDAPSessionLocalHome) obj).create();
    }
    return accessLDAPSessionBean;
}

Also my Local and Local Home interfaces are inside my EJB client which I use as a jar file, while my Session Bean is inside the actual EJB which is used as an EAR.
Following is the error I am getting:
NamingException::javax.naming.NameNotFoundException: Name global not found in context "java:".

Am I missing some configuration resulting in the failure of JNDI lookup? Any help would be gratefully appreciated. Thanks in advance.

A: WebSphere Application Server 7.0 is only an implementation of EJB 3.0, but the java:global namespace wasn't added until EJB 3.1, which wasn't implemented in WebSphere Application Server until 8.0.  As with all EJB 3.0 implementations, you will need to lookup a vendor-specific binding name.  You can find the WebSphere Application Server binding name by looking at the CNTR0167I messages in SystemOut.log.  See the EJB 3.0 application bindings overview topic in the Knowledge Center if you would like to customize this binding name.
Regardless, it is not a best practice to directly lookup EJBs by their binding name.  Instead, you should use an EJB reference.  In EJB 3.0, that means using an annotation like this in an EE managed object (such as a servlet or another EJB):
@EJB
private AccessLDAPSessionLocalHome home;

In this case, the EJB container is required to find a target EJB within the same application that contains the EJB reference, so you do not need to explicitly configure a target binding name for the EJB reference.
If you need to access the EJB reference from a utility class rather than an EE managed class, then declare the EJB reference with a name on a managed class (such as a servlet or another EJB), and look it up from the utility class:
@EJB(name = "ejb/accessHome", beanInterface = AccessLDAPSessionLocalHome.class)
public class MyServlet { ... }

public class MyUtility {
    ...
    InitialContext context = new InitialContext();
    Object obj = context.lookup("java:comp/env/ejb/accessHome");
    ...
}

You can configure multiple such EJB references on the same managed EE class using the @EJBs annotation:
@EJBs({
    @EJB(name = "ejb/accessHome", beanInterface = AccessLDAPSessionLocalHome.class),
    @EJB(name = "ejb/other" beanInterface = Other.class)
})
public class MyServlet { ... }

If your EJB is packaged in a separate EAR, then note that this is not a portable configuration.  See the "Local client views" section of the EJB modules topic in the Knowledge Center.  Additionally, you will need to explicitly configure a binding name for the EJB reference.

A: I think the way you are looking up the ejb is not correct. The JNDI name would be something like "java:comp/env/". ejb-ref-name would be part of your web.xml
Also, you will need to give providerURL and factoryName to the context object before doing the lookup.


text:
Q: grouping messages and processing bunch of messages at once with kafka I have a Kafka cluster with multiple brokers. In my application, I need to group messages based on an Identifier(unique) and I need to put all the messages with the same ID into a separate location(topic or partition). My first question is how can we achieve this in Kafka. I am familiar with producing with a key in Kafka, but it just guarantees to put all the relative events in one place, But I need to make sure that the topic or partition only has messages with the same ID(nothing else inside that topic or partition).
My other question is how can we make the consumers subscribe to a specific topic, but run for example every 10 minutes (not as soon as one msg arrives) and process all the messages in that topic(or a specific partition)? By processing all the messages I mean literally on all the messages not one by one.


text:
Q: Assign image position using javascript variables I wish to change the position of my image depending on its size, so when its wider (as I will keep them the same height) it will stay central because its less left. Here is my code
    img1 = document.getElementById("type-pic1");
    width1 = img1.clientWidth;
    left1 = (300 - width1) / 2;

my div is 300 pixels wide. This is what I want my CSS to look like
    #type-pic1
    {
    position: absolute;
    left: var left 1;
    }

I don't mind doing this all in the javascript file, I hope this makes sense and someone can help, thanks in advance.

A: Something like this should do the trick:
img1.style.left = left1+"px";


text:
Q: subprocess without hang parent process I have python function and I am running that process in maya. I want to run that function as a another process so maya will be still responsive and I can continue working on maya.
from multiprocessing import Process
def test_func(node):
   # I have some crazy functions in here
   pass

def run_test():
   p = Process(target=test_func, args=(items,))
   p.daemon = True
   p.start()

This is a test function only . I want to just show what I was trying to do. Any idea what is the smart way to start a process without disturbing maya ?
Thanks a lot

A: This may not be obvious to everyone, since you sort of glazed over a key issue pretty quickly... But you are trying to use multiprocessing within a session of Autodesk Maya. That, to my knowledge, doesn't work.
For the high-level reasons, which I am sure others can give more detail on, multiprocessing.Process wants to fork the Maya process and continue running. That means it needs to copy the entire maya image (which could be over 1GB of memory if you are doing a lot of stuff in your scene), and continue running. Anything you do via the Maya API would be in a completely different process, in a different scene graph. Also you are very likely to deadlock, as all of the various synchronization primitive states from the main process are now copied as-is to the new space.
You are better off sticking with a threading solution in Maya, or shelling out to an external process. Even with threading though, you have some limited ability to interact with the Maya API, and they provide utils for executing calls into the main thread and even waiting on their results.
Again, anyone else with more low-level knowledge of process forking and deadlocking, please feel free to expand this answer.

A: I haven't done any python multi threading, only c++, but unless Process implicitly uses multi threading, it won't run at the same time. Look up documentation for the threading module which is part of the standard library.


text:
Q: Why does Worksheet.Copy not return a reference to the new workbook created I have some code where wb is an existing multi-worksheet workbook. If I copy one of the sheets "Overview" a new workbook is created - so why does the following error saying "object required"?:
Dim wbCopy As Excel.Workbook
Set wbCopy = wb.Sheets("Overview").Copy

A: The Worksheet.Copy method doesn't return a reference to the new Workbook. You might use a Worksheet reference instead:
Dim wsCopy As Excel.Worksheet    'changed from wb to wsCopy

As you know, if you don't supply either the After or Before argument it copies to a new Workbook. Copying within the same workbook would use this code:
Set wsCopy = wb.Worksheets("Overview")
wsCopy.Copy After:= wb.Worksheets(1)    'or Before:=

If you want to copy the sheet to a new workbook, and retain a reference to it, then this needs to be done in stages:
Dim wbNew As Excel.Workbook
Dim wsCopied As Excel.Worksheet

Set wbNew = Workbooks.Add
wsCopy.Copy before:=wbNew.Worksheets(1)
Set wsCopied = wbNew.Worksheets(1)

If you only need to keep a reference to the new workbook then just omit the last line (and the variable declaration for wsCopied).

A: This is one of the few occasions you have to use one of the Active* objects
wb.Sheets("Overview").Copy
Set wbCopy = ActiveWorkbook

A: The worksheets copy method appears to return a boolean value rather than a workbook object. To set a reference to the workbook you can use the following.
Sub wbcopy()

Dim wbcopy As Excel.Workbook
Dim wbIndex As Excel.Workbook
Dim sArray() As String
Dim iIndex As Integer
Dim bfound As Boolean
Dim wb As Workbook

Set wb = ThisWorkbook

ReDim sArray(Workbooks.Count)

'Find the names of all the current workbooks
For Each wbIndex In Workbooks
    sArray(iIndex) = wbIndex.FullName
Next wbIndex

'Copy the sheet to a new workbook
wb.Sheets("Overview").Copy

'Find the sheet with the new name
For Each wbIndex In Workbooks

    bfound = False

    For iIndex = LBound(sArray) To UBound(sArray)
        If wbIndex.FullName = sArray(iIndex) Then
            bfound = True
            Exit For
        End If
    Next iIndex

    If Not bfound Then
        Set wbcopy = wbIndex
        Exit For
    End If

Next wbIndex

End Sub

A: I ran into the same thing today. To me the active* objects is too vague so I looked for a way to reliably determine the sheet object.
Just if anyone's looking for this, here's for the files:
dim sws, tws as worksheet

set sws = thisworkbook.sheets("source")
sws.copy before:=sws
set tws = sws.previous

That does the job
rn43x


text:
Q: What's the greatest range of orders of magnitude? There's a famous claim along the lines of "40 dp of PI are sufficient to calculate the circumference of the Observable Universe to the width of a hydrogen atom"
I don't know the accuracy and detail of claim, but it prompted me to be curious ...
I assume that the claim (if it were true and accurately remembered) if equivalent to stating: "There are 40 orders of (decimal) magnitude difference between the diameter of the universe and the diamater of a hydrogen atom".
But that's not the biggest possible difference between interestingly measurable things, because the diameter of a hydrogen atom isn't the smallest length ... we could go smaller (protons, electrons, quarks, planck length)
I don't know astrophysics well enough to know whether there's anything that's interesting to describe bigger than the Observable Universe.
But, it seems that whilst considering length you can arrive at "The greatest possible difference in orders of magnitude".
But there are other things that can be measured. Time for example.
So question:
What metric has the greatest range of orders of magnitude that are interesting to talk about? and how big is that range?

A: Resistivity has a quite impressive range--for example, the resistivity of teflon is about $10^{30}$ times higher than the resistivity of copper.
So I think "resistivity of different materials" might be the winner, or at least a contender, for most orders of magnitude ratio of quantities that can and often do come up naturally in everyday life.

A: Your question is pretty vague, but I will restrict it to mean: what is the physical property with the largest range of measured values. This is still probably subjective, but it's a little more manageable and fun to think about anyway.
Here's one possibility: range of measured half-lives of radioactive isotopes (see wiki list). The shortest measured half-life (that of hydrogen-7) is order $10^{-23}$ seconds, and the longest (that of tellurium-128) is order $10^{31}$ seconds, so they span an amazing 54 orders of magnitude in all.
This is kind of ridiculous. It is more than the ratio between the size of a proton and the size of the observable universe, which are separated by a mere 41 orders of magnitude (maybe this is what your quote is supposed to say?), and it is about the difference between the Planck length and a light-year (!). It's fun to think about what the experimental challenges must be making measurements on both ends of that spectrum. Both ends (particularly the long-time end) are bounded by experimental ability, so this is not too far from being a list of the range of times over which we can measure anything. Naturally, that means it is subject to change. For example, we've been looking for proton decay for a long time, but all we can say right now is that the lifetime must be more than order $10^{39}$ seconds. If we ever find it this range will shoot at least another hundred million times larger.

A: Measured bulk baryonic densities vary by around 45 orders of magnitude - from around $10^{18}$ kg/m$^3$ in neutron stars to $4\times 10^{-28}$ kg/m$^3$ for the universe as a whole.

A: Observed energy of a single particle is interesting, because energy (and particles) are fundamental.
At one extreme, the IceCube observatory has claimed detection of neutrinos with energies of 0.001eV. I'm not sure if an energy difference counts, but the Mossbauer effect means that the change of energy arising from doppler-shifting gamma-photons from a radioactive source moving at a few centimeters per second is detectable: that's an energy difference of under $10^{-5}$ eV.
At the other extreme there are "OMG" cosmic rays with energies in excess of $10^{20}$ eV. We can't be absolutely certain that these are single protons. A mechanism for generating such particles is hard to envisage (and it has to be located in our immediate galactic proximity!). It's possible that it's spitting out atomic nuclei rather than protons, in which case we should maybe deduct a couple of orders of magnitude for safety.
Anyway, that's at least 23 orders of magnitude, maybe a few more.
We can of course detect electromagnetic radiation with frequencies of a few Hz and maybe lower, and one must assume that this corresponds to photons of femto-eV. However, we couldn't detect a single such photon, only the effect of large correlated numbers thereof.

A: Temperature achieved in man-made experiments ranges from half a nanoKelvin to five TeraKelvin (quark-gluon plasmas), or across 22 orders of magnitude.
The temperature at the start of the universe was a lot higher, but because the universe was opaque in its early days, any attempt to "measure" that temperature must be a theoretical derivation from other observations. Possibly, of the order of the  Planck temperature $1.4\times 10^{32} K$, above which it is unclear whether "temperature" has any meaning.
But there are various ways of defining temperature, and under some definitions it is possible to create systems in which "temperature" reaches infinity, goes negative, and starts approaching zero from the other direction! Negative thermodynamic temperatures are measures of population inversions, as found in every lasing medium. Yes, this is perhaps cheating, from the perspective of this question.


text:
Q: global COLOR opacity hover overlay? I'm using the below for a global link opacity overlay.
a:hover {
    text-decoration: none;  opacity: 0.6; /* css standard */
    filter: alpha(opacity=60); /* internet explorer */
} /* mouse over link */

How can I add color to this? Is this possible with CSS or am I looking at a JS / jQuery solution only?

A: a:hover{
    /* your stuff here */
    color:#f00;                // older browsers
    color: rgba(255,0,0,0.4);  // browsers with rgba support (r,g,b,alphaOpacity)
}

A: If you want the colour e.g. black to be on the background then your code will be
a:hover {text-decoration: none;  opacity: 0.6; /* css standard */
filter: alpha(opacity=60); /* internet explorer */ /* mouse over link */ background: #000; }

and if you want the a tag to have a colour of eg black then your css will look like this
a:hover {text-decoration: none;  opacity: 0.6; /* css standard */
filter: alpha(opacity=60); /* internet explorer */  /* mouse over link */ color: #000; }

for some reason you have an extra } in your code.

A: It seems you dont need opacity at all. The effect you are searching for is a tranparent background. Use rgba() with a rgb() fallback and define a transparent background instead.
a:hover {
    text-decoration: none;
    background: rgb(255,0,0) /* fallback */
    background: rgba(255,0,0,0.6) /* red with 60% opactiy */
    color: #000;
}


text:
Q: How to call OpenCSV library CSVReader(Reader in, char x) in Groovy? I have having trouble calling OpenCSV library CSVReader(Reader in, char x) in Groovy?  The problem is that Groovy thinks of single-quoted literals as a String rather than a character and the constructor requires a character.
Therefore, this doesn't work:
reader = new CSVReader( new FileReader( tFile ), ',' )

I tried this and it didn't work either:
reader = new CSVReader( new FileReader( tFile ), String.toCharacter(",").charValue() )

A: That is a feature of Groovy, you need to cast the literal to char like this:
reader = new CSVReader(new FileReader(tFile), (char) ',')

or like this:
reader = new CSVReader(new FileReader(tFile), ',' as char)

You can even use double quotes. See this issue ticket


text:
Q: Django rest_framework oAuth2 APIView error I am making a Django application API, where an authorized user can post a messages, and other users can browse the message and like/dislike/comment on the messages (twitter style).
I have implemented oAuth2 already and tested it.
The API works fine from the admin panel, but when I access it through url, it is giving error:
enter image description here
My models.py class is:
class Posts(models.Model):

    def expirationTimeCalculation(self):
        EXPIRATION_DURATION = 86400 #time in seconds
        expirationTime = self.creationTimestamp + timedelta(seconds = EXPIRATION_DURATION)
        return expirationTime

    def postLiveStatus(self):
        return (self.expirationTimestamp > timezone.now)

    def postLiveTimeRemaining(self):
        if (self.expirationTimestamp > timezone.now):
            return (self.expirationTimestamp - timezone.now).total_seconds()
        else:
            return 0

    postIdentifier = models.IntegerField()
    title = models.CharField(max_length=100)
    message = models.TextField()
    topic = models.ManyToManyField('Topics')
    creationTimestamp = models.DateTimeField(default=timezone.now)
    expirationTimestamp = property(expirationTimeCalculation)
    post_owner = models.ForeignKey(AppUser, related_name='post_owner', on_delete=models.CASCADE)
    isLive = property(postLiveStatus)
    post_likes = models.ForeignKey('Likes', related_name="post_likes", on_delete=models.CASCADE)
    post_dislikes = models.ForeignKey('Dislikes', related_name="post_dislikes", on_delete=models.CASCADE)
    post_comments = models.ForeignKey('Comments', related_name="post_comments", on_delete=models.CASCADE)

    def __str__(self):
        return self.title

class Topics(models.Model):
    TOPICS = [('P','Politics'),('H','Health'),('S','Sports'),('T','Tech')]
    topicName = models.CharField(max_length=2, choices=TOPICS, blank=False)

class Likes(models.Model):
    isLiked = models.BooleanField(null=True)
    likes_owner = models.ForeignKey(AppUser, related_name='likes_owner', on_delete=models.CASCADE)
    post = models.ForeignKey(Posts, related_name='likes', on_delete = models.CASCADE)

class Dislikes(models.Model):
    isDisliked = models.BooleanField(null=True)
    dislikes_owner = models.ForeignKey(AppUser, related_name='dislikes_owner', on_delete=models.CASCADE)
    post = models.ForeignKey(Posts, related_name='dislikes', on_delete = models.CASCADE)

class Comments(models.Model):
    comment = models.TextField(null=True)
    comments_owner = models.ForeignKey(AppUser, related_name='comments_owner', on_delete=models.CASCADE)
    post = models.ForeignKey(Posts, related_name='comments', on_delete = models.CASCADE)

The serializer class is:
class CommentsSerializer(serializers.ModelSerializer):
    comments_owner = CreateUserSerializer()
    class Meta:
        model = Comments

        fields = ('comment', 'comments_owner')

class DislikesSerializer(serializers.ModelSerializer):
    dislikes_owner = CreateUserSerializer()
    class Meta:
        model = Dislikes
        fields = ('isDisliked', 'dislikes_owner')

class LikesSerializer(serializers.ModelSerializer):
    likes_owner = CreateUserSerializer()
    class Meta:
        model = Likes
        fields = ('isLiked', 'likes_owner')

class TopicsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Topics
        fields = ('topicName')

class PostsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Posts
        fields = ('postIdentifier', 'title', 'message', 'topic', 'creationTimestamp', 'expirationTimestamp', 'isLive', 'post_owner', 'post_likes', 'post_dislikes', 'post_comments')

Views class is:
from rest_framework.generics import ListAPIView
from .models import Posts
from .serializers import PostsSerializer

class PostsView(ListAPIView):
    queryset = Posts.objects.all()
    serilaizer_class = PostsSerializer

And the main URLS class is:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
import posts_backend.views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')), #Adding oAuth2 privider URLS to the url path
    path('authentication/', include('accounts.urls')), #Creating authentication endpoints http://10.61.64.150:8000/authentication/ for performing authentication
    path('v1/posts/', posts_backend.views.PostsView.as_view(),), # Version 1 of the API

]

Can anyone kindly let me know why I am getting this error and how to resolve this?

A: try renaming the attribute from serilaizer_class  to serializer_class


text:
Q: What's the type of custom Fields containing calls to widgetFile? If giving fancyTextField an explicit type will fix this problem, which type do I give it? It expects something in the form of Field m Text, but I'm not sure what m to substitute with.
Here's the error message:
Couldn't match type `HandlerSite m0' with `App'
The type variable `m0' is ambiguous
Possible cause: the monomorphism restriction applied to the following:
  fancyTextField :: Field m0 Text
    (bound at Widget/Input/Text.hs:13:1)
Probable fix: give these definition(s) an explicit type signature
Expected type: [Text]
               -> [FileInfo]
               -> m0 (Either (SomeMessage (HandlerSite m0)) (Maybe Text))
  Actual type: [Text]
               -> [FileInfo] -> m0 (Either (SomeMessage App) (Maybe Text))
In the `fieldParse' field of a record
In the expression:
  Field
    {fieldParse = parseHelper $ Right, fieldView = textInput,
     fieldEnctype = UrlEncoded}
In an equation for `fancyTextField':
    fancyTextField
      = Field
          {fieldParse = parseHelper $ Right, fieldView = textInput,
           fieldEnctype = UrlEncoded}

And here's the code:
module Widget.Input.Text where

import Import

-- This is text Field calling the textInput widget below.
fancyTextField = Field {
  fieldParse = parseHelper $ Right,
  fieldView = textInput,
  fieldEnctype = UrlEncoded
}

type FieldWidget =
     Text             -- Id.
  -> Text             -- Name.
  -> [(Text, Text)]   -- Attributes.
  -> Either Text Text -- Value.
  -> Bool             -- Required?
  -> Widget

textInput :: FieldWidget
textInput i name attrs val req = do
  -- The following works:
  -- [whamlet|<div>Test!|]

  -- But the following doesn't!
  $(widgetFile "fancy")

A: I believe you want to use Handler in place of m.


text:
Q: wrong status for Reachability in appDidBecomeActive I'm using Reachability class, which Apple provided and faced one strange thing.
App checks connection every time app did become active, and if it's active, update some data.
When i turn on airplane mode and just after that relaunch the app, so didBecomeActive will be called, reachability returns wrong status(reachableViaWiFi). And if you repeat this one more time, correct status is returned.
Also i've noticed, that if you turn airplane mode, wait for a several seconds and then relaunch the app, reachability returns correct status.
Is there any explanation for such behaviour?

A: You need to more strict when you check for connectivity. Add more condition while you receive reachability change notification.
Check below conditions:
- (void)reachabilityDidChange:(NSNotification *)notification {

    // Reachbility for internet
    Reachability *reachability = (Reachability *)[notification object];
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];

    switch (internetStatus) {
        case NotReachable:
        {
            NSLog(@"The internet is down.");
            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"The internet is working via WIFI.");
            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN.");
            break;
        }
    }

    // Reachbility for host
    Reachability *hostReachability = [Reachability reachabilityWithHostName:@"www.apple.com"];

    NetworkStatus hostStatus = [hostReachability currentReachabilityStatus];
    switch (hostStatus) {
        case NotReachable:
        {
            NSLog(@"A gateway to the host server is down.");
            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"A gateway to the host server is working via WIFI.");
            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"A gateway to the host server is working via WWAN.");
            break;
        }
    }
}


text:
Q: SilverLight Auto-Size Help? I'm new to using SilverLight and I added a grid to the screen, and both sizes are selected to auto, but for some reason it doesn't fill up the screen. I'm using Visual Studio 2010, Silverlight 3.0
I did the exact same thing with two grids earlier and it works perfect
Here's the code:
<Grid Height="75" HorizontalAlignment="Left" Name="grid2" VerticalAlignment="Top" Background="White">
    <Image Height="74" HorizontalAlignment="Left" Name="image1" Stretch="None" VerticalAlignment="Top" Source="test.jpg" />
</Grid>

A: Setting HorizontalAlignment and VerticalAlignment properties to Stretch and Width, Height to Auto should do the trick.

A: Is it just me, you've set the height explicitly in your grid and your image?
I'm no expert, but from my experience if you don't put anything for width it normally fills the parent.
I also notice there are no Row or column definitions, nor are there any Grid.Row, grid.Column dependency properties, is that just something in they way you copied the code?


text:
Q: How to display a PDF from ResponseEntity in controller method and display to JSP using jquery ajax? I have a pdf stored in my local and from my controller method i am trying to return it in the form of ResponseEntity
If i display directly the response from controller it works fine but my requirement it to embedd the pdf on a section of jsp on IE which is not working.
Below is the code:
Controller:
    @RequestMapping(value="/cde")
    public ResponseEntity<byte[]> getPDF() {
        // json => emp
       System.out.println("here");
        byte[] contents=null;
        // generate the file
        try{

        Path path = Paths.get("C:\\abc.pdf");

         contents = Files.readAllBytes(path);
         System.out.println("CONTENTS"+contents);

        }
        catch(Exception e){
            e.printStackTrace();
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/pdf"));
        String filename = "output.pdf";
        headers.setContentDispositionFormData(filename, filename);
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
        return response;

}

JSP:
Fetch pdf

The code is working on FIREFOX but not on IE


text:
Q: Show & Hide Dynamic content OK so I've got an inbox style layout, with multiple messages with dynamic content for each message, I want to click on a link (Action Needed) and once its click it will open a drop down div containing an iFrame. This is the Javascript I am using:

And that display this:

The images for design view are here... Before:

After:

But when there are more than one of these in the inbox the second wont open, is there a simple css show and hide for parent and child that will not share the same attributes that i can use, or any advice on where to go with this.
Thank you

A: AS far as Dynamic HTML is concerned, you can't handle it without using Javascript or JQuery.
Secondly the Javascript you have written is using getElementById which only allows single element( Which has the same id specifed. ) selection.

Since you want to have same code to work with multiple Inbox, you need to have container and child selector that will help you to give same effect. you need to use selector other than id which allows multiple selection.

Let me know if I am getting wrong.It would be more better if you can put code in JS fiddel.
Enjoy coding ;)


text:
Q: Custom component not rendering properly anymore I'm new to creating custom components on android and it was a fun, annoying, and very educational experience. I was able to make my quite complex custom component and I'm very happy with it. But after I moved it to a directory and out of it, it doesn't display anything anymore.
My project consist of a lot of fragments and my custom component is used on one of them. So when I moved all those fragments in a directory, AS told me that someone can't find something on my custom component class. So I included the custom component class inside the fragments directory. Everything worked fine but when I tried to use the custom view on a different layout which is not a fragment's, the custom component doesn't display anything. I made every variable of the custom view class to public then moved it outside the fragments folder. Now, it doesn't display anything anymore. Please point out what I've done wrong.
This is custom component class.
public class CheckOutItem extends ConstraintLayout {
    public Context ctx;
    public Paint mPaint;
    public Rect mRect;
    int mSquareColor;
    public ImageView imgThumbnail;
    public TextView lblAbbrev, lblFullName;
    public ConstraintLayout lytMain;

    public CheckOutItem(Context context) {
        super(context);
        ctx = context;
        init(null);
    }

    public CheckOutItem(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.checkout_item, this);
        ctx = context;

        init(attrs);
    }

    public CheckOutItem(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        ctx = context;
        init(attrs);
    }

    private void init(@Nullable AttributeSet set){
        inflate(ctx, R.layout.checkout_item, this);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mRect = new Rect();

        if(set == null){
            return;
        }

        TypedArray ta = getContext().obtainStyledAttributes(set, R.styleable.CheckOutItem);

        this.imgThumbnail = findViewById(R.id.imgItemThumbnail);
        this.lblAbbrev = findViewById(R.id.lblItemAbbrevName);
        this.lblFullName = findViewById(R.id.lblItemFullName);
        this.lytMain = findViewById(R.id.lytMain);

        this.lblAbbrev.setText(ta.getText(R.styleable.CheckOutItem_abbrevText));
        this.lblAbbrev.setTextSize(ta.getDimension(R.styleable.CheckOutItem_abbrevTextSize, 1f));
        this.lblAbbrev.setTextColor(ta.getColor(R.styleable.CheckOutItem_abbrevTextColor, Color.BLACK));

        this.lblFullName.setText(ta.getText(R.styleable.CheckOutItem_fullNameText));
        this.lblFullName.setTextSize(ta.getDimension(R.styleable.CheckOutItem_fullNameTextSize, 1f));
        this.lblFullName.setTextColor(ta.getColor(R.styleable.CheckOutItem_fullNameTextColor, Color.BLACK));
        this.lblFullName.setBackgroundColor(ta.getColor(R.styleable.CheckOutItem_fullNameBackgroundColor, Color.WHITE));

        this.lytMain.setBackgroundColor(ta.getColor(R.styleable.CheckOutItem_mainBackgroundColor, Color.LTGRAY));

        ta.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mRect.left = 0;
        mRect.right = getWidth();
        mRect.top = 0;
        mRect.bottom = getHeight();

        canvas.drawRect(mRect, mPaint);
    }
}

This is my layout.
<?xml version="1.0" encoding="utf-8"?>
<merge 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.support.constraint.ConstraintLayout
        android:id="@+id/lytMain"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/border_bg">

        <ImageView
            android:id="@+id/imgItemThumbnail"
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:layout_marginEnd="8dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:srcCompat="@tools:sample/avatars[9]"
            tools:visibility="gone" />

        <TextView
            android:id="@+id/lblItemAbbrevName"
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:gravity="center"
            android:textSize="16sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/lblItemFullName"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginStart="1dp"
            android:layout_marginEnd="1dp"
            android:gravity="center"
            android:textAlignment="center"
            android:textSize="12sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="1.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/lblItemAbbrevName"
            app:layout_constraintVertical_bias="0.0" />

    </android.support.constraint.ConstraintLayout>

</merge>

This is my attrs.xml.
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CheckOutItem">
        <attr name="thumbnail" format="string"/>
        <attr name="abbrevText" format="string"/>
        <attr name="abbrevTextSize" format="dimension"/>
        <attr name="abbrevTextColor" format="color|reference"/>
        <attr name="fullNameText" format="string"/>
        <attr name="fullNameTextSize" format="dimension"/>
        <attr name="fullNameTextColor" format="color|reference"/>
        <attr name="textStyle">
            <enum name="normal" value="0"/>
            <enum name="bold" value="1"/>
            <enum name="italic" value="2"/>
        </attr>
        <attr name="fullNameBackgroundColor" format="color|reference"/>
        <attr name="mainBackgroundColor" format="color|reference"/>
    </declare-styleable>
</resources>

This is how I use it.
<com.example.android.projectname.CheckOutItem
        android:id="@+id/coi2"
        android:layout_width="102dp"
        android:layout_height="102dp"
        android:layout_margin="7.8dp"
        app:abbrevText="MP"
        app:abbrevTextColor="@color/black"
        app:abbrevTextSize="12sp"
        app:fullNameBackgroundColor="@color/colorAccent"
        app:fullNameText="Make Payment"
        app:fullNameTextColor="@color/white"
        app:fullNameTextSize="8sp"
        app:mainBackgroundColor="@color/transparent"
        app:thumbnail="" />

A: You are inflating your layout twice
public CheckOutItem(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    LayoutInflater.from(context).inflate(R.layout.checkout_item, this);
    ...

Remove the second inflate in init
private void init(@Nullable AttributeSet set){
    // inflate(ctx, R.layout.checkout_item, this); // remove this line
    ...


text:
Q: php: flush data and end client connection I have a php-script (in a normal LAMP environment) that runs a couple of housekeeping-tasks at the end of script.
I use flush() to push all the data to the client, which works fine (the page is fully loaded), but the browser still waits for data (indicated by the "loading"-animation) which is confusing for the user but of course clear because Apache cannot know whether PHP will generate more output after flush() - in my case it never does, however.
Is there a way to tell the client that the output is finished and the http-connection should be closed immediately even though the script keeps running?

A: It sounds like you have a long running script performing varioous tasks. Especially it appears to script goes on doing things after it has sent the reply to the client. This is a design that opens a whole lot of potential problems. You should re-think your architecture.
Keep house keeping tasks and client communication strictly separate. For example you could have a client request processed and trigger internal sub requests (which you can detach from) or deligate tasks to a cron like system. Then offer a second view to the client which visualized the progress and result of those tasks. This approach is much safer, more flexible and easier to extend when required. And your problem at hand is solved, too :-)

A: you can use this function fastcgi_finish_request() special function to finish request and flush all data while continuing to do something time-consuming (video converting, stats processing etc.); http://php.net/manual/en/install.fpm.php but you need to install FPM  for it like
<?php
 echo "You can see this from the browser immediately.<br>";
 fastcgi_finish_request();
 sleep(10);
 echo "You can't see this form the browser.";
?>


text:
Q: 'using' before a variable inside a namespace I understand usingdirective can be used to refer to a namespace.
Could anyone please tell what it means when it is used in front of a variable G4NtupleIterator or a class name G4AnalysisManager as in the following example?
namespace G4Csv
{
  using G4NtupleIterator = std::vector<tools::wcsv::ntuple*>::iterator;

  using G4AnalysisManager = G4CsvAnalysisManager;
}

A: The using directive introduces a symbol into the current scope.  If that scope includes a namespace, then it will be part of that namespace but not others, including the global namespace.
In your example you could refer to G4Csv::G4NtupleIterator or G4Csv::G4AnalysisManager.


text:
Q: Can you run a juptyer notebook file from another python file? I currently have a data link and a jupyter notebook file. I am trying to write a python script that grabs the data from the link, and then prompts it to run the jupyter notebook.
So the question is are you able to run a jupyter notebook (.ipynb) file from inside a python (.py) file?


text:
Q: How do I reference functions in other files with leiningen? I'm still fairly new to Clojure so I apologize if this is a completely newbie question but I wasn't able to find a sufficient answer online.
Basically, my problem is that any time I try to run my project, I get an error like:
Exception in thread "main" java.lang.RuntimeException: java.io.FileNotFoundException: Could not locate greeter__init.class or greeter.clj on classpath:

In this case, greeter.clj is in the project in the same directory as the file containing my main function.
For illustration purposes, I've created a project that has a directory tree like this:

My code for core.clj is as follows:
(ns omg.core
(require [greeter]))

(defn -main[] (greet))

My code for greeter.clj is:
(ns greeter)

(defn greet [] println("Hello world"))

Whenever I type lein run -m omg.core I get the exception mentioned above. What am I doing wrong?

A: the greeter namespace it at the wrong level
(ns omg.greeter)

The names in namespace correspond to the folders in the path so to use the file in
/src/omg/greeter.clj that file should contain the omg.greeter namespace. if you want to have it just called greeter then move it down one folder
When using require you need to spell out the namespace of the function you are calling, in this case that would be (omg.greeter/greet). since this is a pain, the use function requires a namespace and adds all it's functions to the current namespace. Another option that is more selective is to use require with a :refer option in the namespace definition
(ns omg.core
    (require [omg.greeter :refer :all]))

or
(ns omg.core
    (require [omg.greeter :refer [greet]]))

Most people put the namespace requirements into the ns call at the top of the file.
a quick read of http://clojure.org/namespaces will hopefully help


text:
Q: How are the values printed in the foreach statement? I am very very new to perl programming.
While reading about the loops, for the foreach loop I got two examples.
The one example is,
foreach ('hickory','dickory','doc') {
   print $_;
   print "\n";
}

Output:-
hickory
dickory
doc

The $_ variable contains the each item. So, it prints.
In another example, they said did not specified the $_ variable in print statement. The empty print statement only there. How it prints the foreach arguments.
foreach ('hickory','dickory','doc') {
   print;
   print "\n";
}

Output:-
hickory
dickory
doc

For this also the same output. How it prints the values. In that book they did not given any explanation for that. I was searched in internet. But I am not able to find anything.

A: Your question about print in foreach being answered, here is a little more on $_.
From General Variables in perlvar

Here are the places where Perl will assume $_ even if you don't use it:

*

*The following functions use $_ as a default argument:

*

*abs, alarm, chomp, chop, chr, chroot, cos, defined, eval, evalbytes, exp, fc, glob, hex, int, lc, lcfirst, length, log, lstat, mkdir, oct, ord, pos, print, printf, quotemeta, readlink, readpipe, ref, require, reverse (in scalar context only), rmdir, say, sin, split (for its second argument), sqrt, stat, study, uc, ucfirst, unlink, unpack.

*All file tests (-f , -d ) except for -t , which defaults to STDIN. See -X

*The pattern matching operations m//, s/// and tr/// (aka y///) when used without an =~ operator.

*The default iterator variable in a foreach loop if no other variable is supplied.

*The implicit iterator variable in the grep() and map() functions.

*The implicit variable of given().

*The default place to put the next value or input record when a <FH>, readline, readdir or each operation's result is tested by itself as the sole criterion of a while test. Outside a while test, this will not happen.

*$_ is by default a global variable.

As you can see, it is available nearly everywhere and it is indeed used a lot. Note that the perlvar page describes a whole lot more of similar variables, many of them good to know about.
Here is an example.  Consider that we read lines from a file, want to discard the ones which have only spaces or start with # (comments), and for others want to split them by spaces into words.
open my $fh, '<', $file  or die "Can't open $file: $!";

while (<$fh>)
{
    next if not /\S/;
    next if /^\s*#/;

    my @words = split;

    # do something with @words ...
}

Let's see how many uses of $_ are in the above example.  Here is an equivalent program
while (my $line = <$fh>)
{
    next if not $line =~ m/\S/;    # if not matching any non-space character
    next if $line =~ m/^\s*#/;     # if matching # after only (possible) spaces

    my @words = split ' ', $line;  # split $line by ' ' (any white space)

    # do something with @words ...
}

Compare these two

*

*the filehandle read <$fh> in the while condition assigns to $_, then available in the loop.

*regular expression's match operator by default works on $_. The m itself can be dropped.

*split by default splits $_.  We also use the other default, for the pattern to split the string by, which is ' ' (any amount of any white space).

*once we do $line = <$fh> the deal with $_ is off (it is undefined in the loop) and we have to use $line everywhere.  So either do this or do while (<$fh>) and use $_.
To illustrate all this a bit further, let us find the longest capitalized word on each line
use List::Util 'max';

my $longest_cap = max map { length } grep { /^[A-Z]/ } @words;

The grep takes the list in @words and applies the block to each element. Each element is assigned to $_ and is thus available to the code inside the block as $_. This is what the regex uses by default. The ones that satisfy the condition are  passed to map, which also iterates assigning them to $_, what is of course the default for length. Finally max from List::Util picks the largest one.
Note that $_ is never actually written and no temporary variable is needed.
Here is some of the relevant documentation.  The I/O Operators in perlop discusses while (<$fh>) and all manner of related things. The regex part is in Regexp Quote-Like Operators in perlop and in perlretut. Also have a look at split.

Defaults are used regularly and to read code written by others you must understand them.  When you write your own code though you can choose whether to use $_ or not, as one can always introduce a lexical variable instead of it.
So, when to use $_ as default (which need not be written) and when not to?
Correct use of defaults, $_ in particular, can lead to clearer and more readable code. What generally means better code. But it is quite possible to push this too far and end up with obscure, tricky, and brittle code. So good taste is required.
Another case is when some parts of the code benefit from having $_ for their defaults while at other places you then have to use $_ explicitly. I'd say that if $_ is seen more than once or twice in a section of code it means that there should be a properly named variable instead.
Overall, if in doubt simply name everything.

A: If you are not declaring any variable in your foreach loop it sets by default $_
From perldoc about foreach:

The foreach keyword is actually a synonym for the for keyword, so you
  can use either. If VAR is omitted, $_ is set to each value.

So it explains the first loop.
The second loop, as you already know now that $_ is set with each element from your array, will works because you are omitting the $var.
You could use foreach loop with explicit variable like this:
foreach my $item ( @list )
{

 print "My item is: $item\n";

}

Or you can omit like you did and  print  will still work as @Dada said because:

If FILEHANDLE is omitted, prints to the last selected (see select)
  output handle. If LIST is omitted, prints $_ to the currently selected
  output handle.

A: I will explain why you getting same results with the different syntax:
If you omit the control variable from the beginning of the foreach
loop, Perl uses its favorite default variable, $_ . This is (mostly) just like any other scalar variable, except for its unusual name. For example:
foreach ('hickory','dickory','doc') {
  print $_;
  print "\n";
}

Output :
hickory
dickory
doc

Although this isn't Perl's only default by a long shot, it's Perl's most common default. You'll see many other cases in which Perl will automatically use $_ when you don't tell it to use some other variable or value, thereby saving the programmer from the heavy labor of having to think up and type a new variable name. So as not to keep you in suspense, one of those cases is
print , which will print $_ if given no other argument:
foreach ('hickory','dickory','doc') {
  print; # prints $_ by default
  print "\n";
}

Output :-
hickory
dickory
doc


text:
Q: Replacing URLs with link using a for loop I've been searching around for this but all I could find was broken scripts and plus, I might have a method that is quite simple.
I'm trying to use a for () loop for this one.
This is what I've got:
<?php
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

$makerepstring = "Here is a link: http://youtube.com and another: http://google.com";

 if(preg_match_all($reg_exUrl, $makerepstring, $url)) {

     // make the url into link
     for($i=0; $i < count(array_keys($url[0])); $i++){
   $makerepstring = preg_replace($reg_exUrl, ''.$url[0][$i].' ', $makerepstring);
     }

 }

 echo $makerepstring;
?>

However this fails brutally for some reason I can't comprehend.
The output from echo $makerepstring; as follows(from source code):
<a href="http://google.com " target="_blank" rel="nofollow">http://google.com   <a href="http://google.com " target="_blank" rel="nofollow">http://google.com

I'd really like to do it with a for()... Could somebody try and figure out how to get this to work with me?
Thanks in advance!
/J
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

$makerepstring = "http://youtube.com http://google.com";

$url = array();

$instances = preg_match_all($reg_exUrl, $makerepstring, $url);

if ($instances > 0) {

    // make the url into link
    for($i=0; $i < count(array_keys($url[0])); $i++){
        $makerepstring = preg_replace($reg_exUrl, ''.$url[0][$i].' ', $makerepstring);
        /*echo $url[0][$i]."
";
        echo $i."
";
        print_r($url);
        echo "
";*/
    }

}

echo $makerepstring;

This does not work either, although I'm not quite sure how you meant I should do this.
EDIT:
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

$makeurl = "http://google.com http://youtube.com";

if(preg_match($reg_exUrl, $makeurl, $url)) {

       echo preg_replace($reg_exUrl, ''.$url[0].' ', $makeurl);

} else {
echo $makeurl;
}

Would give:
http://google.com http://google.com

A: that's not how preg_match_all works. http://php.net/manual/en/function.preg-match-all.php shows you that the matches go in a passed-along array, and the function returns the number of matches, instead. So first call
...
$matches = array();
$instances = preg_match_all(..., $matches);
if ($instances > 0) {
  // and then your code
}
...

And then iterate over the $matches array, which now has content.

A: You are performing the match twice:

*

*in preg_match_all function

*then you are matching again in preg_replace, which should not happen here

Use string concatation instead:
$makerepstring = "Here is a link: http://youtube.com and another: http://google.com";

$new_str = '';

 if(preg_match_all($reg_exUrl, $makerepstring, $url)) {

     var_dump($url[0]);

     // make the url into link
     for($i=0; $i < count(array_keys($url[0])); $i++){
         $new_str .= ''.$url[0][$i].' ';
     }

 }

 echo $new_str;


text:
Q: What is a rigorous, mathematical way to obtain the shortest confidence interval given a confidence level? After reading the great answer for this question by @Ben, I am a bit confused by the part " set the relative tail sizes as a control variable, and then you find the formula for the length of the confidence interval conditional on that variable". I understand this means you need to compute the length of the confidence interval as a function of the relative tail sizes and then minimize the function. However, what exactly is relative tail sizes? Is it the ratio between the areas of the two tails?
Also, is there another way to find shortest CI for a given confidence level?
For those who are interested, I know there are somewhat relevant results allowing us to compute sample size such that the length of a CI, say 95% CI, does not exceed a certain bound.

A: Shortest confidence interval is an ambiguous term
There is no such thing as the shortest confidence interval.
This is because the confidence interval is a function of the data $X$. And while you can make the confidence interval shorter for some particular observation, this comes at the cost of increasing the size of intervals for other possible observations.
Only when you define some way to apply some weighted average over all the observations, then you could possibly (but I believe not certainly or at least not easily) construct some confidence interval with the 'shortest' length.

Conditioning on observation versus conditioning on the parameter: Contrast with credible intervals, where shortest interval makes more sense.
This contrasts with credible intervals. Confidence intervals relate to the probability that the parameter is inside the interval conditional on the parameter. Credible intervals relate to the probability that the parameter is inside the interval conditional on the observation.
For credible intervals you can construct a shortest interval for each observation individually (by choosing the interval that encloses the highest density of the posterior). Changing the interval for one observation does not influence the intervals for other observations.
For confidence intervals you could make the intervals smallest in a sense that these intervals relate to hypothesis tests. Then you can make the shortest decision boundaries/intervals (which are functions of the parameters, the hypotheses).

Some related questions

*

*In this question...
The basic logic of constructing a confidence interval
..the topic was to get a 'shortest interval'  but there is no unambiguous solution when 'shortest' is not unambiguously defined.
That same question also clarifies something about the 'relative tail sizes'. What we can control are the tails of the distribution of the observation conditional on the parameter. Often this coincides with the confidence interval*, and we can think of the confidence interval as distribution around the point estimate of the parameter.
However, this symmetry may not need to be, as we can see in the case like the following: let's consider the observation/sample $\hat{\theta}$ from a distribution parameterized by $\theta$ following $${\hat\theta \sim \mathcal{N}(\mu=\theta, \sigma^2=1+\theta^2/3)}$$ You see this in the image below (for details see the particular question). In that image the red and green lines depict the confidence interval boundaries as a function of the observed $\hat{\theta}$. But you can consider them also as a function of $\theta$, and it is actually in that view how the boundaries are determined (see the projected conditional pdf's and how the boundaries enclose symmetrically the highest $\alpha\%$ of those pdf's but do not provide a symmetric confidence interval, and some boundaries may even become infinite).

*In this question...
Are there any examples where Bayesian credible intervals are obviously inferior to frequentist confidence intervals
... you see a comparison between credible intervals and confidence interval.

For a given observation, credible intervals, when they are the highest density posterior interval, are (often) shorter than confidence intervals. This is because confidence intervals do not need to coincide with the highest density interval conditional on the observation. On the other hand, note that in the vertical direction (for a given true parameter) the boundaries of the confidence interval are enclosing a shortest interval.

**(often this coincides with the confidence interval) We see an example in this question...
Differences between a frequentist and a Bayesian density prediction
where we see a sketch for an (prediction) interval based on a t-distribution. There is a certain duality to the construction of the interval:

We can construct a frequentist prediction interval with the interpretation that

*

*No matter what the value of $\mu$ and $\sigma$ is, the value $X_{n+1}$ will be $x\%$ of the time inside the prediction interval.

but also:

*

*Given a hypothetical predicted value $\tilde{X}_{n+1}$ in the prediction range, the observations $\bar{X}$ and $s$ (the sample mean and sample deviation) will be occuring within some range that occurs $x$ percent of the time. (That means we will only include those values in the prediction range for which we make our observations $x\%$ of the time, such that we will never fail more than $x\%$ of the time)

So instead of considering the distribution of $X_{n+1}$ given the data $\bar{X}$ and $s$, we consider the other way around, we consider the distribution of the data $\bar{X}$ and $s$ given $X_{n+1}$.

In the image we see the interval boundaries around the observed mean (in the example, which is about prediction interval instead of confidence interval, observed additional point $X_{n+1}$). But the boundaries should actually be considered the other way around. It is the hypothetical observation that is inside the boundaries of a hypothesis test related to each of the parameters inside the confidence interval (in the example it is a prediction interval).

A: The shortest possible confidence interval for any particular parameter is the empty interval with length 0.
A confidence interval isn't just an interval. It's a procedure for constructing an interval from a sample. So, your procedure can be "For this particular sample, I'll take the empty interval, and then for every other sample (from this repeatable experiment which I am definitely doing) I'll randomly take either the empty interval with probability 0.05, or the set of all possible values of the paramater, with probability 0.95." According to the definition, this is a 95% confidence interval.
Of course, this is a silly example. But it's important to remember that properties of a confidence interval, like its length, are random variables. What you are probably looking for is the interval with the shortest expected length.

A: For the most part, people use probability-symmetric confidence intervals (CIs). For example, a 95% confidence
interval is made by cutting off probability 0.025
from each tail of the relevant distribution.
For CIs based on the symmetrical normal and Student t
distributions, the probability-symmetric interval is
the shortest.
However, notice that the usual phrase is to find "a
95% CI," not the 95% CI." This recognizes the possibility of alternatives to the probability-symmetric rule.
CI for normal mean, SD known. Suppose you have a random sample of size $n=16$ from
a normal population with unknown $\mu$ and known $\sigma=10.$ Then if $\bar X = 103.2$ the usual
(probability-symmetric) CI for $\mu$ is $\bar X \pm 1.96(\sigma/\sqrt{n})$ or $(98.30, 108.10)$ of length
$9.80.$
qz = qnorm(c(.025,.975));  qz
[1] -1.959964  1.959964
103.2 + qz*10/sqrt(16)
[1]  98.30009 108.09991
diff(103.2 + qz*10/sqrt(16))
[1] 9.79982

However, another possible 95% CI for $\mu$ is $(98.07, 107.90)$ of length $9.84.$ This interval also has 95%
'coverage probability'. This is very seldom done in
practice because (a) it takes a little extra trouble, (b) for practical purposes the result is the same, and (c)
the alternative interval is a little longer.
qz = qnorm(c(.02,.97));  qz
[1] -2.053749  1.880794
103.2 + qz*10/sqrt(16)
[1]  98.06563 107.90198
diff(103.2 + qz*10/sqrt(16))
[1] 9.836356

CI for normal SD, mean unknown. Now suppose we
hava a sample of size $n=16$ for a normal population with
unknown $\mu$ and $\sigma$ and we want a 05% CI for $\sigma.$ If $S = 10.2$ then the probability-symmetric 95% CI for $\sigma,$ based on $\frac{(n-1)S^2}{\sigma^2} \sim \mathsf{Chisq}(\nu=n-1=16),$ is of the form $\left(\sqrt{\frac{(n-1)S^2}{U}},
            \sqrt{\frac{(n-1)S^2}{L}}\right),$
where $L$ and $U$ cut probability 0.025 from the lower and upper tails, respectively, of $\mathsf{Chisq}(15).$ For our data, this computes to $(7.53,15.79)$ of length $8.25.$
qc=qchisq(c(.975,.025),15); qc
[1] 27.488393  6.262138
sqrt(15*10.2^2/qc)
[1]  7.53479 15.78645
diff(sqrt(15*10.2^2/qc))
[1] 8.251661

However, this is clearly not the shortest 95% CI based on
this chi-squared distribution. If we cut probability 0.03 from the lower tail of the distribution and probability 0.02 from its upper tail, we can get the
95% CI $(7.43, 15.49)$ of length $8.06.$
qc=qchisq(c(.98,.03),15); qc
[1] 28.259496  6.503225
sqrt(15*10.2^2/qc)
[1]  7.431279 15.491070
diff(sqrt(15*10.2^2/qc))
[1] 8.05979

Moreover, cutting probability $0.04$ from the lower tail $(0.01$ from the upper), we'd
get a CI of width $7.88.$ But a 4.5%-0.5% split gives
a slightly longer interval than that.
By trial and error (or a grid search) one could find (nearly) the
shortest possible 95% CI. In my experience, even though such intervals are shorter, this is not
usually done because (a) it is extra trouble and (b) for practical purposes, the result may be about the same.
[However, in a practical application, if we were to get too far from cutting equal probabilities from the two tails, one may wonder whether a one-sided confidence
interval (giving an upper or lower confidence bound on $\sigma)$ might be more useful.]
Addendum. A plot of lengths of 95% CIs for $\sigma$ against the probability
cut from the lower tail of $\mathsf{Chisq}(15).$ The minimum length $7.879782$ occurs when probability $0.041$ is cut from the lower tail.

lp = seq(0.001, .049, by=.001)
m = length(lp); len=numeric(m)
for(i in 1:m) {
  L = qchisq(lp[i], 15)
  U = qchisq(.95+lp[i], 15)
  lcl = sqrt(15*10.2^2/U)
  ucl = sqrt(15*10.2^2/L)
  len[i] = ucl-lcl }
plot(lp, len, type="l", lwd=2)
min(len)
[1] 7.879782
lp[len==min(len)]
[1] 0.041

A: Some theory on optimal confidence intervals
Confidence intervals are formed from pivotal quantities, which are functions of the data and parameter of interest that have a distribution that does not depend on the parameters of the problem.  Confidence "intervals" are a special case of the broader class of confidence sets, which need not be connected intervals.  However, for the purposes of simplicity, we will restrict the present answer to cases where the confidence set is a single interval (i.e., a confidence interval).
Suppose we want to form a confidence interval for the unknown parameter $\phi$ at confidence level $1-\alpha$ using the data $\mathbf{x}$.  Consider a continuous pivotal quantity $H(\mathbf{x}, \phi)$ with a distribution that has quantile function $Q_H$.  (Note that this function does not depend on the parameter $\phi$ or the data since it is a pivotal quantity.)  Using the pivotal quantity, we can choose any value $0 \leqslant \theta \leqslant \alpha$ and form a probability interval from the quantile function.  We then "invert" the inequality expression to turn this into an interval statement for the parameter of interest:
$$\begin{align}
1-\alpha
&= \mathbb{P}(Q_H(\theta) \leqslant H(\mathbf{X}, \phi) \leqslant Q_H(1-\alpha+\theta)) \\[6pt]
&= \mathbb{P}(L_\mathbf{X}(\alpha, \theta) \leqslant \phi \leqslant U_\mathbf{X}(\alpha, \theta)). \\[6pt]
\end{align}$$
Substituting the observed data $\mathbf{x}$ then gives the general form for the confidence interval:
$$\text{CI}_\phi(1-\alpha) \equiv \Big[ L_\mathbf{x}(\alpha, \theta), U_\mathbf{x}(\alpha, \theta) \Big].$$
The functions $L_\mathbf{x}$ and $U_\mathbf{x}$ are lower and upper bound functions for the interval, and they depend on the confidence level for the interval and our choice of $\theta$.  This latter parameter represents the left tail area used in the initial probability interval for the pivotal quantity, and it can be varied over the above range.  If we want to form the optimal (shortest) confidence interval at the confidence level $1-\alpha$, we need to solve the following optimisation problem:
$$\underset{0 \leqslant \theta \leqslant \alpha}{\text{Minimise}} \ \text{Length}(\theta)
\quad \quad \quad \quad \quad
\text{Length}(\theta) \equiv U_\mathbf{x}(\alpha, \theta) - L_\mathbf{x}(\alpha, \theta)$$
Generally speaking, the minimising value $\hat{\theta}$ will depend on the data $\mathbf{x}$ and the value $\alpha$ determining the confidence level.  The length of the resulting optimal (shortest) confidence interval will likewise depend on the data and the confidence level.  We will see below that in some cases the optimising point does not depend on the data values at all, but even in this case the resulting length of the optimised interval depends on the data and confidence level (just as you would expect).
In problems involving a continuous pivotal quantity, this optimisation can usually be solved using standard calculus method.  (And thankfully, for some intervals the work has already been done for you in some functions in the stat.extend package.)  Below we give some examples looking at confidence intervals for the population mean and standard deviation for normal data.  Assuming that the optimisation part leads to a minimising value for all data values, this will give you a confidence interval that is the shortest interval formed from inversion of the initial pivotal quantity.  We will also show how to compute these intervals directly from existing R functions.  It is important to note that there will be other confidence intervals formed with other methods that may be shorter for particular samples.$^\dagger$

Example 1 (CI of population mean for normal data): Suppose we observe data $X_1,...,X_n \sim \text{IID N}(\mu, \sigma^2)$ known to come from a normal distribution with unknown parameters.  In order to form a CI for the mean parameter $\mu$ we can use the well-known pivotal quantity:
$$\sqrt{n} \cdot \frac{\bar{X}_n - \mu}{S_n} \sim \text{St}(n-1).$$
Suppose we let $t_{n-1, \alpha}$ denote the critical point of the T-distribution with $n-1$ degrees-of-freedom and with upper tail $\alpha$.  Using the above pivotal quantity, and choosing any value $0 \leqslant \theta \leqslant \alpha$, we have:
$$\begin{align}
1-\alpha
&= \mathbb{P} \Bigg( -t_{n-1, \theta} \leqslant \sqrt{n} \cdot \frac{\bar{X}_n - \mu}{S_n} \leqslant t_{n-1, \alpha-\theta} \Bigg) \\[6pt]
&= \mathbb{P} \Bigg( \bar{X}_n - \frac{t_{n-1, \alpha-\theta}}{\sqrt{n}} \cdot S_n \leqslant \mu \leqslant \bar{X}_n + \frac{t_{n-1, \theta}}{\sqrt{n}} \cdot S_n \Bigg), \\[6pt]
\end{align}$$
giving the confidence interval:
$$\text{CI}_\mu(1-\alpha) = \Bigg[ \bar{x}_n - \frac{t_{n-1, \alpha-\theta}}{\sqrt{n}} \cdot s_n , \ \bar{x}_n + \frac{t_{n-1, \theta}}{\sqrt{n}} \cdot s_n \Bigg],$$
with length function:
$$\text{Length}(\theta) = ( t_{n-1, \alpha-\theta} + t_{n-1, \theta}) \cdot \frac{s_n}{\sqrt{n}}.$$
In order to minimise this function, we can observe that the critical point function is a convex function of its tail area, which means that the length function is maximised at the point where the upper tail areas in the two parts are the same.  (I leave it to the reader to perform the relevant calculus steps to demonstrate this.)  This gives the solution:
$$\alpha - \hat{\theta} = \hat{\theta}
\quad \quad \implies \quad \quad
\hat{\theta} = \frac{\alpha}{2}.$$
Thus, we can confirm that the optimal (shortest) confidence interval in this case is the symmetric confidence interval:
$$\text{CI}_\mu(1-\alpha) = \Bigg[ \bar{x}_n \pm \frac{t_{n-1, \alpha/2}}{\sqrt{n}} \cdot s_n \Bigg].$$
In this particular case, we see that the standard symmetric interval (with each tail area the same) is the optimal confidence interval.  Varying the relative tail areas away from equal areas increases the length of the interval and so it is not advisable.  This standard confidence interval can be programmed using the  CONF.mean function in the stat.extend package.
#Generate some data
set.seed(1)
n    <- 60
MEAN <- 12
SDEV <- 3
DATA <- rnorm(n, mean = MEAN, sd = SDEV)

#Compute 95% confidence interval for the mean
library(stat.extend)
CONF.mean(alpha = 0.05, x = DATA)

        Confidence Interval (CI)

95.00% CI for mean parameter for infinite population
Interval uses 60 data points from data DATA with sample variance = 6.5818
and assumed kurtosis = 3.0000

[10.6225837668173, 14.0231144933285]

Example 2 (CI of population standard deviation for normal data): Continuing the above problem, suppose we now want to form a CI for the standard deviation parameter $\sigma$.  To do this we can use the well-known pivotal quantity:
$$\sqrt{n-1} \cdot \frac{S_n}{\sigma} \sim \text{Chi}(n-1).$$
Suppose we let $\chi_{n-1, \alpha}$ denote the critical point of the  chi distribution with $n-1$ degrees-of-freedom and with upper tail $\alpha$.  Using the above pivotal quantity, and choosing any value $0 \leqslant \theta \leqslant \alpha$, we have:
$$\begin{align}
1-\alpha
&= \mathbb{P} \Bigg( \chi_{n-1, \theta} \leqslant \sqrt{n-1} \cdot \frac{S_n}{\sigma} \leqslant \chi_{n-1, 1-\alpha+\theta} \Bigg) \\[6pt]
&= \mathbb{P} \Bigg( \frac{\sqrt{n-1} \cdot S_n}{\chi_{n-1, 1-\alpha+\theta}} \leqslant \sigma \leqslant  \frac{\sqrt{n-1} \cdot S_n}{\chi_{n-1, \theta}} \Bigg), \\[6pt]
\end{align}$$
giving the confidence interval:
$$\text{CI}_{\sigma}(1-\alpha) = \Bigg[ \frac{\sqrt{n-1} \cdot s_n}{\chi_{n-1, 1-\alpha+\theta}}, \ \frac{\sqrt{n-1} \cdot s_n}{\chi_{n-1, \theta}} \Bigg],$$
with length function:
$$\text{Length}(\theta) = \Bigg( \frac{1}{\chi_{n-1, \theta}} - \frac{1}{\chi_{n-1, 1-\alpha+\theta}} \Bigg) \cdot \sqrt{n-1} \cdot s_n.$$
This function can be minimised numerically to yield the minimising value $\hat{\theta}$, which gives the optimal (shortest) confidence interval for the population standard deviation.  Unlike in the case of a confidence interval for the population mean, the optimal interval in this case does not have equal tail areas for the upper and lower tail.  This problem is examined in Tate and Klett (1959), where the authors look at the corresponding interval for the population variance.
This confidence interval can be programmed using the  CONF.var function in the stat.extend package.
#Compute 95% confidence interval for the variance
CONF.var(alpha = 0.05, x = DATA, kurt = 3)

        Confidence Interval (CI)

95.00% CI for variance parameter for infinite population
Interval uses 60 data points from data DATA with sample variance = 6.5818
and assumed kurtosis = 3.0000
Computed using nlm optimisation with 8 iterations (code = 3)

[4.50233916286611, 9.41710949707062]

$^\dagger$ To see this, suppose you have a parameter $\theta \in \Theta$ and consider the class of confidence intervals constructed as follows.  Choose some event $Y \in \mathscr{Y}$ using an exogenous random variable $Y$ with fixed probability $\mathbb{P}(Y = \mathscr{Y}) = \alpha$ and choose some point $\mathbf{x}_0$ for the observable data of interest.  Then form the interval:
$$\text{CI}(1-\alpha) = \begin{cases}
[\theta_0] & & & \text{if } \mathbf{x} = \mathbf{x}_0  \text{ or } Y \in \mathscr{Y}, \\[6pt]
\Theta & & & \text{if } \mathbf{x} \neq \mathbf{x}_0 \text{ and } Y \notin \mathscr{Y}. \\[6pt]
 \end{cases}$$
Assuming that $\mathbf{x}$ is continuous we have $\mathbb{P}(\mathbf{x} \neq \mathbf{x}_0) = 0$ and so the interval has the required coverage probability for all $\theta \in \Theta$.  If $\mathbf{x} = \mathbf{x}_0$ then this interval is composed of a single point and so has length zero.  This demonstrates that it is possible to formulate a confidence interval with length zero at an individual data outcome.


text:
Q: 2 WiFi-Nets behind a single SSID, how to connect to a specific one? My wifi router is sending at both 2,4 GHz and 5 GHz ranges.
I want to connect to a 2,4 GHz WiFi.
However my Ubu 20.04 box always connects to a 5 GHz channel under the common SSID.
I can sudo iwlist frequency and see that channels 1 to 13 work under 2,4 GHz.
I can nmcli -f ssid,bssid   dev wifi to find out the BSSID of the wifi networks available, but i cannot associate BSSID's with the 2,4 GHz channels seen above.
At the end I want to connect to a specific SSID by doing nmcli d wifi connect XX:XX:XX:XX:XX:XX
Even better would be to setup my pc to always connect to any network under 2,4 GHz.
Any idea how to achieve that?
Thx a lot!
Using ubuntu 20.04.


text:
Q: converting code to be able to use Multiprocessing I have a rather long question I hope I can get help with.
I have a code that runs a simulation by a "while true" loop and after that a "for" loop that saves data from the simulation and restart the sim after given time. This code works fine, but now Im trying to convert this into a multiprocess where I can get 4 simultaneous simulations and for loops. So I tried to put most of the code into a function and then called it but it does not seem to work. Sorry for the long code I appreciate any help!
The first working code without multiprocessing
for z in range(8):
    for q in range(100):
        time_re = time_re + 3000
        tk.after(time_re,appender)
        tk.after(time_re,restart)
    ava(avaR1)

while True:
    time_steps = range(0,iterations+1)
    B = Beta.get()
    G = Gamma.get()
    D = Diff.get()
    M = Mor.get()

    steps_x_or_y = np.random.rand(n)
    steps_x = steps_x_or_y < D/2
    steps_y = (steps_x_or_y > D/2) & (steps_x_or_y < D)
    nx = (x + np.sign(np.random.randn(n)) * steps_x) % l
    ny = (y + np.sign(np.random.randn(n)) * steps_y) % l

    for i in np.where( (S==1) & ( np.random.rand(n) < B ))[0]:     # loop over infecting agents
         S[(x==x[i]) & (y==y[i]) & (S==0)] = 1         # Susceptiples together with infecting agent becomes infected

    S[ (S==1) & (np.random.rand(n) < G) ] = 2         # Recovery

    S[ (S==1) & (np.random.rand(n) < M) ] = 3         # Death

    nrInf1 = sum(S==1)
    nrSus.append(sum(S==0))
    nrInf.append(sum(S==1))
    nrRec.append(sum(S==2))
    nrRec1 = sum(S==2)
    nrDea = sum(S == 3)
    iterations += 1

    tk.update()
    tk.title('Infected:' + str(np.sum(S==1)))
    x = nx                                              # Update x
    y = ny                                              # Update y

The second code with me trying to change it to multiprocessing
def main1(i):

    # Physical parameters of the system
    x = np.floor(np.random.rand(n)*l)          # x coordinates
    y = np.floor(np.random.rand(n)*l)          # y coordinates
    S = np.zeros(n)                  # status array, 0: Susceptiple, 1: Infected, 2: recovered
    I = np.argsort((x-l/2)**2 + (y-l/2)**2)
    S[I[1:initial_infected]] = 1              # Infect agents that are close to center
    nrRec1 = 0
    nrDea = []
    time_re = 0
    particles = []
    R = .5                           # agent plot radius
    nx = x                           # udpated x
    ny = y                           # updated y

    def restart():
        global S
        I = np.argsort((x-l/2)**2 + (y-l/2)**2)
        S = np.zeros(n)
        S[I[1:initial_infected]] = 1

    rest = Button(tk, text='Restart',command= restart)
    rest.place(relx=0.05, rely=.85, relheight= 0.12, relwidth= 0.15 )

    def ava(k,o):
        global b
        k.append(sum(o)/3)
        Beta.set(b)                                  # Parameter slider for mortality rate
        b += 0.03125
        #bSaver.append(b)

    def appender(o):
        nrDea1.append(nrDea)
        o.append(nrRec1)

    for j in range(n):     # Generate animated particles in Canvas
            particles.append( canvas.create_oval( (x[j] )*res/l,
                                                  (y[j] )*res/l,
                                                  (x[j]+2*R )*res/l,
                                                  (y[j]+2*R )*res/l,
                                                  outline=ccolor[0], fill=ccolor[0]) )

    if i == 1:
        b=0
        for z in range(3):
            for q in range(3):
                time_re = time_re + 1000
                tk.after(time_re,appender(nrSRec1))
                tk.after(time_re,restart)
            tk.after(9000,ava(avaR1,nrSRec1))

    elif i == 2:
        b=0.25
        for z in range(3):
            for q in range(3):
                time_re = time_re + 1000
                tk.after(time_re,appender(nrSRec2))
                tk.after(time_re,restart)
            tk.after(9000,ava(avaR2,nrSRec2))

    elif i == 3:
        b=.50
        for z in range(3):
            for q in range(3):
                time_re = time_re + 1000
                tk.after(time_re,appender(nrSRec3))
                tk.after(time_re,restart)
            tk.after(9000,ava(avaR3,nrSRec3))

    else:
        b=.75
        for z in range(3):
            for q in range(3):
                time_re = time_re + 1000
                tk.after(time_re,appender(nrSRec4))
                tk.after(time_re,restart)
            tk.after(9000,ava(avaR4,nrSRec4))

    while True:

            B = Beta.get()
            G = Gamma.get()
            D = Diff.get()

            steps_x_or_y = np.random.rand(n)
            steps_x = steps_x_or_y < D/2
            steps_y = (steps_x_or_y > D/2) & (steps_x_or_y < D)
            nx = (x + np.sign(np.random.randn(n)) * steps_x) % l
            ny = (y + np.sign(np.random.randn(n)) * steps_y) % l

            for i in np.where( (S==1) & ( np.random.rand(n) < B ))[0]:     # loop over infecting agents
                S[(x==x[i]) & (y==y[i]) & (S==0)] = 1         # Susceptiples together with infecting agent becomes infected

            S[ (S==1) & (np.random.rand(n) < G) ] = 2         # Recovery
            nrDea= sum(S == 3)
            nrRec1 = sum(S==2)

            tk.update()
            tk.title('Infected:' + str(np.sum(S==1)))
            x = nx                                              # Update x
            y = ny                                              # Update y

if __name__ == '__main__':
    p1=mp.Process(target=main1, args=(1,))
    p1.start()
    p2=mp.Process(target=main1, args=(2,))
    p2.start()
    p3=mp.Process(target=main1, args=(3,))
    p3.start()
    p4=mp.Process(target=main1, args=(4,))
    p4.start()
    joinedList = avaR1+avaR2+avaR3+avaR4
    print(joinedList)

Tk.mainloop(canvas)