text:
Q: Two centrals, one peripheral Is it possible for a BTLE (4.0) peripheral to remain advertising after a central has connected, and could another central then also connect simultaneously?
I can find nothing addressing this clearly, while it is clear that a central can connect to n-many peripherals at once.

A: The Bluetooth Core Specification Version 4 says this on page 200:
"The Periph- eral role is optimized for devices that support a single connection and are less complex than central devices. Devices supporting the peripheral role only require Controllers that support the Controller's slave role. The Central role supports multiple connections and is the initiator for all connections with devices in the peripheral role. Devices supporting the central role require a Controller that support the Controller's master role and generally supports more complex functions compared to the other LE GAP roles."
Which looks like a no to me, but it's not quite as specific as you might have hoped.
You can find a list of the adopted Bluetooth specifications from bluetooth.com (formerly bluetooth.org) at this link:

https://www.bluetooth.com/specifications/adopted-specifications

The quote above comes from Core Version 4.0 page 200 and is also available in the Core Version 4.2 on page 98.

A: The "Bluetooth specification Version 4.2 [Vol 3, Part C]" states the following aspects:
•   Page 231:
2.2.2.3 Peripheral Role
"Any device that accepts the establishment of an LE physical link using any of
the connection establishment procedures as defined in Section 9 is referred to
as being in the Peripheral role."
•   From section 9 at the "Limited Discoverable Mode" section at page 351:
9.2.3.2 Conditions
"While a device is in the Peripheral role the device may support the limited
discoverable mode. While a device is in the Broadcaster, Observer or Central
role the device shall not support the limited discoverable mode."
...
"While in the limited discoverable mode the device shall send advertising event
types with the advertising data including the Flags AD type as defined in [Core
Specification Supplement], Part A, Section 1.3 with all the following flags set as
described"
"The device shall remain in limited discoverable mode until a connection is
established or the Host terminates the mode."
•   From section 9 at the "General Discoverable Mode" section at page 352:
9.2.4.2 Conditions
"While a device is in the Peripheral role the device may support the general
discoverable mode. While a device is in the Broadcaster, Observer or Central
role the device shall not support the general discoverable mode."
...
"While in general discoverable mode the device shall send advertising events
with the advertising data including the Flags AD data type as defined in [Core
Specification Supplement], Part A, Section 1.3 with all the following flags set as
described"
...
"The device shall remain in general discoverable mode until a connection is
established or the Host terminates the mode."
The standard is assertive you have to stop advertising when the connection is established.


text:
Q: Resize Wry WebView from window.resizeTo I have a web application currently running in Electron and would like to move it to Wry/Tauri for opening speed.
The application uses window.resizeTo to change the window size in real time.
I have tried using the same command with Wry/Tauri, but it does not work.
Is it possible to intercept such a call and act correctly?

A: Maybe will be useful for someone other. I figured out that it is possible to use webview.evaluate_script('<js code>') to inject some code in opened page.
Thus it's possible to change the default window.resizeTo functionallity to something I need to, for example for my needs I can do:
window.resizeTo = (w, h) => window.ipc.postMessage(`resize,${w},${h}`);

On the WRY side I can use with_ipc_handler to resize the window as requested.
WebViewBuilder::new()
  .with_ipc_handler(|win, msg| {
    let (w, h) = parse_resize_msg(&msg).unwrap();
    win.set_inner_size(LogicalSize::new(w, h)).unwrap();
  })
  .build()?;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Colored blocks and towers
George got a big box from his parents. In this box are colored blocks.
He has white, black, red, blue and orange blocks. These blocks are all
exactly the same size and of he has the same amount of blocks for each
color. George will build towers of $10$ blocks high. Two towers are
equal if they have the same color on every level of the tower. How
many different towers can George build?
A. Without white blocks?
B. With exactly $6$ white blocks?
C. With two blocks of each color?

A. Is this just $4^{10}$?
B. Is this ${{10}\choose{6}} + 4^4$?
C. Is this $5!$ ?

A: For C), we choose the $2$ positions (from the $10$) that will be occupied by colour 1. Then we choose the $2$ positions, from the remaining $8$, that are occupied by colour $2$. And so on.
For B), for every way of selecting where the whites will go, there are $4^4$ ways to fill in the rest. So you need to multiply, not add.
The answer to A) is correct.


text:
Q: How can I keep an extra empty row in a SWT table? How can I keep an extra empty row in a SWT table without adding dummy value in the model? I want to show an empty row always for the purpose of painting a rectangle around the last row? Any clue?
Scenario: The table size is going to be fixed. If I have 5 items then I want the sixth row as empty where I can draw. If I have 100 rows then I want the empty row at the 101st position and the table should scroll on some event and show that painted rectangle.
Hope to see an answer soon.

A: Finally I am able to add an empty row in the table without adding a dummy value in the content provider. Here is what I did:
I extended the JFace TableViewer class and overrided the refresh(), refresh(Object element) and inputChanged(Object input, Object oldInput) method. Basically in all these three methods I first remove the empty Item if there is any  and then let the original jface method call happen and then I again add the new empty table item.
Below is the code which worked for me.
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;

/**
 * @author amitkumar
 */
public class ExtraEmptyRowTableViewer extends TableViewer {

    boolean addExtraRow = false;

    public ExtraEmptyRowTableViewer(Composite parent) {
        super(parent);
        IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
        if (workbenchWindow != null
                && workbenchWindow.getActivePage() != null
                && workbenchWindow.getActivePage().getActiveEditor() != null
                && workbenchWindow.getActivePage().getActiveEditor().getClass().getName().equals(
                        "org.eclipse.compare.internal.CompareEditor")) {
            addExtraRow = true;
        }
    }

    public ExtraEmptyRowTableViewer(Composite composite, int style) {
        super(composite, style);
        IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
        if (workbenchWindow != null
                && workbenchWindow.getActivePage() != null
                && workbenchWindow.getActivePage().getActiveEditor() != null
                && workbenchWindow.getActivePage().getActiveEditor().getClass().getName().equals(
                        "org.eclipse.compare.internal.CompareEditor")) {
            addExtraRow = true;
        }
    }

    @Override
    public void refresh(Object element) {
        if (!addExtraRow) {
            super.refresh(element);
        } else {
            removeEmptyRow();
            super.refresh(element);
        }
    }

    @Override
    protected void inputChanged(Object input, Object oldInput) {
        if (!addExtraRow) {
            super.inputChanged(input, oldInput);
        } else {
            removeEmptyRow();
            super.inputChanged(input, oldInput);
            @SuppressWarnings("unused")
            TableItem tableItem = new TableItem(getTable(), SWT.NO_BACKGROUND | SWT.NO_FOCUS);
        }

    }

    public void removeEmptyRow() {
        try {
            for (TableItem tableItem : getTable().getItems()) {
                if (tableItem == null || tableItem.getText() == null
                        || "".equals(tableItem.getText())) {
                    tableItem.dispose();
                }
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void refresh() {
        if (!addExtraRow) {
            super.refresh();
        } else {
            removeEmptyRow();
            super.refresh();
            @SuppressWarnings("unused")
            TableItem tableItem = new TableItem(getTable(), SWT.NO_BACKGROUND | SWT.NO_FOCUS);
        }
    }

}

Thanks...
Amit Kumar


text:
Q: Python folium - set ID of particular map elements As per the question in the link below:
Set map id using folium?
df = pd.read_csv("gc_geo.csv")
fgc=folium.FeatureGroup(name="Gigant",overlay=True)
fgc._name = "Gigak"
fgc._id= "1"

I am wondering about a similar option for any Folium map element.
The code I prepared above seems not to work.
The console is fine, but nothing changes, as tried in VSC (see image below).
Is there any workaround to set my folium map elements with customized icons


text:
Q: Where to locate resolv.conf file in CentOS 7 I know that "/etc/resolv.conf" is auto generated file by "/etc/resolvconf/resolv.conf.d/head" when reboot Ubuntu 14.04. It's ok
But where i can locate same "/etc/resolvconf/resolv.conf.d/head" file in CentOS 7 ?
UPDATE
Content of file /etc/resolv.conf
**# Generated by NetworkManager**
search reesu.co.in
nameserver 8.8.8.8
nameserver 8.8.4.4

But I want to see this content:
**# Generated by NetworkManager**
search domain.tld
nameserver 8.8.8.8
nameserver 8.8.4.4

OR
**# Generated by NetworkManager**
**#search reesu.co.in**
search domain.tld
nameserver 8.8.8.8
nameserver 8.8.4.4

after every reboot:

A: In CentOS, you add entries to:
/etc/sysconfig/network-scripts/ifcfg-eth0.
You can add up to two DNS entries in the ifcfg-eth* file as, for example:
DNS1=8.8.8.8
DNS2=4.4.4.4
Official source

A: Did you try /etc/resolv.conf ?
In other words, resolv.conf is either generated by NetworkManager if you have it installed or you have to configure it yourself.
I've had that problem with Redhat servers where I wanted to keep NetworkManager from overwriting my static configuration of resolv.conf so I ended up setting my configuration in resolv.conf then changing the attributes to read-only like so
chattr +i /etc/resolv.conf

NOTE: you will have to do chattr -i before being able to change the content of /etc/resolv.conf in the future.


text:
Q: Problemas De Herencia Multiple Python estoy haciendo un trabajo de una clase de un curso que estoy tomando de python, y resulta que cree 4 archivos, en los que ocupe 2 para hacer las clases padres, y en un tercer archivo hice la clase hija con el metodo que queria ejecutar, y en le ultimo archivo importe todos los modulos correctamente pero a la hora de ejecutar me dice que no se encuentra el nombre del modulo que elegi. Inserto codigo de cada archivo para que se entienda mejor. Saludos gente.
Codigo del archivo Figura Geometrica:
class FiguraGeometrica:
def __init__(self, alto,ancho):
    self.alto = alto
    self.ancho = ancho

Codigo del Archivo Color:
class Color:
def __init__(self,color):
    self.color = color

Codigo Del Archivo Cuadrado
from Heredados.FiguraGeometrica import FiguraGeometrica
from Heredados.Color import Color
class Cuadrado(FiguraGeometrica, Color):
    def __init__(self,lado,color):
        FiguraGeometrica.__init__(self, lado,lado)
        Color.__init__(self, color)

    def area(self):
        return self.alto * self.ancho

A: No hay problema con apuntar a la clase desde la raíz. Es lo mismo que yo haría.
Simplemente añade el archivo __init__.py vacío tanto en la raíz como en la carpeta Heredados. Eso permitirá a Python interpretar la estructura del código correctamente, aun en Python 3.
Chequea esta respuesta: https://stackoverflow.com/a/48804718/4710386


text:
Q: Floating action button is giving unneeded colored border The FloatingActionButton give hilarious pink border although I don't need that the other one is my original picture that I am attaching in with FloatingActionButton

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.myapplication.MainActivity">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:src="@drawable/screen_logo"/>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    >
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/view"
        android:layout_margin="5dp"/>
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:src="@drawable/search"/>
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin='5dp'
        android:src="@drawable/add"/>
</LinearLayout>

A: change colorAccent to blue in color.xml
or use app:backgroundTint


text:
Q: What does function: 0x7f452394c4b0 mean (context in body) I was messing around in lua with a random number generator(I was watching a tutorial and the guy went over it
The script I ran ( ran many scripts that got the same thing, but this is the most simple one) was this: print(math.random)
I am very new to lua ( just started today) so it is very possible I screwed something up.
Any help would be appreciated
Thanks,
GJW

A: math.random is a function in Lua's math library.
See https://www.lua.org/manual/5.4/manual.html#pdf-math.random
In order to execute the function you must call it.
math.random()

printing the function value as in print(math.random) will print a string representation of that value. 0x7f452394c4b0 is an identifier which is unique to that function value at runtime. This is helpful in debugging.


text:
Q: Importing documentCreateElement function from Webkit I am trying to import documentGetElementById function for use in Reflex FRP. I tried the import below but can't find the function (which according to hackage should be there):
GHCi, version 8.0.1: http://www.haskell.org/ghc/  :? for help
[1 of 1] Compiling Main             ( Test.hs, interpreted )
Ok, modules loaded: Main.
*Main> import Graphics.UI.Gtk.WebKit.DOM.Document
*Main Graphics.UI.Gtk.WebKit.DOM.Document> :t documentGetElementById
<interactive>:1:1: error:
   Variable not in scope: documentGetElementById

I will appreciate help with resolving this. I am running latest Reflex platform build with ghc 8.0.1 on mac where webkit works now. I see the same problem on Linux as well. So, it doesn't seem to be platform-specific.
I also did github code search on ghcjs-dom but documentGetElementById doesn't show up. So, perhaps it has been moved somewhere else?

A: documentGetElementById has been renamed to getElementById after ghcjs-dom refactoring. So, an import like below would work:
*Main> import Graphics.UI.Gtk.WebKit.DOM.Document
*Main Graphics.UI.Gtk.WebKit.DOM.Document> :t getElementById
getElementById
  :: (DocumentClass self, System.Glib.UTFString.GlibString string,
      MonadIO m) =>
     self -> string -> m (Maybe Graphics.UI.Gtk.WebKit.Types.Element)


text:
Q: json array in httr post I am trying to pass a json array in a POST request using the httr package. However I get a HTTP/1.1 400 Bad Request because of the formatting of the array. Here's how I build the request:
decos <- list(name="ais-static-journey")
decos <- jsonlite::toJSON(decos, auto_unbox = TRUE) #Have also tried decos <- toJSON(decos, pretty = TRUE)

body <- list(mmsis=mmsis, startDate= startDate,
             endDate= endDate, decorations = decos)

r <- POST(decoratedurl,body=body, encode="json",add_headers(Authorization=auth), verbose())

I also had a look at this.
The error I get is primarily because of the back slashes in the request:
"decorations":"{\"name\":\"ais-static-journey\"}"}
This needs to be "decorations":[{"name":"ais-static-journey"}]
How do I achieve this?

A: Figured out. This works:
decos <- list(list(name="ais-static-journey"))
body <- list(mmsis=mmsis, startDate= startDate,
             endDate= endDate, decorations = decos)
r <- POST(decoratedurl,body=body, encode="json",add_headers(Authorization=auth), verbose())


text:
Q: Clause WHERE in PHP mysql I just want to update my latest data inserted only.. but I'm sure I'm wrong at WHERE (at $query1 and $query2)
<?php
include "koneksi.php";
$kdj=$_POST['kdj'];
$id=$_POST['id'];
$qty = $_POST['qty'];
$kodelagi = mysql_query("Select kd_jual from nota ORDER BY id_nota DESC LIMIT 1");
$row = mysql_fetch_array($kodelagi);
$kodelagi1 = $row['kd_jual'];
if((!empty($id)) && (!empty($kdj)) && (!empty($qty)))
{
    $query = mysql_query("INSERT INTO nota (id_item,qty,kd_jual) values ('$id','$qty','$kdj');");
    $query1 = mysql_query("UPDATE nota,item SET nota.harga_item = item.harga_item WHERE nota.kd_jual = '$kodelagi1'");
    $query2 = mysql_query("UPDATE nota SET subtotal = harga_item * qty WHERE nota.kd_jual = '$kodelagi1'");
    ?><script language="Javascript">;
    document.location = 'transaksi2.php' </script><?php
}else
{
    print "<script>alert('Maaf, tidak boleh ada field yang kosong !');
    javascript:history.go(-1);</script>";
}?>

because when I run this, I just got this on my DB
| id_nota | id_item | harga_item | qty | subtotal | Kd_jual
|  57     |   11    |  0         | 23  |  0       |13-10-201323:32:20

A: You are trying to get the latest insert record before even inserting. Do Select Query after Inserting the record. Also one more point, you are getting "kd_jual" value for last inserted record. It is the datetime column. There can be multiple records with same datetime. So in certain use case this will fail & in turns updates more than one record(Not just latest inserted). Better use the ID column(id_nota)
I have tried to modify your code as below. I didn't tested it. Correct it if required.
<?php
include "koneksi.php";
$kdj=$_POST['kdj'];
$id=$_POST['id'];
$qty = $_POST['qty'];

if((!empty($id)) && (!empty($kdj)) && (!empty($qty)))
{
$query = mysql_query("INSERT INTO nota (id_item,qty,kd_jual) values ('$id','$qty','$kdj');");

$kodelagi = mysql_query("Select id_nota from nota ORDER BY id_nota DESC LIMIT 1");
$row = mysql_fetch_array($kodelagi);
$max_id_nota= $row['id_nota'];

$query1 = mysql_query("UPDATE nota,item SET nota.harga_item = item.harga_item WHERE nota.id_nota = '$max_id_nota'");

$query2 = mysql_query("UPDATE nota SET subtotal = harga_item * qty WHERE nota.id_nota = '$max_id_nota'");

?><script language="Javascript">;
document.location = 'transaksi2.php' </script><?php
}else
{
print "<script>alert('Maaf, tidak boleh ada field yang kosong !');
javascript:history.go(-1);</script>";
}?>


text:
Q: Binomial Expansion without inifinty series Variable here is "a" and "b".The question is to simplify the $\sqrt [3] { (\frac{a}{\sqrt{b^3} })\times {\frac {\sqrt{a^6b^2}}{a} }+ \frac{a}{b^2}}$
So these are my steps
=$\left(\frac {a^3b} {b^\frac {3} {2} }+ \frac {a} {b^2}\right)^\frac {1} {3}$
=$\left({a^3b^{1-\frac {3} {2}} } + \frac {a} {b^2}\right)^\frac {1} {3}$
=$\left({a^3b^\frac {-1} {2} } + \frac {a} {b^2}\right)^\frac {1} {3}$
Now the real question is,how to simplify this?Assuming the both fraction is simplified to "x" and "y",I get $(x+y)^\frac {1} {3}$ but my family said that it is expanded to this:
$(x+y)^\frac {1} {3}=x^\frac {1} {3}+y^\frac {1} {3}$
It should not be this because $(x+y)^2=x^2+2xy+y^2$
The thing is I noticed where $(x+y)^n$ have a pattern called pascal triangle.But this can be only applied when n≥1 where n is a integer.
The problem with the binomial theorem is that the answer is infinite,which I do not want to get this.I need to get an answer where it is not infinite and does not involve any roots.How do I simplify this?
I have checked with Issac Newton theory,but the Issac Newton theory is infinite.
I have searched online and I see is infinite answer: Link
If this is impossible to simplify without avoiding infinite series,is there another method to solve the question,$\sqrt [3] { (\frac{a}{\sqrt{b^3} })\times {\frac {\sqrt{a^6b^2}}{a} }+ \frac{a}{b^2}}$?

A: In general,
$$(x+y)^{1/3}\ne x^{1/3}+y^{1/3}$$
For example, take $x=y=1$. If this weren't true, we'd have $\sqrt[3]2=2$.
In fact, if $x$ and $y$ are positive, we have:
$$(x+y)^{1/3}<x^{1/3}+y^{1/3}$$


text:
Q: How to make a simple javascript auto scroll widget like Google News? I want to make a real simple widget like this:
https://news.google.com/news/rtc?pz=1&cf=all&ncl=dgEurGFdFYAMclM_T4fKHKqMP6gwM&topic=h&ar=1336324205
It is fixed width and height, and has about five or so items that scroll downwards as new items are added.
I'll be using a datasource to bind the items.
The scroller is there, it is the first item on the top - below the picture bar.
Essentially, new items come from the top and the items at the bottom scroll off. It kind of looks like something dropped from top and popped the bottom thing out - into hiding.


text:
Q: Activate "Managed Metadata Navigation" feature using CSOM We're trying to automate a Site Provisoning process but cannot figure out how to activate the Managed Metadata Navigation feature using CSOM.
This is the code we're executing:
        var clientSite = ClientContext.Site;
        var clientSiteFeatures = clientSite.Features;
        ClientContext.Load(clientSiteFeatures);
        ClientContext.ExecuteQuery();

        // Activate the feature
        clientSiteFeatures.Add(featureId, force, scope);
        ClientContext.ExecuteQuery();

The ID we're activating (this is SP2013 online) is '7201d6a4-a5d3-49a1-8c19-19c4bac6e668' - online resources tell us this should be the correct one. However, this is the error we receive:
Feature with Id '7201d6a4-a5d3-49a1-8c19-19c4bac6e668' is not installed in this farm, and cannot be added to this scope.

Activating the feature manually using Site Settings works like a charm, we didn't get any prerequisite warnings. We've tried activating things like publishing and enterprise features, but no luck.
How can we activate the Managed Metadata Navigation feature using CSOM?

A: This error occurs since Metadata Navigation and Filtering (Id: {7201d6a4-a5d3-49a1-8c19-19c4bac6e668}) is a Web level feature but your example is intended for activating a Site level features.
The following example demonstrates how to activate Metadata Navigation and Filtering feature:
using (var ctx = new ClientContext(webUri))
{
    ctx.Credentials = new SharePointOnlineCredentials(userName, securePassword);

    var featureId = new Guid("7201d6a4-a5d3-49a1-8c19-19c4bac6e668");
    var features = ctx.Web.Features;
    features.Add(featureId, true, FeatureDefinitionScope.None);
    ctx.ExecuteQuery();
}


text:
Q: Python & SCons & Matlab: Wrong command input I am using SCons to install a package, but when I try to compile with mex, the matlab compiler, it runs other command from pdfTeX with same name. To solve this problem on bash, I've just changed .bashrc:
alias mex="/Applications/MATLAB_R2009b.app/bin/mex"
but I dont know how to change it on SCons environment. Someone knows how to do it?
Thanks.

A: I've managed to fix this problem. On SCons, the environment it sees is from the instance:
env = Environment(..., ENV = os.environ)

What I did was to add to os.environ the path of the matlab mex, by doing:
os.environ['PATH'] = matlabPath + '/bin:' +  os.environ['PATH'];

Where matlabPath is the Matlab Path, e.g.:
/Applications/MATLAB_R2009b.app

That's it!


text:
Q: SocketTimeoutException when JBoss routes request to tomcat both running locally I have two applications running locally, one is a JBoss and the other is running on tomcat. Jboss application is legacy one and I have made code changes in it to route the traffic to tomcat server. I want to test this code change locally first before it is deployed on our QA boxes. If the request is of certain type JBoss application builds HttpClient and makes a POST call with appropriate request, header etc to the tomcat application, I print this already so there is no issue here. Now in my tomcat application's console log,  I only see below SocketTimeoutException error, so the request is dying somewhere immediately. I'm lost here and don't know how to debug this further
Things I have tried
1. I have restarted applications multiple times
2. Increased Socket timeouts and connection timeouts etc
3. Started JBoss app in debug mode and made sure that before the actual routing to tomcat happens, request, header, http client config etc.
2016-05-06 14:36:53,920 ERROR [http-nio-8080-exec-2]  - 87d141f302e74 - ygpdY8VQsu -
util.ExceptionHandler - INTERNAL_SERVICE_ERROR_java.net.SocketTimeoutException_org.apache.tomcat.util.net.NioBlockingSelector_read_202
    java.net.SocketTimeoutException
        at org.apache.tomcat.util.net.NioBlockingSelector.read(NioBlockingSelector.java:202)
        at org.apache.tomcat.util.net.NioSelectorPool.read(NioSelectorPool.java:251)
        at org.apache.tomcat.util.net.NioSelectorPool.read(NioSelectorPool.java:232)
        at org.apache.coyote.http11.InternalNioInputBuffer.fill(InternalNioInputBuffer.java:133)
        at org.apache.coyote.http11.InternalNioInputBuffer$SocketInputBuffer.doRead(InternalNioInputBuffer.java:177)
        at org.apache.coyote.http11.filters.IdentityInputFilter.doRead(IdentityInputFilter.java:110)
        at org.apache.coyote.http11.AbstractInputBuffer.doRead(AbstractInputBuffer.java:416)
        at org.apache.coyote.Request.doRead(Request.java:460)
        at org.apache.catalina.connector.InputBuffer.realReadBytes(InputBuffer.java:338)
        at org.apache.tomcat.util.buf.ByteChunk.substract(ByteChunk.java:395)
        at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:363)
        at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:190)
        at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.ensureLoaded(ByteSourceJsonBootstrapper.java:505)
        at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.detectEncoding(ByteSourceJsonBootstrapper.java:129)
        at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.constructParser(ByteSourceJsonBootstrapper.java:226)
        at com.fasterxml.jackson.core.JsonFactory._createJsonParser(JsonFactory.java:1191)
        at com.fasterxml.jackson.core.JsonFactory._createParser(JsonFactory.java:1182)
        at com.fasterxml.jackson.core.JsonFactory.createJsonParser(JsonFactory.java:831)
        at com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:671)
        at com.fasterxml.jackson.jaxrs.base.ProviderBase._createParser(ProviderBase.java:575)
        at org.jboss.resteasy.plugins.providers.jackson.ResteasyJackson2Provider.readFrom(ResteasyJackson2Provider.java:111)
        at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.readFrom(AbstractReaderInterceptorContext.java:59)
        at org.jboss.resteasy.core.interception.ServerReaderInterceptorContext.readFrom(ServerReaderInterceptorContext.java:62)
        at org.jboss.resteasy.core.interception.AbstractReaderInterceptorContext.proceed(AbstractReaderInterceptorContext.java:51)

Edit 1
After further debugging, I found that the error is happening in tomcat server's read interceptor at context.proceed(); line
public class DecoratedReaderInterceptor implements ReaderInterceptor {

    @Override
    public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException {

        boolean validate = shouldValidateResource(context);
        Object obj =  context.proceed();
        if (obj instanceof Resource) {
            processResource((Resource) obj, validate);
        } else if (obj instanceof Resource[]) {
            for (Resource resource : (Resource[]) obj) {
                processResource(resource, validate);
            }
        }
        return obj;
    }
}

Edit 2
Found the answer and I'm embarrassed. In JBoss server there was a debug statement I added to read the stream to output the request, now the stream was already read, tomcat server did not have anything to consume. Hence the SocketTimeoutException


text:
Q: self.property or property in Swift In a Swift method you can access a property using self.property or simply property.
Is there any difference? Is one of these preferred? Is there any style guide published by Apple which requires one or the other?

A:
In practice, you don't need to write self in your code very often. If
  you don't explicitly write self, Swift assumes that you are referring
  to a property or method of the current instance whenever you use a
  known property or method name within a method.
The main exception to this rule occurs when a parameter name for an
  instance method has the same name as a property of that instance. In
  this situation, the parameter name takes precedence, and it becomes
  necessary to refer to the property in a more qualified way. You use
  the self property to distinguish between the parameter name and the
  property name.

Reference: The Swift Programming Guide from Apple.


text:
Q: Protractor Exits with code 0 even though tests are failing I am running protractor v4.0.9 via npm, and noticed that my build on Visual Studio Team Services does not fail even when tests are reported as failing.  Looking into this further, I introduced an error so that tests would fail and then ran them locally.  As the screenshot below shows, I have 17/17 failing tests, but the exit code is still 0, which I understand is a success.  It even says chrome #01 passed, which I assume is wrong.

Here is my protractor config:
"use strict";
exports.config = {
    baseUrl: process.env.npm_package_config_baseUrl,
    framework: 'jasmine',
    capabilities: {
        browserName: 'chrome'
    },
    specs: ['test/*.spec.js'],
    rootElement: 'se-app',
    directConnect: true,
    ignoreUncaughtExceptions: false,
    onPrepare: function () {
        var globals = require('protractor');
        var browser = globals.browser;
        browser.ignoreSynchronization = true;
        browser.manage().window().maximize();
        var specReporter = require('jasmine-spec-reporter');

        // add jasmine spec reporter
        jasmine.getEnv().clearReporters();
        jasmine.getEnv().addReporter(new specReporter({
            displayStacktrace: false
        }));

        var reporters = require('jasmine-reporters');
        jasmine.getEnv().addReporter(new reporters.JUnitXmlReporter({
            savePath: 'junit/'
        }));
    },
};

I checked the documentation for the Protractor config but could not see any obvious settings that would cause this to happen.  I even added in ignoreUncaughtExceptions:false (shown above) to be explicit but it made no difference.

A: Ok, I found the problem.  By default, Jasmine includes the console Reporter and the CompletionReporter.  The latter is what exits the process if the tests fail.  By clearing the reporters, I was removing this reporter.
I could just remove that line, but I want to remove the console reporter so that the spec reporter and console reporter aren't both doing the same job.
So I had to add the completion reporter back in.  I'm not sure if this is the "correct" way to do it, but it works.  Here is my new onPrepare function:
onPrepare: function() {
    let globals = require('protractor');
    let reporters = require('jasmine-reporters');
    let CompletionReporter = require('jasmine/lib/reporters/completion_reporter');
    let SpecReporter = require('jasmine-spec-reporter');

    let browser: ProtractorBrowser = globals.browser;
    browser.ignoreSynchronization = true;
    browser.manage().window().maximize();

    let specReporter = new SpecReporter({
        displayStacktrace: false
    });

    let junitReporter = new reporters.JUnitXmlReporter({
        savePath: 'junit/'
    });

    let completionReporter = new CompletionReporter();
    completionReporter.onComplete((success: boolean) => {
        if (!success) {
            process.exit(1);
        }
    });

    // Now clear all existing reporters and add the ones I want in the order I want
    jasmine.getEnv().clearReporters();
    jasmine.getEnv().addReporter(specReporter);
    jasmine.getEnv().addReporter(junitReporter);
    jasmine.getEnv().addReporter(completionReporter);
}

A: In case anyone runs into this on Jasmine 2+, Maloric's answer won't cover you.  Instead, add the onComplete function to the protractor.conf itself:
...other conf...,
onComplete: function (success) {
    if (!success) {
      process.exit(1);
    }
}

For some reason, the default onComplete action appears to be empty, but this'll rectify it.  If you already have other onComplete actions specified, just add a process.exit(code) call.

A: In case you are using grunt-protractor-runner module to run protractor, make sure that the option keepAlive in Gruntfile.js, under protractor.options is set to false.


text:
Q: move objects on screen in javafx I'm new to Javafx and I'm trying to make a game with it.
For this I need a fluid motion  of some objects on the screen.
I'm not sure, which is the best way.
I started a testfile with some rectangle. I wanted the rectangle to move along a path to the click position. I can make it appear there by just setting the position. So I thought I just could make smaller steps and then the motion would appear fluid. But it doesnt work this way. Either it is because the movement is to fast, so I would need to make the process wait (I wanted to use threads for that purpose) or it is because the java intepreter isn't sequentiell and therefore it just shows the final position. Maybe both or something I didn't come up with.
Now I would like to know weather my thoughts on this topic are right and if there is  a more elegant way to achieve my goal.
I hope you can give me some advise!
regards Felix

A: What you need to do for your car game is to read Daniel Shiffman's The Nature of Code, especially chapter 6.3 The Steering Force.
The book is very easy to understand. You can apply the code to JavaFX. I'll not go into details, you have to learn JavaFX yourself. So here's just the code:
You need an AnimationTimer in which you apply forces, move your objects depending on the forces and show your JavaFX nodes in the UI depending on the location of your objects.
Main.java
package application;

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

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class Main extends Application {

    static Random random = new Random();

    Layer playfield;

    List<Attractor> allAttractors = new ArrayList<>();
    List<Vehicle> allVehicles = new ArrayList<>();

    AnimationTimer gameLoop;

    Vector2D mouseLocation = new Vector2D( 0, 0);

    Scene scene;

    MouseGestures mouseGestures = new MouseGestures();

    @Override
    public void start(Stage primaryStage) {

        // create containers
        BorderPane root = new BorderPane();

        // playfield for our Sprites
        playfield = new Layer( Settings.SCENE_WIDTH, Settings.SCENE_HEIGHT);

        // entire game as layers
        Pane layerPane = new Pane();

        layerPane.getChildren().addAll(playfield);

        root.setCenter(layerPane);

        scene = new Scene(root, Settings.SCENE_WIDTH, Settings.SCENE_HEIGHT);

        primaryStage.setScene(scene);
        primaryStage.show();

        // add content
        prepareGame();

        // add mouse location listener
        addListeners();

        // run animation loop
        startGame();

    }

    private void prepareGame() {

        // add vehicles
        for( int i = 0; i < Settings.VEHICLE_COUNT; i++) {
            addVehicles();
        }

        // add attractors
        for( int i = 0; i < Settings.ATTRACTOR_COUNT; i++) {
            addAttractors();
        }

    }

    private void startGame() {

        // start game
        gameLoop = new AnimationTimer() {

            @Override
            public void handle(long now) {

                // currently we have only 1 attractor
                Attractor attractor = allAttractors.get(0);

                // seek attractor location, apply force to get towards it
                allVehicles.forEach(vehicle -> {

                    vehicle.seek( attractor.getLocation());

                });

                // move sprite
                allVehicles.forEach(Sprite::move);

                // update in fx scene
                allVehicles.forEach(Sprite::display);
                allAttractors.forEach(Sprite::display);

            }
        };

        gameLoop.start();

    }

    /**
     * Add single vehicle to list of vehicles and to the playfield
     */
    private void addVehicles() {

        Layer layer = playfield;

        // random location
        double x = random.nextDouble() * layer.getWidth();
        double y = random.nextDouble() * layer.getHeight();

        // dimensions
        double width = 50;
        double height = width / 2.0;

        // create vehicle data
        Vector2D location = new Vector2D( x,y);
        Vector2D velocity = new Vector2D( 0,0);
        Vector2D acceleration = new Vector2D( 0,0);

        // create sprite and add to layer
        Vehicle vehicle = new Vehicle( layer, location, velocity, acceleration, width, height);

        // register vehicle
        allVehicles.add(vehicle);

    }

    private void addAttractors() {

        Layer layer = playfield;

        // center attractor
        double x = layer.getWidth() / 2;
        double y = layer.getHeight() / 2;

        // dimensions
        double width = 100;
        double height = 100;

        // create attractor data
        Vector2D location = new Vector2D( x,y);
        Vector2D velocity = new Vector2D( 0,0);
        Vector2D acceleration = new Vector2D( 0,0);

        // create attractor and add to layer
        Attractor attractor = new Attractor( layer, location, velocity, acceleration, width, height);

        // register sprite
        allAttractors.add(attractor);

    }

    private void addListeners() {

        // capture mouse position
        scene.addEventFilter(MouseEvent.ANY, e -> {
            mouseLocation.set(e.getX(), e.getY());
        });

        // move attractors via mouse
        for( Attractor attractor: allAttractors) {
            mouseGestures.makeDraggable(attractor);
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Then you need a general sprite class in which you accumulate the forces for acceleration, apply acceleration to velocity, velocity to location. Just read the book. It's pretty much straightforward.
package application;

import javafx.scene.Node;
import javafx.scene.layout.Region;

public abstract class Sprite extends Region {

    Vector2D location;
    Vector2D velocity;
    Vector2D acceleration;

    double maxForce = Settings.SPRITE_MAX_FORCE;
    double maxSpeed = Settings.SPRITE_MAX_SPEED;

    Node view;

    // view dimensions
    double width;
    double height;
    double centerX;
    double centerY;
    double radius;

    double angle;

    Layer layer = null;

    public Sprite( Layer layer, Vector2D location, Vector2D velocity, Vector2D acceleration, double width, double height) {

        this.layer = layer;

        this.location = location;
        this.velocity = velocity;
        this.acceleration = acceleration;
        this.width = width;
        this.height = height;
        this.centerX = width / 2;
        this.centerY = height / 2;

        this.view = createView();

        setPrefSize(width, height);

        // add view to this node
        getChildren().add( view);

        // add this node to layer
        layer.getChildren().add( this);

    }

    public abstract Node createView();

    public void applyForce(Vector2D force) {
        acceleration.add(force);
    }

    public void move() {

        // set velocity depending on acceleration
        velocity.add(acceleration);

        // limit velocity to max speed
        velocity.limit(maxSpeed);

        // change location depending on velocity
        location.add(velocity);

        // angle: towards velocity (ie target)
        angle = velocity.heading2D();

        // clear acceleration
        acceleration.multiply(0);
    }

    /**
     * Move sprite towards target
     */
    public void seek(Vector2D target) {

        Vector2D desired = Vector2D.subtract(target, location);

        // The distance is the magnitude of the vector pointing from location to target.

        double d = desired.magnitude();
        desired.normalize();

        // If we are closer than 100 pixels...
        if (d < Settings.SPRITE_SLOW_DOWN_DISTANCE) {

            // ...set the magnitude according to how close we are.
            double m = Utils.map(d, 0, Settings.SPRITE_SLOW_DOWN_DISTANCE, 0, maxSpeed);
            desired.multiply(m);

        }
        // Otherwise, proceed at maximum speed.
        else {
            desired.multiply(maxSpeed);
        }

        // The usual steering = desired - velocity
        Vector2D steer = Vector2D.subtract(desired, velocity);
        steer.limit(maxForce);

        applyForce(steer);

    }

    /**
     * Update node position
     */
    public void display() {

        relocate(location.x - centerX, location.y - centerY);

        setRotate(Math.toDegrees( angle));

    }

    public Vector2D getVelocity() {
        return velocity;
    }

    public Vector2D getLocation() {
        return location;
    }

    public void setLocation( double x, double y) {
        location.x = x;
        location.y = y;
    }

    public void setLocationOffset( double x, double y) {
        location.x += x;
        location.y += y;
    }

}

In the demo my sprite is just a triangle, I implemented a utility method to create it.
Vehicle.java
package application;

import javafx.scene.Node;

public class Vehicle extends Sprite {

    public Vehicle(Layer layer, Vector2D location, Vector2D velocity, Vector2D acceleration, double width, double height) {
        super(layer, location, velocity, acceleration, width, height);
    }

    @Override
    public Node createView() {
        return Utils.createArrowImageView( (int) width);
    }

}

The demo has an attractor, in your case it'll be just a mouse click. Just click on the circle and drag it. The vehicles will follow it.
package application;

import javafx.scene.Node;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;

public class Attractor extends Sprite {

    public Attractor(Layer layer, Vector2D location, Vector2D velocity, Vector2D acceleration, double width, double height) {
        super(layer, location, velocity, acceleration, width, height);
    }

    @Override
    public Node createView() {

        double radius = width / 2;

        Circle circle = new Circle( radius);

        circle.setCenterX(radius);
        circle.setCenterY(radius);

        circle.setStroke(Color.GREEN);
        circle.setFill(Color.GREEN.deriveColor(1, 1, 1, 0.3));

        return circle;
    }

}

Here's the code for dragging:
MouseGestures.java
package application;

    import javafx.event.EventHandler;
    import javafx.scene.input.MouseEvent;

    public class MouseGestures {

        final DragContext dragContext = new DragContext();

        public void makeDraggable(final Sprite sprite) {

            sprite.setOnMousePressed(onMousePressedEventHandler);
            sprite.setOnMouseDragged(onMouseDraggedEventHandler);
            sprite.setOnMouseReleased(onMouseReleasedEventHandler);

        }

        EventHandler<MouseEvent> onMousePressedEventHandler = new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {

                dragContext.x = event.getSceneX();
                dragContext.y = event.getSceneY();

            }
        };

        EventHandler<MouseEvent> onMouseDraggedEventHandler = new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {

                Sprite sprite = (Sprite) event.getSource();

                double offsetX = event.getSceneX() - dragContext.x;
                double offsetY = event.getSceneY() - dragContext.y;

                sprite.setLocationOffset(offsetX, offsetY);

                dragContext.x = event.getSceneX();
                dragContext.y = event.getSceneY();

            }
        };

        EventHandler<MouseEvent> onMouseReleasedEventHandler = new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {

            }
        };

        class DragContext {

            double x;
            double y;

        }

    }

The playfield layer would be just some race track:
Layer.java
package application;

import javafx.scene.layout.Pane;

public class Layer extends Pane {

    public Layer(double width, double height) {

        setPrefSize(width, height);

    }

}

Then you need some settings class
Settings.java
package application;

public class Settings {

    public static double SCENE_WIDTH = 1280;
    public static double SCENE_HEIGHT = 720;

    public static int ATTRACTOR_COUNT = 1;
    public static int VEHICLE_COUNT = 10;

    public static double SPRITE_MAX_SPEED = 2;
    public static double SPRITE_MAX_FORCE = 0.1;

    // distance at which the sprite moves slower towards the target
    public static double SPRITE_SLOW_DOWN_DISTANCE = 100;

}

The utility class is for creating the arrow image and for mapping values:
Utils.java
package application;

import javafx.scene.SnapshotParameters;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.StrokeLineCap;
import javafx.scene.shape.StrokeLineJoin;

public class Utils {

    public static double map(double value, double currentRangeStart, double currentRangeStop, double targetRangeStart, double targetRangeStop) {
        return targetRangeStart + (targetRangeStop - targetRangeStart) * ((value - currentRangeStart) / (currentRangeStop - currentRangeStart));
    }

    /**
     * Create an imageview of a right facing arrow.
     * @param size The width. The height is calculated as width / 2.0.
     * @param height
     * @return
     */
    public static ImageView createArrowImageView( double size) {

        return createArrowImageView(size, size / 2.0, Color.BLUE, Color.BLUE.deriveColor(1, 1, 1, 0.3), 1);

    }

    /**
     * Create an imageview of a right facing arrow.
     * @param width
     * @param height
     * @return
     */
    public static ImageView createArrowImageView( double width, double height, Paint stroke, Paint fill, double strokeWidth) {

        return new ImageView( createArrowImage(width, height, stroke, fill, strokeWidth));

    }

    /**
     * Create an image of a right facing arrow.
     * @param width
     * @param height
     * @return
     */
    public static Image createArrowImage( double width, double height, Paint stroke, Paint fill, double strokeWidth) {

        WritableImage wi;

        double arrowWidth = width - strokeWidth * 2;
        double arrowHeight = height - strokeWidth * 2;

        Polygon arrow = new Polygon( 0, 0, arrowWidth, arrowHeight / 2, 0, arrowHeight); // left/right lines of the arrow
        arrow.setStrokeLineJoin(StrokeLineJoin.MITER);
        arrow.setStrokeLineCap(StrokeLineCap.SQUARE);
        arrow.setStroke(stroke);
        arrow.setFill(fill);
        arrow.setStrokeWidth(strokeWidth);

        SnapshotParameters parameters = new SnapshotParameters();
        parameters.setFill(Color.TRANSPARENT);

        int imageWidth = (int) width;
        int imageHeight = (int) height;

        wi = new WritableImage( imageWidth, imageHeight);
        arrow.snapshot(parameters, wi);

        return wi;

    }

}

And of course the class for the vector calculations
Vector2D.java
package application;

public class Vector2D {

    public double x;
    public double y;

    public Vector2D(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public void set(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double magnitude() {
        return (double) Math.sqrt(x * x + y * y);
    }

    public void add(Vector2D v) {
        x += v.x;
        y += v.y;
    }

    public void add(double x, double y) {
        this.x += x;
        this.y += y;
    }

    public void multiply(double n) {
        x *= n;
        y *= n;
    }

    public void div(double n) {
        x /= n;
        y /= n;
    }

    public void normalize() {
        double m = magnitude();
        if (m != 0 && m != 1) {
            div(m);
        }
    }

    public void limit(double max) {
        if (magnitude() > max) {
            normalize();
            multiply(max);
        }
    }

    static public Vector2D subtract(Vector2D v1, Vector2D v2) {
        return new Vector2D(v1.x - v2.x, v1.y - v2.y);
    }

    public double heading2D() {
        return Math.atan2(y, x);
    }

}

Here's how it looks like.

The triangles (vehicles) will follow the circles (attractor) and slow down when they get close to it and stop then.


text:
Q: Скриншот открывающегося окна Пытаюсь сделать скриншот появляющейся второй формы над первой:
procedure TForm1.Button1Click(Sender: TObject);
var
i: integer;
b: TBitmap;
begin
 Form2.Show;
 i := 1; // Устанавливаем счетчик
  b := TBitmap.Create(); // Создаем объект типа  TBitmap
  b.Width := Form2.ClientWidth; // Устанавливаем ширину изображения
  b.Height := Form2.ClientHeight; // Устанавливаем высоту изображения
  b.Canvas.CopyRect(Rect(0, 0, b.Width, b.Height), Form2.Canvas,
  Form2.ClientRect);    // Копируем канву формы в наш TBitmap
  while FileExists(InttoStr(i) + '.bmp') do       // Генерируем уникальное имя
  inc(i);
  b.SavetoFile(InttoStr(i) + '.bmp');             // Сохраняем картинку
  b.Free;
end;

На скриншоте второй формы не до конца прорисовываются компоненты (см. картинку).
Также пробовал делать sleep сразу после Form2.Show, но всю задержку я наблюдал непрорисованное окно Form2 - очень странно. я как-то думал, что после Form2.Show форма-то уже должна нарисоваться...

A: Вот и решение:
procedure TForm1.Button1Click(Sender: TObject);
var
  b: TBitmap;
begin
  Form2.Show;
  b := TBitmap.Create();
  b.Width := Form2.ClientWidth;
  b.Height := Form2.ClientHeight;
  Form2.PaintTo(b.Canvas, 0, 0);
  b.SavetoFile('screen.bmp');
  b.Free;
end;


text:
Q: What does the ".Configure()" call do in Fluent.Azure? What does the ".Configure()" call do in Fluent.Azure? Is it required? If I include it in the code (like below) it doesn't return, it just sits and blocks.
But it is used in MS's examples:  https://github.com/Azure-Samples/app-service-dotnet-manage-storage-connections-for-web-apps/blob/master/Program.cs
var azure = Microsoft.Azure.Management.Fluent.Azure
    .Configure()
    .Authenticate(credentials)
    .WithDefaultSubscription()
    ;

[Edit]
Here are the packages I was referencing:

I "was" referencing them because I have since upgraded two of the packages to fix this issue (even though the ones I referenced were within the range specified in the nuget package):  Any command on Fluent.Azure Results in "Method not found"
As for what happens, .Configure() never returns. The code stops and blocks on that line. (Or at least I think it's that line because when I remove it it works.) When I have them enabled, it will throw an exception about the thread being locked up, too, but I disabled those and it didn't return after several hours, when it's very quick without that line of code.

A: First, you'd better provide a completed sample code, and the nuget packages you're using as well as their versions.
Here, I'm using Microsoft.Azure.Management.Fluent, version 1.34.0.
Regarding What does the ".Configure()" call do in Fluent.Azure? Is it required?, After going through the source code here, the Configure() method is used to return an IConfigurable instance, and then IConfigurable instance calls the Authenticate(credentials) method(source code here).
Actually, the Configure() method is not required, you can directly call the Authenticate(credentials) method(source code here).
I'm not sure why it sits and blocks at your side, unless you provide more details as I mentioned previously. I did test with/without .Configure(), either of them can work well.
Here is a screenshot of debug with .Configure() method:


text:
Q: Does Envoy support TCP proxy? Hello can you please let me know if Envoy ( https://lyft.github.io/envoy/ ) support TCP proxy? I saw that external clients can connect to the "Front" Envoy Edge Proxy using HTTP,TLS. Can you please let me know if there is any possibility for external clients to connect using TCP connection? Some kind of HAProxy replacement. For example:
request tcp ip:port   0.0.0.0:7000
forwarded tcp ip:port
192.168.1.11:8000
Thanks

A: Yes, Envoy supports TCP proxy:

Since Envoy is fundamentally written as a L3/L4 server, basic L3/L4 proxy is easily implemented.

It seems there is no example for TCP proxying at the moment but you could try the suggested reference for enabling Envoy to do what you wish.

there is any possibility for external clients to connect using TCP connection?

I guess it depends more on your network setup than on Envoy setup.


text:
Q: how to know if a query is succes or fail in node and mongoose I'm creating a little REST API with express and mongoose, and my problem is relatively simple:
I need to know the typeError to send an statusCode and message to the client. Example, well, if a query for username: John Doe is false, how i know it? Exist a typeError for not matching querys? Or it returns me an empty object instead?
Thanks, and sorry about my bad english.

A: The following code explains how to handle finding duplicates(or at least how I've done it). It's up to you to determine the functions you'll implement for each response and really which query you use. To answer your question though, mongo returns an empty object if there is no duplicate.
Model.findOne({ user_id: 'John Doe' }, function(err, user) {
        if (err) {conole.log(err) // do something if there is an error}
        if (user) {
            // Do something here if a match is found
        } else {
            // Do something here if nothing is found.
});


text:
Q: Amazon API create a website I need to create website using Amazon API where I can pass static content(basically index.html content) and they should return some kind of temporary(internal?) URL to access newly created website.
What are the right services that need to be used to achive such goal?

A: Amazon S3 is probably what you're looking for. It will host static content and if you expose the bucket as publicly visible, then you will get what you're looking for. Here is the developer guide for AWS PHP SDK with S3:
http://docs.aws.amazon.com/aws-sdk-php/guide/latest/service-s3.html
The bucket can be configured for website access via the putBucketWebsite() function.
http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html#_putBucketWebsite


text:
Q: Strangeness and G-parity of glueballs I know that glueballs are virtual particles predicted by QCD and that they form a color singlet. I am stucked in the problem, which seems to be a easy one, of finding the strangennes and G-parity of such a particle. I don't know, or I don't remember, how to find the quantum number S (strangeness) without any previous information about charge - or hypercharge. I know that the simplest glueball has positive parity, zero angular momentum and even under charge conjugation. It means that its G-parity is positive, because the angular momentum is zero and C-parity is positive - it was given. What is troubling me is the strangeness. I believe it has to be zero, but I can't show that.

A: glue ball

In particle physics, a glueball (also gluonium, gluon-ball) is a hypothetical composite particle.1 It consists solely of gluon particles, without valence quarks.

Strangeness is a conserved quantum number except in weak decays. A glue ball consists of gluons which may loop to particle antiparticle pairs which carry zero strangeness, beauty, charm  quantum numbers , as they can only be created by strong interactions in such pairs.


text:
Q: Request with json as data I want to get a response from post request to a site that requires password and json data as input. The code looks like this:
import requests
from requests.auth import HTTPBasicAuth
import json

url = 'http://ssss.ct.xxx:9000/xxx.xx_xxx/xxxx/get/json/'
data = '''{"RowSelectors":[{"Name":"xx","Value":"100649","Operation":"OR" },
{"Name":"xx","Value":"577","Operation":"OR" }],"TableName":"YY"}'''

response = requests.post(url, data=json.loads(data), auth = HTTPBasicAuth('my_user', 'my_password'))
print(response)

And the print function shows me a "Response [415]", which is "Unsupported Media Type" error. I expect it to return me a result from the query in variable "data". I know that something might be wrong with this data, but I don't know how to solve this.
I also tried using another library:
import urllib.request
import urllib.parse
import json
data1 = '''{"RowSelectors":[{"Name":"xx","Value":"100649","Operation":"OR" },
{"Name":"xx","Value":"577","Operation":"OR" }],"TableName":"YY"}'''

data1= json.loads(data1)
params = urllib.parse.urlencode(data1)
x = urllib.request.Request('http://ssss.ct.xxx:9000/xxx.xx_xxx/xxxx/get/json/', data=params)
y= urllib.request.urlopen(x, data = params)

print(y.read())

But it doesn't work too. The error in this case is: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str. And I don't understand the documentation on how i should include the user and password to this code.
Additional maybe useful info : I'm using soapUI and I have 3 inputs that I want to have. First is endpoint=http://ssss.ct.xxx:9000, then its resource=/xxx.xx_xxx/xxxx/get/json/ and the SQL query written in data. I expect my response to be a table in json.
I appreciate any help;)


text:
Q: How to simulate mobile viewport using angular I am building an application where there would be 3 preview buttons (Desktop, Mobile, Tablet). Users will be able to create their own design (such as card view/accordions) which would inherit bootstrap classes for responsiveness. Once they click on the preview buttons for eg Mobile/Desktop/Tablet, their created components would behave as per the viewport.
The necessary CSS is in place. The scenario can be achieved if we are using an iframe to load the component. When we are using the iframe that time the viewport behaves as a separate element, helping the CSS to render as it's getting the desired width for the breakpoint. But without the iframe it's not able to bring the outer shell, hence the CSS is waiting for the entire browser to resize, and then only it can show the changes.
But I would want to remove the iframe dependency from the project. The project is being built using angular js 11.
For better understanding, it's the same thing that we experience when we do inspect elements and switch on the mobile emulator in chrome.
Any kind of help or another solution way around is highly appreciated.


text:
Q: how can I assign variable b to indexes of the string a? I have a problem with task.
Write a program that will replace the given position for the given string (also given by the user). The function has 3 parameters, string for analysis, position that should be replaced and the character that has services to be changed.
I tried it that way but it doesn't work.
At the end there is the same string as at the beginning
a =input("enter string\n")
print(len(a))
for i in enumerate(a):
   print("individual indexes:",([i]))

b = input("enter the index number you want to replace\n")
b = str([a,i])
c = input("what do you want to change ?\n")
a1 = a.replace(b,c)
print(a1)

A: b = int(b)
a1 = a[:b] + 'c' + a[b:]

a =input("enter string\n")
print(len(a))
for i in enumerate(a):
   print("individual indexes:",([i]))

b = int(input("enter the index number you want to replace\n"))
c = input("what do you want to change ?\n")
a1 = a[:b] + 'c' + a[b:]
print(a1)

A: First, a side note. Avoid using variable names such as: a, b...names should be meaningful.
For example:

*

*a  -->  input_str

*b --> idx_to_change

*c --> new_char

*a1 --> final_str
A full working example:
input_str =input("enter string\n")
print(len(input_str))
for i in enumerate(input_str):
   print("individual indexes:",([i]))
idx_to_change = input("enter the index number you want to replace\n")
idx_to_change = input_str [int(idx_to_change)]
new_char = input("what do you want to change ?\n")
final_str = input_str.replace(idx_to_change, new_char)
print(final_str)


text:
Q: How to use struct in custom framework in ios/swift? I need to use struct in my custom framework, how can the following be done?
Here my framework:
MyFramework.framework
public class SomeClass : NSObject {

    public struct myDetails {

        public var firstName: String?
        public var lastName: String?

        public init(fName: String? LastName lName: String?) {
            self.firstName = fName
            self.lastName = lName
        }//init end

    }// struct end

    public func fillStruct(inout myStruct: myDetails) {

        myStruct.firstName = "John"
        myStruct.lastName = "Devid"
    }

}// class end

Here's my Application:
// ViewController.swift

import MyFramework

var refObj: SomeClass?

override func ViewDidLoad() {
    refObj = SomeClass()

    let tempStruct = refObj.myDetails(fName: nil LastName lName: nil) // I CANT ABLE ACCESS LIKE THIS.

    refObj.fillStruct(&tempStruct)
}

What I want, is my application to send the data to the struct and my framework to fill the struct and finish the function.
How can this be achieved?


text:
Q: Google checkout transaction number I am working on a PHP website with Google checkout Payment. I need to get  the transaction id in the merchant calculation page using API Call back url. What method can I use for this?

A: Google Checkout offers a service similar to Paypal's IPN where they send all of the transaction information to a URL you specify. This includes the transaction number.


text:
Q: Using GEGL with GTK 4 for a simple image viewer with pan/zoom support I need a simple image widget with a support of panning/zooming but unfortunately it appears GTK still does not offer one. I have managed to achieve something similar by using a ScrolledWindow and a Picture backed by a PixBuf (via scaling the PixBuf on demand and a EventControllerMotion to mimic panning), but needless to say that this approach is too slow for smooth zooming on touchpads and uses an insanely high amount of memory due to no tiling.
A suggested approach seems to be using GEGL, but it's not obvious how one is supposed to do that. There seems to be helper libraries for previous versions of GTK (gegl-gtk and gegl-gtk3) but I do not know how one is supposed to use it with GTK 4 applications. And to be honest the documentations are pretty much non-existent.
So I would appreciate some examples/explanations on basics usages of GEGL within GTK (4) applications, or whether if there is a better way.


text:
Q: Removing/Hiding Review tab on product pages I'm trying to remove the review tab that appears on product pages and I have added in the two reference blocks below in catalog_product_view.xml.
<block class="Magento\Catalog\Block\Product\View" name="product.info.review" template="product/view/review.phtml"/>
<referenceBlock name="product.info.review" remove="true" />
<referenceBlock name="reviews.tab" remove="true" />

However this has not just removed the review tab but also the Description and Additional Information Tabs. Is there a way of just removing the review tab and nothing else?
My Magento version is 2.2.4

A:
app/code/Vendor/YourTheme/view/frontend/layout/catalog_product_view.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="product.info.details">
            <referenceBlock name="reviews.tab" remove="true"/>
        </referenceBlock>
    </body>
</page>


text:
Q: How to insert nested form values into DB I am using Rails 4.
In my project, include nested form for has_many relationship. From UI point of view, I got it. But nested form values are not inserting into database.
class Newspaper < ActiveRecord::Base
    has_to :newspaper_categories, :dependent_destroy => true
    accepts_nested_attributes_for :newspaper_categories, :allow_destroy => true, :reject_if => :all_blank
end

class NewspaperCategory < ActiveRecord::Base
    belongs_to :newspaper
end

Newspaper form contents like,
<%= nested_form_for(@newspaper) do |f| %>

     # Newspaper form fields

     # Include `Newspaper category` form from the file.
    <%= f.fields_for :newspaper_categories do |nc|%>
         <%= render "newspaper_category"  %>
    <% end %>

    # For add new form using JS
    <%= f.link_to_add "Add New", :newspaper_categories %>

    <%= f.submit %>
<% end %>

In my Newspaper Controller,
# add build in new method,
def new
   @newspaper = Newspaper.new
   @newspaper.newspaper_categoried.build
end

# In params set task_attributes,
def newspaper_params
   params.require(:newspaper).permit(:name, :logo, task_attributes[:cat_link, :_destroy])
end

Where I goes wrong, still i'm confusing to insert

A: Update this
params.require(:newspaper).permit(:name, :logo, {newspaper_categories_attributes: [ :_destroy, :category_id, :rss_link, :image_url]})


text:
Q: Trie tree definition using lambda and defaultdict I thought below trie tree definition may have infinite recursive definition loop, since Trie is defined by Trie, etc. But I tried, it seems ok. Wondering why there is no infinite recursive definition loop?
Trie = lambda: collections.defaultdict(Trie)
root = Trie()
cur = root
for c in 'hello':
    cur = cur[c]


text:
Q: What to do about a closed-as-duplicate question whose answers are arguably superior to answers to referenced question? I just noticed the update to Is there any official Stack Overflow Android app?, which now includes critical information not available in the answers contained in the question that this has been closed as a duplicate of.
The specifics of these specific questions/answers aside, what's the recommend response to encountering a situation like this?

A: I'm answering the general question, not this case in particular.
If the answers on a dupe are better than the ones on the original, one option is to nominate it for merging.  This combines the questions into one (the person doing the merge dccides which question to keep) with all of the answers.
I believe this leaves the dupe question intact, with an annotation saying "merged into (link)".  It's possible that I'm mis-remembering and the merge deletes the dupe.  If so, and if the dupe is valuable as a signpost, then it's easy enough to undelete it afterward.
There is no way1 to move only some answers from one question to another; it's all-or-nothing.
1 Well, presumably devs could hack the database directly, but don't ask for that.  It's probably dangerous and almost certainly not worth the effort.


text:
Q: Rails 3.0 form_tag w/ remote incorrect Accept: header I just installed a rails 3.0.3 project on a new machine and I'm getting some weird behavior related to the form_tag :remote => true. It seems the wrong Accept header is set in the request, so it doesn't come in as an AJAX/JS request, but rather an HTML request. On my production server the Accept header is set correctly:
Accept:*/*;q=0.5, text/javascript, application/javascript, application/ecmascript, application/x-ecmascript

Specs:
ruby 1.8.7 (2010-08-16 patchlevel 302) [i686-linux]
Rails 3.0.3

However, on the new machine I'm setting up it looks like this:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Specs:
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux]
Rails 3.0.3

This is the code for generating the form (inside _request.html.erb)

<%= t( 'user.translation_requests.request' ) %>

  <%= form_tag( request_translation_artist_song_path( @artist, @song ),
           :method => :post,
           :remote => true,
           :class => 'left',
           :style => 'margin-left: 20px;' ) %>
    <%= languages_combobox_large( @into_languages, 'language_id' ).html_safe %>
  </form>

And of course in my controller I only respond to format.js, but the request comes in as format.html. I thought :remote => true took care of this. The generated HTML for the form looks good as well:
<form accept-charset="UTF-8" action="/xxx/request_translation" class="left" data-remote="true" format="js" method="post" style="margin-left: 20px">

A: Please ensure you are including jquery.js as well as *jquery_ujs.js* in your HTML header.
jquery_ujs is responsible for sending forms via AJAX that have set the data-remote attribute. As it is unobtrusive the form will work without that as well. But it is sent via normal page request.


text:
Q: Should I hear be able to a difference in pronunciation between "or" and "all", and if so, what is it? I'm not a native speaker of English; I'm Vietnamese. When I listen to a voice sample of or vs all, I can't hear any difference between those two words.
Do they really have the same pronunciation? If so, does this happen everywhere? How can native speakers hear them as different words? Please clarify.

A: When humans are infants, they learn what phonemes are in their native language, and they learn to distinguish between them. If someone isn't exposed to different phonemes being distinguished at a young age, they may be unable to distinguish them at a later age. For a native speaker of English, "l" and "r" are clearly different, but apparently for people who aren't exposed to this distinction at  a young age, they sound very similar. Asians in general seem to have trouble with this distinction, leading to the term "Engrish" being used to refer to English as spoken by Asian people. I'm sure there are phonemes in Vietnamese that native English speakers would have trouble distinguishing.

A: The 'r' in the word 'or' sounds like a growling dog. The 'l' in the word 'all' is the sound created when you place your tongue to the roof of your mouth at the end of the word. Say the 'a' with mouth open and tongue down, then push to roof of mouth to change the 'a' sound into the 'l'.


text:
Q: Transforming a circle into a sphere by z-axis inflation This question is somehow an analogue to the mylar balloons or paper bag problem, but I was unable to find a solution for the surface of the latter cases (the focus is usually on the calculation of the volume).
If transforming a circle into a sphere along with $z$-axis, we can calculate the $z$ for each given $x,y$ point by
$$(x-x_0)^2 + (y-y_0)^2 + (z-z_0)^2 = r^2$$
assuming the circle is centered in the $x-y$ plane:
$$z = \sqrt{r^2-x^2-y^2}$$
Now if applying a condition for the inflation process. For example, $z$ remains $0$ at $x,y=0,0$ (the circle centre), which creates a torus.

How can we generally calculate the $z$ for a given point $x,y$?
The key point in the sphere case is that $z=0$ at the circle edge, and $z=r$ at $0,0$.
How do we apply the conditions in a typical case like the torus case given above (not generally solving torus)?


text:
Q: multiple components in one template I have main component, whose template is another component. I was wondering can I have 2 components in one template, both to be displayed. For example, I've created component which contains navigation, and the other one contains body. Since I need navigation to stay the same in all other pages, I made a component for it. How can I solve this? Is it even possible?
e.g
import { Component } from '@angular/core';

@Component({
moduleId: module.id,
selector: 'my-app',
template: `
<firstComponent></firstComponent>
<secondComponent></secondComponent>
`
})
export class AppComponent {

}

A: You can do this by having them as two separate components and adding it to declarations array of the respective module
import { Component } from '@angular/core';

@Component({
selector: 'firstComponent',
template: `
         ..................
`
})
export class FirstComponent {

}

Second component
import { Component } from '@angular/core';

@Component({
selector: 'secondComponent',
template: `
         ..................
`
})
export class SecondComponent {

}

export class AppModule {

declarations:[AppComponent,FirstComponent,SecondComponent]


text:
Q: Determine equation of plane that intersects an ellipsoid which results in a specified eccentricity of the resulting intersection ellipse Suppose you're given the ellipse
$$ \dfrac{x^2}{a^2} + \dfrac{y^2}{b^2} + \dfrac{z^2}{c^2} = 1 $$
I would like to find the direction of the normal to the cutting plane to this ellipsoid that will result in an ellipse with a given eccentricity.
That is, if the cutting plane is
$$ n^T (x - x_0) = 0 $$
where $n$ is a unit vector, then find $n$ such that the ellipse of intersection has eccentricity $e$, $0 \le e \lt 1 $.
Since the eccentricity of the intersection ellipse depends only on the direction of the normal vector of the cutting plane, and not its position, we can take $x_0 = 0 $.
My attempt:
Let the unit normal vector of the cutting plane be given in spherical coordinates as
$ n = [ \sin \theta \cos \phi, \sin \theta \sin \phi, \cos \theta ]^T $
Then it follows that two mutually perpendicular vectors that span the plane $n^T r = 0 $ are
$u_1 = [ \cos \theta \cos \phi, \cos \theta \sin \phi, - \sin \theta ]^T$
and
$u_2 =[- \sin \phi, \cos \phi, 0 ]^T $
Therefore, by defining $V = [u_1, u_2] $, we can express points of the plane as
$ r =  V w$
where $w = [w_1, w_2]^T \in \mathbb{R}^2 $
Let $Q = \text{diag}( \dfrac{1}{a^2}, \dfrac{1}{b^2} , \dfrac{1}{c^2} ) $
Substituting $r$ in the equation of the ellipsoid, results in
$ w^T V^T Q V w = 1 $
The matrix $V^T Q V$ is $2 \times 2$, and by finding its eigenvalues $\lambda_1 , \lambda_2$ where $\lambda_1 \le \lambda_2 $, we have that the ratio of the semi-minor axis to the semi-major axis is
$\dfrac{B}{A} = \sqrt{ \dfrac{ \lambda_1 }{\lambda_2 } }$
So that the eccentricity of the ellipse of intersection is
$ e = \sqrt{ 1 - \left(\dfrac{B}{A}\right)^2 } = \sqrt{1 - \dfrac{\lambda_1}{\lambda_2} } $
So given $e$ we want to have the ratio of eigenvalues equal to
$ \dfrac{\lambda_1}{\lambda_2} = 1 - e^2 $
Since the normal of the plane has two degrees of freedom, namely $\theta$ and $\phi$, while the condition on the plane is one-dimensional, then we can fix one of the two parameters, for example $\phi$, and find the angle $\theta$ using iterative numerical methods (because the expression for the eigenvalues is very complex).
That's sums up my approach.
I appreciate any hints, comments, or solutions.

A: As mentioned above in the question, we'll take the unit normal to the plane to be
$ n = [\sin \theta \cos \phi, \sin \theta \sin \phi, \cos \theta ]^T $
Then the $V$ matrix whose two columns are two unit vectors that are mutually orthogonal and also orthogonal to $n$ is given by
$ V = \begin{bmatrix} \cos \theta \cos \phi && - \sin \phi \\ \cos \theta \sin \phi && \cos \phi \\ -\sin \theta && 0 \end{bmatrix} $
It follows that
$V^T Q V = \begin{bmatrix}  c_1^2 (A  c_2^2 + B  s_2^2 ) + C s_1^2  &&        (B - A) c_1 c_2 s_2 \\ (B - A) c_1 c_2 s_2 &&   A s_2^2 + B c_2^2 \end{bmatrix} $
where $c_1 = \cos \theta, s_1 = \sin \theta, c_2 = \cos \phi, s_2 = \sin \phi $, and $A = \dfrac{1}{a^2}, B = \dfrac{1}{b^2} , C = \dfrac{1}{c^2} $
Suppose now that we fix $\phi$ to a certain value, then we can define the following constants to simplify the analysis
$A_1 =  A c_2^2 + B s_2^2 , A_2 = A s_2^2 + B c_2^2  , A_3 = (B-A) c_2 s_2$
Then our matrix becomes
$ V^T Q V = \begin{bmatrix}  A_1 c_1^2  + C s_1^2  &&        A_3 c_1  \\ A_3 c_1 &&   A_2 \end{bmatrix} $
Its eigenvalues are the roots of the following characteristic polynomial,
$ | \lambda I - V^T Q V | = (\lambda - (A_1 c_1^2 + C s_1^2) ) (\lambda - A_2) - A_3^2 c_1^2 $
So the two $\lambda$'s are given by
$\lambda_1 = \dfrac{1}{2} (  B_1 - \sqrt{\Delta} ) $
$\lambda_2 = \dfrac{1}{2} (  B_1 + \sqrt{\Delta} ) $
where
$ B_1 = A_1 c_1^2 + C s_1^2 + A_2 $
$ \Delta = (A_1 c_1^2 + C s_1^2 + A_2)^2 - 4 ( A_2 (A_1 c_1^2 + C s_1^2) - A_3^2 c_1^2) $
Now we want
$\dfrac{\lambda_1}{\lambda_2} =1- e^2  = r^2 $
Therefore,
$ r^2 \lambda_2 = \lambda_1 $
Hence,
$ r^2 (  B_1 + \sqrt{\Delta} ) = (  B_1 - \sqrt{\Delta} ) $
Re-arranging,
$ \sqrt{\Delta} (r^2 + 1) = (B_1)(1 - r^2) $
Squaring
$ \Delta = K B_1^2 \hspace{35pt}(*) $
where $ K = \left( \dfrac{1 - r^2}{1 + r^2} \right)^2$
Recall that
$ B_1 = A_1 c_1^2 + C s_1^2 + A_2 =\alpha_1 + \alpha_2 \cos(2 \theta)  $
where
$\alpha_1 = A_2 + \dfrac{1}{2} (A_1 + C) $
$\alpha_2 = \dfrac{1}{2} (A_1 - C) $
and
$ \Delta = (A_1 c_1^2 + C s_1^2 + A_2)^2 - 4 ( A_2 (A_1 c_1^2 + C s_1^2) - A_3^2 c_1^2) =\alpha_3 + \alpha_4 \cos(2 \theta) + \alpha_5 \cos^2(2 \theta)$  $
where
$\alpha_3 = \bigg(A_2 + \dfrac{1}{2} (A_1 + C) \bigg)^2 -2 A_2 (A_1 + C) + 2 A_3^2 $
$\alpha_4 = A_2 (A_1 - C) - 2 ( A_2 A_1 - A_3^2 - C ) $
$\alpha_5 = \dfrac{1}{4} (A_1 - C)^2$
Equation $(*)$ now becomes
$\alpha_3 + \alpha_4 \cos(2 \theta) + \alpha_5 \cos^2(2 \theta) = K (\alpha_1 + \alpha_2 \cos(2 \theta) )^2 $
which can be re-written in compact form as
$ \alpha \cos(2 \theta)^2 + \beta \cos(2 \theta) + \gamma = 0 \hspace{35pt} (**)$
where
$ \alpha = \alpha_5 - K\alpha_2^2 $
$ \beta = \alpha_4 - 2 K\alpha_1 \alpha_2 $
$ \gamma = \alpha_3 - K\alpha_1^2 $
And this is quadratic polynomial in $ \cos(2 \theta) $, which can be solved by using the quadratic formula.
As an example, I let $a = 3, b = 5, c = 4$, and plotted the resulting $\theta$ as a function of $\phi$ for an eccentricity of $ e = 0.7 $ over the range $0^\circ \le \phi \le 90^\circ$.


text:
Q: How to implement ASP.NET identity: CREATE DATABASE permission denied in database 'master' First of all, I already checked here:
ASP.Net Identity how to set target DB?
I'm now getting this error

CREATE DATABASE permission denied in database 'master'.

On this line of code:
Dim user As User = manager.Find(Trim(Username.Text), Trim(Password.Text))

Full error:

[SqlException (0x80131904): CREATE DATABASE permission denied in database 'master'.]
  System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +3249852
  System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +345
  System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4927
  System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) +1287
  System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +367
  System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +386
  System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) +965
  System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext) +505
  System.Data.Entity.SqlServer.<>c__DisplayClass1a.b__19(DbConnection conn) +136
  System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action1 act) +347
  System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action1 act) +916
  System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) +117
  System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection) +212
  System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection) +172
  System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +175
  System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +116
  System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func3 createMigrator, ObjectContext objectContext) +121
  System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +169
  System.Data.Entity.CreateDatabaseIfNotExists1.InitializeDatabase(TContext context) +257
  System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action  action) +72
  System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +483
  System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input) +177
  System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action) +274
  System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +37
  System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +76
  System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext() +21
  System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider() +59
  System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1 source, Expression1 predicate, CancellationToken cancellationToken) +208
  System.Data.Entity.QueryableExtensions.FirstOrDefaultAsync(IQueryable1 source, Expression`1 predicate) +172
Microsoft.AspNet.Identity.EntityFramework.d__6c.MoveNext() +502
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13855856
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
  Microsoft.AspNet.Identity.CultureAwaiter1.GetResult() +48
  Microsoft.AspNet.Identity.<FindAsync>d__12.MoveNext() +357
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +13855856
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
  Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func1 func) +348
  MyApp.Login_identity.UserLogin_Click(Object sender, EventArgs e) in C:\MyApp\Login_identity.aspx.vb:168
  System.Web.UI.WebControls.Button.OnClick(EventArgs e) +11747645
  System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +150
  System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3360

I changed the DbContext initialization in AppModel.vb to my existing connection string conn1, which points to the SQL Server database I already converted to the new identity tables.
My connection string:
<add name="conn1"
     connectionString="data source=(local)\sqlexpress;Initial Catalog=myapp;User Id=sa;Password=XXXX;"
     providerName="System.Data.SqlClient" />

AppModel.vb:
Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports System.Collections.Generic
Imports System.ComponentModel.DataAnnotations
Imports System.Data.Entity
Imports System.Linq
Imports System.Web

Namespace AspnetIdentitySample.Models
    Public Class ApplicationUser
        Inherits IdentityUser
        ' HomeTown will be stored in the same table as Users
        Public Property HomeTown() As String
            Get
                Return m_HomeTown
            End Get
            Set(value As String)
                m_HomeTown = Value
            End Set
        End Property
        Private m_HomeTown As String
        Public Overridable Property ToDoes() As ICollection(Of ToDo)
            Get
                Return m_ToDoes
            End Get
            Set(value As ICollection(Of ToDo))
                m_ToDoes = Value
            End Set
        End Property
        Private m_ToDoes As ICollection(Of ToDo)

        ' FirstName & LastName will be stored in a different table called MyUserInfo
        Public Overridable Property MyUserInfo() As MyUserInfo
            Get
                Return m_MyUserInfo
            End Get
            Set(value As MyUserInfo)
                m_MyUserInfo = Value
            End Set
        End Property
        Private m_MyUserInfo As MyUserInfo
    End Class

    Public Class MyUserInfo
        Public Property Id() As Integer
            Get
                Return m_Id
            End Get
            Set(value As Integer)
                m_Id = Value
            End Set
        End Property
        Private m_Id As Integer
        Public Property FirstName() As String
            Get
                Return m_FirstName
            End Get
            Set(value As String)
                m_FirstName = Value
            End Set
        End Property
        Private m_FirstName As String
        Public Property LastName() As String
            Get
                Return m_LastName
            End Get
            Set(value As String)
                m_LastName = Value
            End Set
        End Property
        Private m_LastName As String
    End Class

    Public Class ToDo
        Public Property Id() As Integer
            Get
                Return m_Id
            End Get
            Set(value As Integer)
                m_Id = Value
            End Set
        End Property
        Private m_Id As Integer
        Public Property Description() As String
            Get
                Return m_Description
            End Get
            Set(value As String)
                m_Description = Value
            End Set
        End Property
        Private m_Description As String
        Public Property IsDone() As Boolean
            Get
                Return m_IsDone
            End Get
            Set(value As Boolean)
                m_IsDone = Value
            End Set
        End Property
        Private m_IsDone As Boolean
        Public Overridable Property User() As ApplicationUser
            Get
                Return m_User
            End Get
            Set(value As ApplicationUser)
                m_User = Value
            End Set
        End Property
        Private m_User As ApplicationUser
    End Class
    Public Class MyDbContext
        Inherits IdentityDbContext(Of ApplicationUser)
        Public Sub New()
            MyBase.New("conn1") 'DefaultConnection
        End Sub

        Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
            MyBase.OnModelCreating(modelBuilder)

            ' Change the name of the table to be Users instead of AspNetUsers
            modelBuilder.Entity(Of IdentityUser)().ToTable("Users")
            modelBuilder.Entity(Of ApplicationUser)().ToTable("Users")
        End Sub

        Public Property ToDoes() As DbSet(Of ToDo)
            Get
                Return m_ToDoes
            End Get
            Set(value As DbSet(Of ToDo))
                m_ToDoes = Value
            End Set
        End Property
        Private m_ToDoes As DbSet(Of ToDo)

        Public Property MyUserInfo() As DbSet(Of MyUserInfo)
            Get
                Return m_MyUserInfo
            End Get
            Set(value As DbSet(Of MyUserInfo))
                m_MyUserInfo = Value
            End Set
        End Property
        Private m_MyUserInfo As DbSet(Of MyUserInfo)
    End Class

End Namespace

UPDATE
Based on a comment I also checked here.
I don't really get why this is a role issue, since I'm reusing a connection string that is already working fine with updating other (non-identity related) tables. Also I don't get why the error refers to the master table as I'd expect that I'm not trying to connect to that in any way by the manager.Find method.
Anyway, the user through which I'm currently testing is already assigned to the sysadmin role:

UPDATE 2
Ok, thanks to Jeremy's comment below I'm a step closer...I needed to add user IIS APPPOOL\.NET v4.5 to role sysadmin, because that was the user connecting as shown in SQL Server profiler (although I'm unsure about the security risks when adding this user to this role).
Anyway, the Find method no longer throws an error and using SQL Server profiler I see the SQL statement is fired when I execute this code Dim user As User = manager.FindByName(Trim(Username.Text))
exec sp_executesql N'SELECT TOP (1)
[Extent1].[Id] AS [Id],
[Extent1].[ApplicationId] AS [ApplicationId],
[Extent1].[MobileAlias] AS [MobileAlias],
[Extent1].[IsAnonymous] AS [IsAnonymous],
[Extent1].[LastActivityDate] AS [LastActivityDate],
[Extent1].[MobilePIN] AS [MobilePIN],
[Extent1].[LoweredEmail] AS [LoweredEmail],
[Extent1].[LoweredUserName] AS [LoweredUserName],
[Extent1].[PasswordQuestion] AS [PasswordQuestion],
[Extent1].[PasswordAnswer] AS [PasswordAnswer],
[Extent1].[IsApproved] AS [IsApproved],
[Extent1].[IsLockedOut] AS [IsLockedOut],
[Extent1].[CreateDate] AS [CreateDate],
[Extent1].[LastLoginDate] AS [LastLoginDate],
[Extent1].[LastPasswordChangedDate] AS [LastPasswordChangedDate],
[Extent1].[LastLockoutDate] AS [LastLockoutDate],
[Extent1].[FailedPasswordAttemptCount] AS [FailedPasswordAttemptCount],
[Extent1].[FailedPasswordAttemptWindowStart] AS [FailedPasswordAttemptWindowStart],
[Extent1].[FailedPasswordAnswerAttemptCount] AS [FailedPasswordAnswerAttemptCount],
[Extent1].[FailedPasswordAnswerAttemptWindowStart] AS [FailedPasswordAnswerAttemptWindowStart],
[Extent1].[Comment] AS [Comment],
[Extent1].[Email] AS [Email],
[Extent1].[EmailConfirmed] AS [EmailConfirmed],
[Extent1].[PasswordHash] AS [PasswordHash],
[Extent1].[SecurityStamp] AS [SecurityStamp],
[Extent1].[PhoneNumber] AS [PhoneNumber],
[Extent1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
[Extent1].[TwoFactorEnabled] AS [TwoFactorEnabled],
[Extent1].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
[Extent1].[LockoutEnabled] AS [LockoutEnabled],
[Extent1].[AccessFailedCount] AS [AccessFailedCount],
[Extent1].[UserName] AS [UserName]
FROM [dbo].[AspNetUsers] AS [Extent1]
WHERE ((UPPER([Extent1].[UserName])) = (UPPER(@p__linq__0))) OR ((UPPER([Extent1].[UserName]) IS NULL) AND (UPPER(@p__linq__0) IS NULL))',N'@p__linq__0 nvarchar(4000)',@p__linq__0=N'flo@outlook.com'

The strange thing is: when I execute it directly in SQL Server Management Studio I get a record returned, but in my code the variable user is Nothing....What can it be?

A: Try this, if your application pool is running under a NETWORK SERVICE identity. Then give SysAdmin Role for "NT AUTHORITY\NETWORK SERVICE":

Or give SysAdmin to which ever account running the app pool.
If that doesn't work, check if any of these solutions help: CREATE DATABASE permission denied in database 'master' (EF code-first)
Edit:
Its not very secure to give all these accounts sysAdmin. After you get this working tighten up the SQL security to just dbReader and dbWriter roles.

And what is going wrong with the FindByName method?

Now there is no exception and the problem is that no data is returned I think
there is still something going on with permissions.
Since you're using SQL Authentication in the Connection String, can you try it with Windows Integrated? Otherwise try using the appPool IIS accounts credentials in your connection string and see if that yields a clue as to whats wrong?

A: You connection string contains "User Id=sa;Password=XXXX", thus that connection is attempting to use SQL Server authentication. Your SSMS login property's title bar appears to be identifying a Windows account, which implies there is a belief that Windows Authentication should be used. And yet the connection is attempting to use SQL Server authentication (not Windows authentication). If not already configured, SQL Server's authentication mode can be changed to support both SQL Authentication and Windows Authentication ("Mixed Mode" authentication) see https://msdn.microsoft.com/en-us/library/ms188670.aspx.
Alternatively, the connection string can be changed to use Windows authentication/integrated security, per https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx#integratedsecurity

A: Why instead to utilize an identity field don´t you utilize a HASH value in a NVARCHAR() field?
For instance: you may get an individual data from user (or a join of his fields), calculate a HASH from .NET Cryptography library and set that NVARCHAR() with the data.
This way (and supposing you´re utilizing SHA-512 HASH) you will be able to have a Base64 string of an individual data, like an Identity itself.
But, if your goal is have an identity to the momentum, you may get the user data, plus the current datetime, calculate its HASH and save this data as the record´s identity.

A: You should probably use a different SQL account than "sa" but the default database for sa is master.  The Find method is likely using the default database for the user even though myapp is defined in the connection string.
Change the default database for sa to myapp, here:

A: Your user should be added to the dbcreator role.
Otherwise you're not allowed to create new databases.
Sysadmin/public are not enough.


text:
Q: Angularjs - Accordion not works as per expect using the angularjs, i have created a accordion effects. all it works rather that considering other panel.
my accordion have 2 panels, when i click on first panel, that should shuffle the state ( that's happening ) and need to close other panel if that opens. how to do that?

var app = angular.module('myapp', []);
app.controller('MainCtrl', function($scope) {
    $scope.one = false;
    $scope.two = false;
    $scope.accordion = function( label ) {
        $scope[label] = !$scope[label];
    }
});
h1 {
    background: gray;
    cursor: pointer;
}

Title One

Content one

Title Two

Content Two

A: Its simply a matter of assignment of single variable, without any complex logic. Hence, removing the redundant function and moving assignment to ng-click in HTML.

var app = angular.module('myapp', []);

app.controller('MainCtrl', function($scope) {

  //$scope.one = false; // this is not required anymore
  //$scope.two = false; // this is not required anymore
  $scope.current = 'one';
  // toggle accordion state
  $scope.toggleAccordion = function(label){
        if($scope.current == label){
              $scope.current = '';
        } else {
              $scope.current = label;
        }
  }

});
h1{
  background:gray;
  cursor:pointer;
}

Title One

Content one

Title Two

Content Two


text:
Q: How can I add events to a dynamically created PictureBox? (Visual Basic) As you can see, This is my current code for making pictureboxes. Basically, I am going to make about a hundred of them, so doing it by hand will be a giant pain. I don't know how to add events though, how do you do it?

A: Imports System.ComponentModel
Public Class frmScreen
    Inherits Form
    Dim CellColor As PictureBox
    '
    '
    '
Private Sub Screen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    CellColor = New PictureBox
    With CellColor
        .BackColor = Color.Azure
        '
        '
        '
    End With

    'When you do click on the CellColor control the you go to ScreenPicBox method
    AddHandler CellColor.Click, AddressOf ScreenPicBox_Checked

    'If you need to remove by code the handler you can write the following instruction
    RemoveHandler CellColor.Click, AddressOf ScreenPicBox_Checked

End Sub

Private Sub ScreenPicBox_Checked(sender As Object, e As EventArgs)
    If TypeOf sender Is PictureBox Then
        'do anything here
    End If

End Sub

End Class
I hope that it shows the way you want, Darp mosh. Happy coding! :)