Q: Rails precompile multiple javascript_includes_tag I'm actually building a new app under Rails 4.
I used to put my javascript_includes_tag at the bottom of my layout. But for an unknown reason, it creates a bug when trying to use confirm: on delete link.
So I put back this line at the top :
!!!
%html{ :lang => 'en' }
  %head
    = stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true
    = javascript_include_tag "application", "data-turbolinks-track" => true

So far so good, the bug is now gone. Anyway, since my app is gonna use a lot of Javascript, I still need to load those third part library at the bottom. So, what I did is to only let the Rails library at the top :
// application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks

Then I tried to create another js file named third-part and try to do the same as application but including my third part libraries. Unfortunately, it does not work.
// third-part.js
//= require bootstrap
//= require app
//= require app.plugin

How can I add another javascript_includes_tag at the bottom the same way I did for application? Here I mean that on production it will also compress those files.
Thanks a lot for your help
EDIT :
It's actually loading my files well on DEVELOPMENT, but not on my production.
On production I just got <script data-turbolinks-track="true" src="/javascripts/third-part.js"></script> and I can't access the file
I've tried :
config.assets.precompile += %w( third-part.js )

and
rake assets:precompile RAILS_ENV=production

but it still not working
EDIT 2 :
I made a test of precompliling on production mode from my local machine. It did work. It might be a problem with my server.
EDIT 3 :
Just earse my application from server and clone a new one from my Github but it's still not working. Don't know why :(

A: In your config/environments/production.rb add this line to precompile the external assets
config.assets.precompile += ["third-part.js"]

and don't forget to mention env=production while precompiling assets on production.


Q: Magento: Limit text field size in product custom attribute to 80 characters I have a problem by using the following tip from the magento forum:

Quote:
  One option you could do is to add a backend model for this attribute.
  In this model you could write your own beforeSave function that will
  process the length of given value and trim it to be the desired
  length. The class should extend  Mage_Eav_Model_Entity_Attribute_Backend_Abstract
Code:

public function beforeSave($object) {
     $attrCode = $this->getAttribute()->getAttributeCode();
     if ($object->hasData($attrCode)) {
         $object->setData($attrCode, substr($object->getData($attrCode),0,50));
     }
     return $this; }

My question now is: how and where do I implement this snippet?
I recently put it in /app/code/core/Mage/Eav/Model/Entity/Attribute/Backend/Default.php but it had no effect.

A: first at all, you'll never should place custom code into core files. This destroys your upgradabillity. Create your own custom modules under app/code/local. There you can create your model which extends from Mage_Eav_Model_Entity_Attribute_Backend_Abstract.
May this link helps you to create your module:
http://www.smashingmagazine.com/2012/03/01/basics-creating-magento-module/
Also you can use magerun (an cli tool for magento) to create a module: http://magerun.net/


Q: Usage of Negatives in Everyday Speach: Unnecessary or Incorrect I frequently have this debate with my fiancée about whether it is as appropriate to use a negative in the following examples as it is to omit it.
I am frequently found making statements using the negative form seen below:

*

*"I wonder if they wouldn't mind taking us with them this weekend."
vs

*

*"I wonder if they would mind taking us with them this weekend."
or

*

*"I wonder if it wouldn't be possible to substitute ham for turkey in my sandwich."
vs

*

*"I wonder if it would be possible to substitute ham for turkey in my sandwich."
Question

*

*Is it appropriate to use the negative form "wouldn't" in these sentences?

Author's Viewpoint
The way I see it, it is just as appropriate to wonder if something was possible is it would be to wonder if it was not possible. One may view this as inefficient speech but I don't believe it is incorrect; grammatically or otherwise.
I would greatly appreciate it if someone could give an explanation as to why this is correct or incorrect and the reasoning behind their position.


Q: IIS is not loading .css files Hi I just started working with an IIS server for my AngularJS project.
So my problem is that my project loads angular, but not .css files, neither my own nor bootstraps.
I have looked at the big fat web, and I noticed that most solutions is to check static content in Windows features. However that was already ticked for me. And I'm wondering if there are other solutions?

index.html
<!doctype html>
<html ng-app="SimPlannerApp">
    <head>
        ...

        <!-- Load Bootstrap CSS library -->
        <link type="text/css" href="lib/bootstrap-3.3.5-dist/css/bootstrap.min.css">

        <!-- Load AngularJS modules -->
        <script src="lib/Angular-1.4.7/angular.min.js"></script>
        <script src="lib/Angular-1.4.7/angular-ui-router.min.js"></script>

        <!-- Load AngularJS Application -->
        <script src="core.js"></script>

        <!-- Our CSS -->
        <link type="text/css" href="assets/styles/main.css">
        <link type="text/css" href="assets/styles/nav.css">
    </head>

    <body>
        ...

        <!-- This is where page content is inserted to -->
        <div ui-view></div>
    </body>
</html>

File tree

*

*assets

*styles

*

*main.css

*nav.css

*lib

*Angular-1.4.7

*

*angular.min.js

*angular-ui-router.min.js

*bootstrap-3.3.5-dist

*

*css

*

*bootstrap.min.css

*index.html

*core.js

Files loaded to the browser

A: A guy in my team found the solution. When referencing the stylesheets I've forgotten the rel="stylesheet" after each of them.
so this
<link type="text/css" href="assets/styles/main.css">

should be this
<link type="text/css" href="assets/styles/main.css" rel="stylesheet">


Q: Ensure rotation takes the same amount of time regardless of angle to be rotated in Unity I hope somebody can help.  I have a script that rotates a globe, over which a plane (which is stationary) flies from 1 country to another.  This all works fine and is achieved with the following script
while (!DestinationReached)
    {
        Vector3 planetToCountry = (Destination.localPosition - Vector3.zero);//.normalized; //vector that points from planet to country
        Vector3 planetToCamera = (camTr.position - tr.position).normalized; //vector that points from planet to camera/plane

        Quaternion a = Quaternion.LookRotation(planetToCamera);
        Quaternion b = Quaternion.LookRotation(planetToCountry);

        b = Quaternion.Inverse(b);

        newRotation = a * b;
        tr.rotation = Quaternion.Slerp(tr.rotation, newRotation, 0.01f);

        if (Approximately(tr.rotation, newRotation, 0.0001f)) //if here the plane has arrived
        {
            Debug.Log("Destination reached");
            DestinationReached = true;
        }
        yield return new WaitForEndOfFrame();

    }

It essentially calculates the angle between the plane (the camera is attached to the plane GO and views it from above) and the destination the globe needs to rotate to so that the plane looks as though it flies to the destination.
The issue I have is I need to make the flight time uniform regardless of the angle the globe must rotate, so lets say it must be 5 seconds, regardless if the plane flies from Paris to Ireland or Paris to Australia.  Anybody have any ideas on how to do this.
I have to admit, I nicked this script for the web, as my Vector and Quaternion mathematics is hopeless :)

A: If you want to be flexible and e.g. add some easing at beginning and end but still finish within a fixed duration I would do it like this (I'll just assume here that your calculating the final rotation is working as intended)
// Adjust the duration via the Inspector
[SerializeField] private float duration = 5f;

private IEnumerator RotateRoutine()
{
    // calculate these values only once!

    // store the initial rotation
    var startRotation = tr.rotation;

    // Calculate and store your target ratoation
    var planetToCountry = (Destination.localPosition - Vector3.zero);
    var planetToCamera = (camTr.position - tr.position);

    var a = Quaternion.LookRotation(planetToCamera);
    var b = Quaternion.LookRotation(planetToCountry);
    b = Quaternion.Inverse(b);

    var targetRotation = a * b;

    if(duration <= 0)
    {
        Debug.LogWarning("Rotating without duration!", this);
    }
    else
    {
        // track the time passed in this routine
        var timePassed = 0f;
        while (timePassed < duration)
        {
            // This will be a factor from 0 to 1
            var factor = timePassed / duration;
            // Optionally you can alter the curve of this factor
            // and e.g. add some easing-in and - out
            factor = Mathf.SmoothStep(0, 1, factor);

            // rotate from startRotation to targetRotation via given factor
            tr.rotation = Quaternion.Slerp(startRotation, targetRotation, factor);

            // increase the timer by the time passed since last frame
            timePassed += Time.deltaTime;

            // Return null simply waits one frame
            yield return null;
        }
    }

    // Assign the targetRotation fix in order to eliminate
    // an offset in the end due to time imprecision
    tr.rotation = targetRotation;

    Debug.Log("Destination reached");
}

A: So the problem here is the t used on your Quaternion.Slerp method, it's constant. This t is the "step" the slerp will do, so if it's contstant, it won't depend on time, it will depend on distance.
Try instead to do something like this, being timeToTransition the time you want that every rotation will match:
public IEnumerator RotatintCoroutine(float timeToTransition)
{
    float step = 0f;
    while (step < 1)
    {
        step += Time.deltaTime / timeToTransition;
        //...other stuff
        tr.rotation = Quaternion.Slerp(tr.rotation, newRotation, step);
        //...more stuff if you want
        yield return null;
    }
}

Edit: addapted to your code should look like this
float timeToFly = 5f;
while (!DestinationReached)
{
    step += Time.deltaTime / timeToTransition;

    Vector3 planetToCountry = (Destination.localPosition - Vector3.zero);//.normalized; //vector that points from planet to country
    Vector3 planetToCamera = (camTr.position - tr.position).normalized; //vector that points from planet to camera/plane

    Quaternion a = Quaternion.LookRotation(planetToCamera);
    Quaternion b = Quaternion.LookRotation(planetToCountry);

    b = Quaternion.Inverse(b);

    newRotation = a * b;
    tr.rotation = Quaternion.Slerp(tr.rotation, newRotation, step);

    if (step >= 1) //if here the plane has arrived
    {
        Debug.Log("Destination reached");
        DestinationReached = true;
    }
    yield return null();
}


Q: Removing dateline in polygons I am using the marine boundaries data from MarineRegions.org and I'm trying to use cylindrical equal area with a -160 central meridian.  I successfully removed the dateline from polygons basically using the method outlined in this GISSE question.  However, the marine boundaries dataset the polygons are singlepart, even with the split and ArcGIS is not allowing me to explode to multi-part (to then dissolve)... the option is grey-ed out.  Can anyone provide a solution to the polygon-crossing-international-dateline problem when the original polygon is singlepart?
Basically, is there a way to accomplish this in ArcGIS?


Q: Functions of jdbc Driver Why jdbc odbc driver written as jdbc.odbc.JdbcOdbcDriver or sun.jadbc.odbc.JdbcOdbc Driver?
In which file the name is stored?
 eg.
 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")

And  What are the functions of jdbcodbc driver and odbc driver?

A:
Why jdbc odbc driver written as jdbc.odbc.JdbcOdbcDriver or sun.jadbc.odbc.JdbcOdbc Driver?

Because (presumably) there are two different JDBC->ODBC driver classes, and those are their respective fully qualified class names.  (Your question is a bit like asking "why are tyres called Michelin and Goodyear?")

In which file the name is stored?

That entirely depends on the design of your application and/or the framework it is using for persistence.

eg.  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")

In that example, the class name is hard-wired into the source code.  Why?  You'd need to ask the person who wrote it!!

And What are the functions of jdbcodbc driver and odbc driver?

A plain ODBC driver provides client-side ODBC APIs that an application can use to make calls to a database.  The driver implements that functionality by interfacing with the vendor-specific native database protocols and / or APIs.  Thus, the driver is hiding the database-specific stuff behind a database independent facade.
A plain JDBC driver does the same thing except that it is providing JDBC APIs.
A JDBC-ODBC driver is actually a "bridge" between the JDBC and ODBC APIs.  The application makes JDBC calls that are mapped to ODBC class by the driver.  This driver then calls a plain ODBC driver which talks to the actual database.  (You would use this if you had a database that had only ODBC drivers, and you wanted to access it from an application implemented to use JDBC.)
For more information on JDBC and ODBC, refer to the respective Wikipedia pages, etcetera.

A: When you use Class.forName(), you create a new class with the given fully qualified name. Since you connect to a DB, you must use the DB driver specific to the type of connection you use. After that I assume you will use DriverManager to create a connection to that resource. The DriverManager will look for classes that can use the connection string you pass to it.


Q: How do I apply only one file or two classes from a Puppet Master server? Let us say that I have a case in which I need to apply only two files from a Puppet configuration on some production servers, without touching the rest of the configuration.
/opt/aservice/myfile/thekey.conf
/opt/myfile/thekey.salt
Let's also say that these are controlled by the following Puppet manifest:
#
# author: Nathan Basanese (nathan@basanese.com)
# date: 04/17/2048
#

class keyconfig ( $cluster ){
    notify {"Deploying key config. files to $fqdn":}

    file {'/opt/aservice/key/config/thekey.conf':
                ensure => present,
                mode => '0644',
                owner => 'aservice-serv',
                group => 'aservice-serv',
                source => "puppet:///modules/keyconfig/$cluster/thekey.conf",
        }
    file {'/opt/aservice/key/config/thekey.salt':
                ensure => present,
                mode => '0644',
                owner => 'aservice-serv',
                group => 'aservice-serv',
                source => "puppet:///modules/keyconfig/$cluster/thekey.salt",
        }
}

How would I apply ONLY these two files to a given server from a Puppet Master?
Perhaps, in the puppet agent command that is run on the target server, could I specify a specific Puppet class to use?
I have used the puppet resource command before, but I'm not sure that would work, here.

A: Every resource is automatically tagged with the fully qualified name of the class or defined type in which it is declared, and with every namespace  segment of the class or type name, among other tags.  You can use those tags to filter the resources that will be applied during a given catalog run.  In the particular example you describe, you could use
puppet agent --no-daemonize --onetime --tags keyconfig

to apply only the resources declared in class keyconfig (and in any other class declared by keyconfig, recursively, but in this case there are no such other classes).
You can also declare tags manually by using the tag metaparameter in your resource declarations.  That can allow you to provide for identifying custom collections of resources.  And speaking of collections, you can use tags in the selection predicates of resource collectors, too.

A: The only way to do that is to have that node contain only the class you are wanting to have applied. In your site.pp you would have the following where the 'myhost.dns' is your fqdn. and $mycluster would be replaced by your cluster string.
node 'myhost.dns' {
    class { 'keyconfig':
      cluster => $mycluster,
    }
}


Q: Button click requires double click or long-press on mobile I'm trying to click a button in a React app, and while it works on desktop, it does not work properly on mobile. I need to long-press or double-click, and play a little bit until the button finally works.
I have replicated my problem in this demo.
If you open the page on a desktop browser and attempt to open the hamburger menu, it should open right away. However, if you open it in mobile, it will not work right away. You will also see the menu jitter a little bit off-screen. Attempting to close the menu by clicking on the overlay has the same problem in mobile.
Why is this not working properly on mobile? How can I get the button to work when I tap it?
I added cursor:pointer to the button after seeing this somewhat similar post, but this doesn't help.
This problem has occurred in the past to me, and I was able to solve it using onMouseDown but it doesn't work this time, I'm guessing because I'm using a component that is imported from a package (react-burger-menu) and can't override its onClick function? I'm not sure what is happening.
EDIT: Solved. See my answer.

A: Turns out it works if I fix the stacking of elements. I had nested my navbar component inside the MapContainer, but this was making things wonky mobile-side. I moved my component outside the MapContainer, and things worked.
I still don't understand why it went wonky mobile-side and in iOS only, but this problem at least is solvable.
Fixed example is here.
My map token has been removed, so you can use your own to substitute, but it is not necessary to have the map showing to see the problem/solution.


Q: How to add my own classes in iReport when I change from Groovy to Java language? I'm working with iReport and JasperReports, when I began to do my report, iReport by default use Groovy, but I need to change to  Java (constrains in my job), I make my report with Groovy and It's works perfectly but when I change to Java language, I get a trouble, because I use a class(fields from java of a class) in my report, so the Mistake is: myfield cannot be resolved  or is not a field.
The class that I use to do my report is:
public final class GrupoEstadistico implements Serializable {

    private Estadistico ccDocumento;
    private Estadistico ccNombres;

    //another class that is an attribute of type Estadistico

    private Date periodo;
    private String tipoEntidad;

    //and another primitives atributes: strings, int

    //getters and setters
}

This is the Estadistico class:
public final class Estadistico implements Serializable, Comparable<Estadistico> {

    private String nombreEntidad;
    private int codigo;
    private int numeroConsultas = 0;

    //and aother primitives atributes: strings, int
    //getters and setters
}

And I use all attributes of the class GrupoEstadistico in my report like a fields.
And I use expressions to get the values of each Estadistico like:
$F{ccDocumento}.numeroConsultasanyone

The trouble that I get when I try to compile the report is:
numeroConsultas cannot be resolved  or is not a field.

What I understand is happening is:

*

*iReport not find my class attributes thus this has

*iRreport not understand the expressions I use.

This is that I been tried to solve my problem:

*

*add a jar file with the classes required to classpath of iReport.

*add the import like: reporte.model.GruoEstadistico in the properties of my report.

*And I been edited the xml and I add the tag scriptlet:
 <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
 name="ListaConsultaEstadistico" pageWidth="895" pageHeight="595"
 orientation="Landscape" columnWidth="855" leftMargin="20" rightMargin="20"
 topMargin="20" bottomMargin="20"
 scriptletClass="reporte.model.GrupoEstadistico"
 uuid="b0990d7b-fade-4200-a2ef-fb0416f5a9c2">

UPDATE:
I'm calling my report from the Java code the following way:
/**Create a List of GrupoEstadistico class. */

List<GrupoEstadistico> this.dataSource = new ArrayList<GrupoEstadistico>();

/**Fill my List....*/

JasperPrint jasperPrint= JasperFillManager.fillReport( reportPath,this.parametros,
                 new JRBeanCollectionDataSource( this.dataSource ));

The dataSource is a  List<GrupoEstadistico>
But still does not work.
Can anyone help me?

A: Send your object in ireport using java program. Define a field with name of your instance and attribute. e.g.
Suppose you send your class instance with grupoEstadistico, define a field in ireport with name "grupoEstadistico.tipoEntidad". and Drag a textfield in any band.
RightClick->Edit Expression-> remove ${field}-> double click on your field->click apply
It will add you attribute in *iReport *. now if you download your file as pdf format , it will show data what ever you send in this instance.


Q: Long Ubuntu 12.04 booting time Can someone help me with the delays in booting:

[    6.034566] tg3 0000:01:00.0: eth0: dma_rwctrl[76180000] dma_mask[64-bit]
  [   10.158037] EXT4-fs (sda5): mounted filesystem with ordered data mode. Opts: (null)
  [   43.640175] ADDRCONF(NETDEV_UP): eth0: link is not ready
[   47.632127] init: plymouth-stop pre-start process (2528) terminated with status 1
  [   47.843599] ieee80211 phy0: brcms_ops_bss_info_changed: arp filtering: enabled true, count 1 (implement)
  [   58.376473] wlan0: no IPv6 routers present
  [   67.530222] cfg80211: Found new beacon on frequency: 2472 MHz (Ch 13) on phy0

A: Maybe is something related with your video driver, because of plymouth crash.
Try updating your video driver to a recent version.


Q: Do unselected columns in a SQL Table slow down a query? For example, say I have columns A,B,C in Table X. If I use the query "Select A, B from X", would that query be any slower than if I delete column C and just do "Select * from X"

A: The performance of a query on a single table that selects all rows is pretty much driven by the I/O cost.  The I/O cost, in turn, is based on the number of data pages read by the query.
In general, having an additional column will increase the size of rows.  Fewer rows fit on fewer pages, so the query could be a bit faster.
Now for caveats.  Here are some:

*

*If C is a varchar that is always NULL, it occupies no extra space.

*If C is varchar(max) (or really large) it might be stored on a separate data page.

*If an index exists with (A, B) (in either order), then the query should use the index.  Because the index covers the query, the number of data pages is irrelevant.

*SQL Server does look aheads on I/O and can interleave I/O with other processing.  So, you might not notice the additional CPU time spend reading the data pages.

I wouldn't be inclined to simply remove columns to speed up such a query, unless the columns are not being used.  The increase in speed -- if any -- is likely to be small.  But there may exist cases where that would be a good idea from a performance perspective.


Q: Offset size and overlay of plots in R I have two plots that I would like to overlay in a particular way. Instead of side by side like when using par(), I would like one to sit inside the other, but be about a quarter the size.
More details: one of my plots is a map, another is a scatterplot with colored quadrants. The colored quadrants represent the colors plotted onto the map, so I would like to inset it nicely in the same plot as the map so that it serves as a legend.
Thanks in advance

A: Here's an example, although the links in comments point to similar approaches.
Grab a shapefile:
download.file(file.path('http://www.naturalearthdata.com/http/',
                        'www.naturalearthdata.com/download/50m',
                        'cultural/ne_50m_admin_1_states_provinces_lakes.zip'),
              {f <- tempfile()})
unzip(f, exdir=tempdir())

Plotting:
library(rgdal)
shp <- readOGR(tempdir(), 'ne_50m_admin_1_states_provinces_lakes')
plot(subset(shp, admin=='Australia'),
     col=sample(c('#7fc97f', '#beaed4', '#fdc086', '#ffff99'),
                9, repl=TRUE))
opar <- par(plt=c(0.75, 0.95, 0.75, 0.95), new=TRUE)
plot.new()
plot.window(xlim=c(0, 1), ylim=c(0, 1), xaxs='i', yaxs='i')
rect(0, 0, 0.5, 0.5, border=NA, col='#7fc97f')
rect(0.5, 0, 1, 0.5, border=NA, col='#beaed4')
rect(0, 0.5, 0.5, 1, border=NA, col='#fdc086')
rect(0.5, 0.5, 1, 1, border=NA, col='#ffff99')
points(runif(100), runif(100), pch=20, cex=0.8)
box(lwd=2)
par(opar)

See plt under ?par for clarification.

A: This is how I did it in the past
grid.newpage()
vp <- viewport(width = 1, height = 1)
submain <- viewport(width = 0.9, height = 0.9, x = 0.5, y = 1,just=c("center","top"))
print(p, vp = submain)
subvp2 <- viewport(width = 0.2, height = 0.2, x = 0.39, y = 0.35,just=c("right","top"))
print(hi, vp = subvp2)
subvp1 <- viewport(width = 0.28, height = 0.28, x = 0.0, y = 0.1,just=c("left","bottom"))
print(ak, vp = subvp1)

in my case p, ak and hi were gg objects (maps created with ggplot) and I was inserting a small version of each near the main use map (p) - as it is typically done


Q: How to automatically add R^2 to a graph with facet wrap using ggplot2? I am trying to add R^2 values to each facet in a ggplot2 graph. This is the code I have so far and this is what the graph looks like currently.
ggplot(BB_new, aes(x=Date, y=pH, color=Treatment)) +
  geom_point(pch=19, size=1,alpha = 1)+
  geom_smooth(aes(color=NULL), method = "lm", formula = y ~ x + I(x^2), se = FALSE) +
  theme_classic()+ theme(legend.title = element_blank())+
  theme(legend.position = c(0.9,0.93))+
  scale_color_manual(labels = c("Reference"),
  values = c("coral1"))+
  facet_wrap(~Hor) + ylim(2.5, 6)


Q: htc files: Why not to use them? I am developing a web application that aims to give a desktop feeling for the end user. That means I need a cross-browser feeling to the application (who doesn't? eheh).
So, I found about .htc files, for working around some IE tweaks (doesn't support border-radius yet, for example). My doubt is: Why isn't everyone using them? Does it come with some problems I am ignoring? From the place I am seeing, it appears to be almost the holy grail for the front-end programmers...

A: Quoting Wikipedia:

HTML Components (HTCs) are a
  nonstandard mechanism to implement
  components in script as Dynamic HTML
  (DHTML) "behaviors"[1] in the
  Microsoft Internet Explorer web
  browser. Such files typically use an
  .htc extension.
An HTC is typically an HTML file (with
  JScript / VBScript) and a set of
  elements that define the component.
  This helps to organize behavior
  encapsulated script modules that can
  be attached to parts of a Webpage DOM.

In two paragraphs, the following are mentioned:

*

*Internet Explorer

*JScript

*VBScript

*nonstandard

I think it's obvious why not everybody is using this technology.

A: How to use border-radius.htc with IE to make rounded corners

The server has to server the HTC with the correct MIME type (text/x-component)

That alone is enough to stop JavaScript frameworks such as jQuery or MooTools from being able to use them. The dependency on configuring anything a server in order to get client-side functionality working is beyond unacceptable.
It's a real pity though, htc files really are capable of a lot of interesting things.


Q: Return indexes of xRange in Dygrpahs Is it possible to retrieve the indexes of the visible xRange in Dygraphs? xAxisRange() returns the value of the low end and high end. Something similar how highlightCallback returns a "row".
I'm using dygraphs 1.1.1


Q: Print list from a dataframe based on another columns value I would like to slice the dataframe according to conditions. I want to keep the area name where the length of codes are 5 or 3.
The dataframeAreaCode is as bellowed
    codes   area
0   113     Leeds
2   115     Nottingham
3   116     Leicester
... ... ...
596 1985    Warminster
597 1986    Bungay
598 1987    Ebbsfleet

*

*This is the code I wrote, but it didn't work.

# print([AreaCode['codes']>4])
for i in AreaCode['codes']:
    if len(i)>4:
        print(AreaCode['area'][i])


Q: vue 3 Property '...' does not exist on type export default {
    data() {
        return {
            isLoading: false
        };
    },
    methods: {
        async showMore(parentId) {
            if (this.isLoading) return;
            this.isLoading = true;
            await this.someAction({ parentId });
            this.isLoading = false;
        }
    }
}

This code give error: Property 'isLoading' does not exist on type

A: Need to use defineComponent wrapper
export default defineComponent({
    ...
});


Q: Integration Testing a rails API using devise_token_auth for authenticaton and cancancan for authorization using Rspec I have a rails-api application that I'm testing using Rspec. The Application uses devise_token_auth gem for authentication and cancancan gem for authorization.
devise_token_auth requires that the client include these authentication headers in every request:
access-token, client, expiry, uid. These headers are available in a response after successful authentication using email and password.
I have decided to use a solution provided in this answer to set these headers during testing.
In ability.rb I have this:
## models/ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
   if user.role? :registered
     can :create, Post, user_id: user.id
     can :update, Post, user_id: user.id
     can :destroy, Post, user_id: user.id
     can :read, Post
   end
  end
end

posts#show action in PostsController looks like this:
## controllers/posts_controller.rb

class PostsController < ApplicationController
  before_action :authenticate_user!
  load_and_authorize_resource

  def show
    render json: @post
  end
end

I have rescued CanCan::AccessDenied error to render a json message and a status of 403 forbidden in ApplicationController
rescue_from CanCan::AccessDenied do |exception|
  render json: {"message" => "unauthorized"}.to_json, :status => 403
end

I have this in spec/support/session_helper.rb
module SessionHelper
 def retrieve_access_headers

 ##I have a user with these credentials and has a "registered" role. in the the test db.

   post "/auth/sign_in", params: {:email => "registered_user@gmail.com", :password => "g00dP@ssword"}, headers: {'HTTP_ACCEPT' => "application/json"}

##These two pass
expect(response.response_code).to eq 200
expect(response.body).to match(/"email": "registered_user@gmail.com"/)

     access_headers = {"access-token" => response.headers["access-token"],
     "client" => response.headers["client"],
     "expiry" => response.headers["expiry"],
     "uid" => response.headers["uid"],
     "token-type" => response.headers["token-type"],
     'HTTP_ACCEPT' => "application/json"
   }

  return access_headers
 end

end
I have this in spec/support/requests_helper.rb
module RequestsHelper
  def get_with_token(path, params={}, headers={})
   headers.merge!(retrieve_access_headers)
   get path, params: params, headers: headers

   #### this outputs the expected headers on a json string and they seem fine ####
   puts "headers: "+headers.to_json
  end
end

I have included the two helpers in rails_helper.rb as shown below:
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

RSpec.configure do |config|
   config.include SessionHelper, type: :request
   config.include RequestsHelper, type: :request
end

Finally I have a request spec in spec/request/posts/show_spec.rb
require 'rspec/its'
require 'spec_helper'
require 'rails_helper'

RSpec.describe 'GET /posts/:id', :type => :request do

    let(:post) {create(:post)}
    let(:id) {post.id}
    let(:request_url) {"/posts/#{id}"}

  context 'with a registered user' do
   it 'has a status code of 200' do
     get_with_token request_url
     expect(response).to have_http_status(:success)
   end
  end
end

I expect this to pass but it fails with message:
Failure/Error: expect(response).to have_http_status(:success)
   expected the response to have a success status code (2xx) but it was 403

The application works as expected on a browser.
What I'm a doing wrong?


Q: how to draw curve edge between nodes more beautiful?
I want to draw pre/post-order threaded binary tree like the in-order threaded binary tree's picture above(from wiki threaded binary tree page).
I tried the code below, however the edges C->B, E->F, H->G are quite different from origin picture. I read the tkz&pgf manual, but not find some method to make the edges as beautiful as origin picture.
\documentclass[10pt, compress,xcolor=x11names,UTF8, aspectratio=169,border=2pt,tikz]{standalone}
% \documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{xeCJK}
%\setCJKmainfont{微软雅黑}
\setCJKmainfont{Hei}

\XeTeXlinebreaklocale "zh"          % Following set to break line automatically.
\XeTeXlinebreakskip = 1pt plus 1pt

\usetikzlibrary{arrows,automata,positioning,trees,calc,positioning}
\tikzset{
    every picture/.style={
        semithick,shorten >=1pt,>=stealth',node distance=4em,
        every state/.style={minimum size=2em,align=center},
        accepting/.style={double distance=.1em,outer sep=\pgflinewidth}
    }
}

\begin{document}

\begin{tikzpicture}[smooth]

    \node[state]   (F)                                {$F$};

    \node[state]   (B)  [below left=2em and 2.5em of F]  {$B$};
    \node[state]   (G)  [below right=2em and 2.5em of F]  {$G$};

    \node[state]   (A)  [below left=1.5em and 1em of B]  {$A$};
    \node[state]   (D)  [below right=1.5em and 1em of B]  {$D$};
    \node[state]   (I)  [below right=1.5em and 1em of G]  {$I$};

    \node[state]   (C)  [below left=1.5em and 0.6em of D]  {$C$};
    \node[state]   (E)  [below right=1.5em and 0.6em of D]  {$E$};
    \node[state]   (H)  [below left=1.5em and 0.6em of I]  {$H$};

    \path[->]   (F) edge              (B)
                (F) edge              (G)

                (B) edge              (A)
                (B) edge              (D)
                (G) edge              (I)

                (D) edge              (C)
                (D) edge              (E)
                (I) edge               (H)

                (A) edge [->,dashed, out=-60,in=-110]            (B)
                (C) edge [->,dashed, out=-130,in=-85,looseness=1.5]           (B)
                (C) edge [->,dashed, out=-50,in=-100,looseness=1.5]           (D)
            (E) edge [->,dashed, out=-120,in=-80,looseness=1.5]           (D)
                (E) edge [->,dashed, out=-50,in=-100]           (F)
            (G) edge [->,dashed, out=-120,in=-70]           (F)
            (H) edge [->,dashed, out=-120,in=-95,looseness=1.5]           (G)
            (H) edge [->,dashed, out=-60,in=-100,looseness=1.5]           (I)
            ;
\end{tikzpicture}

\end{document}

I just want to know how to draw curve edges like the red lines:

A: At page 280 of the Tikz & PGF manual you can find a lot of options for to[] command.
In particular, controls=⟨coordinate⟩ and ⟨coordinate⟩ adds to your path more points of control.
You can try the following
\path[->,green]
  (C) edge [->,dashed, out=-130,in=-85,looseness=1.5,controls=+(200:1.5) and +(-40:1)] (B)
  (E) edge [->,dashed, out=-70,in=-100,controls=+(-30:1.7) and +(240:1.3)] (F)
  (H) edge [->,dashed, out=-120,in=-95,looseness=1.5,controls=+(240:1.5) and +(260:.7)]  (G);

where the controls are given by polar coordinates (angle:radius) relative respectively to the first end the second node of the edge.

Enjoy yourself to find the best path!

A: More freedom with bezier curves en lieu de edges:
\documentclass[10pt, compress,xcolor=x11names,UTF8, aspectratio=169,border=2pt,tikz]{standalone}
% \documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
%\usepackage{xeCJK}
%%\setCJKmainfont{微软雅黑}
%\setCJKmainfont{Hei}
%
%\XeTeXlinebreaklocale "zh"          % Following set to break line automatically.
%\XeTeXlinebreakskip = 1pt plus 1pt

\usetikzlibrary{arrows,automata,positioning,trees,calc,positioning,topaths}
\tikzset{
    every picture/.style={
        semithick,shorten >=1pt,>=stealth',node distance=4em,
        every state/.style={minimum size=2em,align=center},
        accepting/.style={double distance=.1em,outer sep=\pgflinewidth}
    }
}

\begin{document}

\begin{tikzpicture}[smooth]

    \node[state]   (F)                                {$F$};

    \node[state]   (B)  [below left=2em and 2.5em of F]  {$B$};
    \node[state]   (G)  [below right=2em and 2.5em of F]  {$G$};

    \node[state]   (A)  [below left=1.5em and 1em of B]  {$A$};
    \node[state]   (D)  [below right=1.5em and 1em of B]  {$D$};
    \node[state]   (I)  [below right=1.5em and 1em of G]  {$I$};

    \node[state]   (C)  [below left=1.5em and 0.6em of D]  {$C$};
    \node[state]   (E)  [below right=1.5em and 0.6em of D]  {$E$};
    \node[state]   (H)  [below left=1.5em and 0.6em of I]  {$H$};

    \draw[->,dashed] (H.south west) .. controls (0.5,-3.7) and (1.5,-2.7) .. (G.south);
\end{tikzpicture}

\end{document}


Q: Text LCD doesn't function normally on mixed-signal PCB? I have power supply, analog part and microcontroller part on one 2-layer PCB board, very simple. The LCD is on the microcontroller part. It works normally when I have it on a separate board with only the microcontroller, but when I put it in this board, the LCD only displays black dots, not text.
I have tried a few times but it still gives me the same result. I was wondering whether my PCB has any problems? Is it a grounding or decoupling issue? Or something else? Please take a look at my PCB and give me some advice.
[
For more information, the power supply comes from a 7805 (on the Left Side of the Board). It drives a Cypress 27443 PSoC mcu, 1 INA126 Instrumentation Amplifier and 2 OPA4137 Op Amps. However I didn't put in the OPA when testing the LCD. The bottom part of the board is for the Amplifiers.


Q: How to get search results in SharePoint (Office 365 E3)?
I have a problem with documents and pages search feature. Here's what I've done:

*

*Created a trial account of Office 365 E3 based on default .onmicrosoft.com domain name:

Office 365 E3 Microsoft Kaizala Pro Whiteboard (Plan 2)
  Information Protection for Office 365 - Standard Insights by
  MyAnalytics To-Do (Plan 2) Microsoft Forms (Plan E3)
  Microsoft Stream for O365 E3 SKU Microsoft StaffHub Flow for
  Office 365 PowerApps for Office 365 Microsoft Teams
  Microsoft Planner Sway Yammer Enterprise Azure Rights
  Management The latest desktop version of Office Skype for
  Business Online (Plan 2) Office for the web SharePoint Online
  (Plan 2) Exchange Online (Plan 2)

*Created a communication site and added a couple of word documents, links, web pages.

*Configured the site as follow:

Settings
 Site Information
  View all site settings
   Search and Offline Availability
    Allow this site to appear in search results? -> **Yes**
    This site contains fine-grained permissions. Specify the site's ASPX page indexing behavior: -> **Always index all Web Parts on this site**
    Reindex site

Documents
 Library Settings
  Advanced Settings
   Allow items from this document library to appear in search results? -> **Yes**
   Allow non-default views from this list to appear in search results? -> **Yes**
   Reindex Document Library

*Performed search on the main site's page and on the Documents page with a result:
We found 0 results for document here or No items match your search

*I spent a lot of time googling and did not finding a solution. I've also read questions and answers on this resource, but have not find solution that could help.
Could you please help me with this issue?

A: It didn't work along 5 hours I was playing with it. But when I've finished playing with it, went to bed and returned to it again 11 hours later it turned out working. I don't understand why Reindex Site and Reindex Document Library buttons did not help to reindex site's and library's contents in a half an hour at least, but took so much time.
I've been configuring also

 SharePoint admin center
  Search
   Authoritative pages
   Search Center Settings

 SharePoint
  Site Settings
   Site Features
    SharePoint Server Standard Site features -> Active
   Regional Settings
    Time Zone -> UTC+02:00

But unsure it helped. Maybe crawl schedule plays the role.


Q: Ruby on Rails - Scope of Instance Variables with Partial Views I do not understand how to use instance variable properly with partial
views, I am hoping someone here can enlighten me. For example:
class MainController < ApplicationController

  def index
    @item_list = Item.find_all_item
  end

  def detail_display
    @current_selected = @item= Item.find(params[:id])
      redirect_to :action => :index
  end
end

detail_display is invoked when the user clicks on an item in the list.
The variable @current_selected is not available to the partial view
invoked when the index is redirected to. How can I remedy this?
Thank you

A: When you do a redirect, the browser sends an entirely new request, so all of the data from the previous request is inaccessible. You probably don't want to be doing a redirect here; no amount of scope will help you when you're looking at separate runs through your controller.
Think about your design a little bit - what are you trying to do? If the selection is something sticky, maybe it should go in the session. If the change is only in a partial, maybe you should use an Ajax call. Maybe the solution is as simple as rendering the index template instead of redirecting to the index action.


Q: Script to position chart misaligns when sheet isn't active? I have a script that essentially renders/updates an entire page, including two charts on it. These charts are positioned dynamically using the .top property. I write my scripts intentionally independent of the users currently selected sheet, so there is no .Select or .Activate here.
This is the expected result, which works fine when the sheet is active:

Notice the Immediate window in the bottom-right. This debug shows the calculation that determined what each chart's .Top property is, which determines the vertical position.
The first (Spending) chart's .Top property:
Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Top = _
        Sheets("Overview").Shapes.Range(Array("Add_Category_Button")).Top + 22

Debug.Print "1st:  " & _
        Sheets("Overview").Shapes.Range(Array("Add_Category_Button")).Top & _
        " + 22" & _
        " = " & _
        Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Top
' Note: The Add_Category_Button.Top property is consistent and doesn't change.

The second (Income) chart's .Top property:
Sheets("Overview").Shapes.Range(Array("Earning_Chart")).Top _
        = Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Top + _
            Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Height

Debug.Print "2nd:  " & _
        Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Top & _
        " + " & _
        Sheets("Overview").Shapes.Range(Array("Spending_Chart")).Height & _
        " = " & _
        Sheets("Overview").Shapes.Range(Array("Earning_Chart")).Top

The second chart's position is determined by the bottom (.Top + .Height) of the first chart. They stack directly on top of eachother.
However, when I run this script while on a different sheet, this is the result:

First chart aligns fine, but the second one is miscalculated.
My confusion is, looking at the debug, the values it retrieves to calculate the .Top are correct, but the result isn't.
Also, when I run this function on each sheet, they consistently deliver unique results per sheet:

One sheet even messed with the 1st chart calculation.
What part of my code is relying on the currently selected sheet? I don't see anything, so it may be some sort of Excel behavior I don't understand.
Edit
Here's the code used to place the Add_Category_Button shape, which is the only other context there is regarding positioning the charts. I don't see how this could be useful but it was requested.
Sheets("Overview").Shapes.Range(Array("Add_Category_Button")).Top = _
        Sheets("Overview").Range("B" & Functions.GetCategoryCount + _
        Functions.GetAccountCount + 6).Top + 4

The GetCategoryCount and GetAccountCount functions run a CountA worksheet function on a range inside of another sheet, and return that value. Throughout the screenshots provided, those numbers have been the same each time, so it wouldn't relate to the odd positioning issues.
Note: The CountA functions are ran without 'selecting' any other sheets or ranges, so the context of the VBA interpreter doesn't change.
Other than that information, none of the rest of the code relates to positioning the charts, so I don't see a reason to dump it here.

A: It looks like the two sheets in your example are at different zoom levels, theorizing this may be an excel bug:
Have you tried with the zoom levels set the same on the active sheet and the sheet containing the plot? If that works you could try getting the location of two vertically adjacent cells on both sheets and then using the difference of the .top values as the 'row height' on each sheet and using the ratio between the active sheet and the target plot's sheets row height as a conversion factor.
Another thought (an ugly kludge, since the row height difference is probably not accurate enough) is that you could turn application.screenupdating off (if it's not already 'false'), then create a plot on the active page and get its height and width, then compare that to the height and width of a new plot on the target sheet (and use that for the conversion factor).

A: I think it has something to do with not updating "graphically", try making the graph(s) invisible at the beginning of the code and visible again at the end:
With Sheets("Overview").ChartObjects("Spending_Chart")
    .Visible = False
    'Do all your stuff including setting the .Top
    .Visible = True
End With

A: Hard to say without more of your code. Your snippet works fine on my sample workbook. I don't think this is a code problem as much as an Excel/VBA bug you are hitting. More on that below.
One quick comment up front... I don't like your syntax of Shapes.Range(Array("Add_Category_Button")). I would prefer the shorter Shapes("Add_Category_Button") but both work the same for me.
Here is my test routine:
Sub my_test()
    Dim i As Integer

    For i = 1 To ThisWorkbook.Sheets.Count
        ThisWorkbook.Sheets(i).Activate

        Debug.Print ActiveSheet.Name
        Sheets("Overview").Shapes("Pie_Chart").Top = _
            Sheets("Overview").Shapes("Add_Category_Button").Top + 22

        Debug.Print "1st:  " & _
            Sheets("Overview").Shapes("Add_Category_Button").Top & _
            " + 22 = " & _
            Sheets("Overview").Shapes("Pie_Chart").Top

        Sheets("Overview").Shapes("Column_Chart").Top = _
            Sheets("Overview").Shapes("Pie_Chart").Top + _
            Sheets("Overview").Shapes("Pie_Chart").Height

        Debug.Print "2nd:  " & _
            Sheets("Overview").Shapes("Pie_Chart").Top & _
            " + " & _
            Sheets("Overview").Shapes("Pie_Chart").Height & _
            " = " & _
            Sheets("Overview").Shapes("Column_Chart").Top
    Next i
End Sub

And my result:
Overview
1st:  64 + 22 = 86
2nd:  86 + 216 = 302
Interval
1st:  64 + 22 = 86
2nd:  86 + 216 = 302
1-16 to 1-14
1st:  64 + 22 = 86
2nd:  86 + 216 = 302
1-17 to 1-15
1st:  64 + 22 = 86
2nd:  86 + 216 = 302
Control
1st:  64 + 22 = 86
2nd:  86 + 216 = 302

I tried using different view percentages and got consistent results, though the numbers above changed any time I altered the view percentage on the Overview sheet.
I did find I could create some wrong results if I had 2 windows of the same workbook open via View > New Window:
Interval
1st:  75.33331 + 22 = 114.6666
2nd:  114.6666 + 258.5001 = 445.3889
1-16 to 1-14
1st:  75.33331 + 22 = 114.6666
2nd:  114.6666 + 310.5001 = 508.9445
1-17 to 1-15
1st:  75.33331 + 22 = 114.6666
2nd:  114.6666 + 374.0557 = 584.0556
Control
1st:  75.33331 + 22 = 114.6666
2nd:  114.6666 + 449.1668 = 676.5002

In my case, I think the height of the chart was changing after setting the .top property. If you have more than one window or form open, I could imagine that you could have a similar issue. This was very finicky and hard to replicate, but I suspect it has to do with situations where .top was changed with different windows and view percentages involved. When I just had one window and no forms my results were solid.
In my file, the chart height and width seemed to be altered as well, and I was seeing issues where the chart rendered improperly (for example, the selection box was a different size than the chart as displayed, or part of the chart was truncated). This is why I think this may be a bug.
The rendering errors always reset when I reset the chart size, so maybe try also setting the height/width in your code?
    Sheets("Overview").Shapes("Add_Category_Button").Top = 58
    Sheets("Overview").Shapes("Add_Category_Button").Height = 22
    Sheets("Overview").Shapes("Pie_Chart").Height = 200
    Sheets("Overview").Shapes("Pie_Chart").Width = 300
    Sheets("Overview").Shapes("Column_Chart").Height = 200
    Sheets("Overview").Shapes("Column_Chart").Width = 300


Q: How can I label each equation in a row? I use cases and I tend to label each equation in a row, for example in first case I  want to label each equation (1) and (2), and second case I want to label (3) and (4). How can I do this ? Any help is appreciated.

Lấy $ U,V \in \mathcal{T} $. Khi đó
        $\begin{cases}
            U \cap X \in \mathcal{T}_1 \\
            U \cap Y \in \mathcal{T}_2
        \end{cases}$ và
        $ \begin{cases}
        V \cap X \in \mathcal{T}_1  \\
        V \cap Y \in \mathcal{T}_2
        \end{cases} $

A: You can insert the equation numbers manually in the following way:

\documentclass{article}

\usepackage{amsmath}

\newcommand{\manualeqnum}{\refstepcounter{equation}\mbox{\upshape(\theequation)}}

\begin{document}

Some text $U, V \in \mathcal{T}$. Then also
$\begin{cases}
  U \cap X \in \mathcal{T}_1 & \manualeqnum \\
  U \cap Y \in \mathcal{T}_2 & \manualeqnum \label{eq:first}
\end{cases}$ as well as
$ \begin{cases}
  V \cap X \in \mathcal{T}_1 & \manualeqnum \\
  V \cap Y \in \mathcal{T}_2 & \manualeqnum \label{eq:second}
\end{cases}$.

See, for example, equations~\eqref{eq:first} and~\eqref{eq:second}.

\end{document}

You may have to play around with the spacing between the equation numbers and the rest of the text. In most cases it's actually clearer to use the numcases environment:

\documentclass{article}

\usepackage{amsmath,cases}

\begin{document}

Some text $U, V \in \mathcal{T}$. Then also
\begin{numcases}{}
  U \cap X \in \mathcal{T}_1 \\
  U \cap Y \in \mathcal{T}_2 \label{eq:first}
\end{numcases}
as well as
\begin{numcases}{}
  V \cap X \in \mathcal{T}_1 \\
  V \cap Y \in \mathcal{T}_2. \label{eq:second}
\end{numcases}

See, for example, equations~\eqref{eq:first} and~\eqref{eq:second}.

\end{document}


Q: building PyMC3 model incorporating different measurements I am trying to incorporate different types and replicates of measurements into one model in PyMC3.
Consider the following model: P(t)=P0*exp(-kBt) where P(t), P0, and B are concentrations. k is a rate. We measure P(t) at different times and B once, all through counting of particles. k is the parameter of interest we are trying to infer.
My question has two parts:
(1) How to incorporate measurements on P(t) and B into one model?
(2) How to use a variable number of replicate experiments to inform on the value of k?
I think I can answer part (1), but am unsure about whether it is right or done in the right flavour. I failed to generalise the code to include a variable number of replicates.
For one experiment (one replicate):
ts=np.asarray([time0,time1,...])
counts=np.asarray([countforB,countforPattime0,countforPattime1,...])
basic_model = pm.Model()
with basic_model:
    k=pm.Uniform('k',0,20)
    B=pm.Uniform('B',0,1000)
    P=pm.Uniform('P',0,1000)
    exprate=pm.Deterministic('exprate',k*B)
    modelmu=pm.math.concatenate(B*(np.asarray([1.0]),P*pm.math.exp(-exprate*ts)))
    Y_obs=pm.Poisson('Y_obs',mu=modelmu,observed=counts))

I tried to include different replicates along the lines of the above, but to no avail:
...
    k=pm.Uniform('k',0,20) # same within replicates
    B=pm.Uniform('B',0,1000,shape=numrepl) # can vary between expts.
    P=pm.Uniform('P',0,1000,shape=numrepl) # can vary between expts.
    exprate=???
    modelmu=???

A: Multiple Observables
PyMC3 supports multiple observables, that is, you can add multiple RandomVariable objects to the graph with the observed argument set.
Single Trial
In your first case, this would lend some clarity to the model:
counts=[countforPattime0, countforPattime1, ...]

with pm.Model() as single_trial:
    # priors
    k = pm.Uniform('k', 0, 20)
    B = pm.Uniform('B', 0, 1000)
    P = pm.Uniform('P', 0, 1000)

    # transformed RVs
    rate = pm.Deterministic('exprate', k*B)
    mu = P*pm.math.exp(-rate*ts)

    # observations
    B_obs = pm.Poisson('B_obs', mu=B, observed=countforB)
    Y_obs = pm.Poisson('Y_obs', mu=mu, observed=counts)

Multiple Trials
With this additional flexibility, hopefully it makes the transition to multiple trials more obvious.  It should go something like:
B_cts = np.array(...) # shape (N, 1)
Y_cts = np.array(...) # shape (N, M)
ts = np.array(...)    # shape (1, M)

with pm.Model() as multi_trial:
    # priors
    k = pm.Uniform('k', 0, 20)
    B = pm.Uniform('B', 0, 1000, shape=B_cts.shape)
    P = pm.Uniform('P', 0, 1000, shape=B_cts.shape)

    # transformed RVs
    rate = pm.Deterministic('exprate', k*B)
    mu = P*pm.math.exp(-rate*ts)

    # observations
    B_obs = pm.Poisson('B_obs', mu=B, observed=B_cts)
    Y_obs = pm.Poisson('Y_obs', mu=mu, observed=Y_cts)

There might be some extra syntax stuff to get the matrices multiplying correctly, but this at least includes the correct shapes.

Priors
Once you get that setup working, it would be in your interest to reconsider the priors. I suspect you have more information about the typical values for those than is currently included, especially since this seems like a chemical or physical model.
For instance, right now the model says,

We believe the true value of B remains fixed for the duration of a trial, but across trials is a completely arbitrary value between 0 and 1000, and measuring it repeatedly within a trial would be Poisson distributed.

Typically, one should avoid truncations unless they are excluding meaningless values. Hence, a lower bound of 0 is fine, but the upper bounds are arbitrary.  I'd recommend having a look at the Stan Wiki on choosing priors.


Q: Many to many getting "is invalid" error in Rails I am trying to do a many-to-many relation but I get :roles=>[{:error=>:invalid}] when trying to save.
Models
class User < ApplicationRecord
  has_many :user_roles, dependent: :destroy
  has_many :roles, through: :user_roles
end

class Role < ApplicationRecord
  has_many :children, :class_name => "Admin::Role", foreign_key: "parent_id"
  belongs_to :parent, :class_name => "Admin::Role"
  has_many :user_roles, dependent: :destroy
  has_many :users, through: :user_roles
end

class Admin::UserRole < ApplicationRecord
  belongs_to :user
  belongs_to :role
end

Controller
def new
  @user = User.new
end

def create
  @user = User.new(user_params)
  respond_to do |format|
    if @user.save
      redirect_to users_url
    end
  end
end

def user_params
  params.require(:user).permit(:role_ids => [])
end

_form.html.erb
form_with(model: user) do |form|
    form.collection_select(:role_ids, Roles.all, :id, :title, multiple: "multiple")
end

Params log
"user"=>{"role_ids"=>["", "1"]}


Q: R: Data Quality Check: Zip Code matching the City Can someone help me to realize an idea in R?
I want to achieve, that when R gets an Input File with e.g. a list of companies and their address, it will check wether the zip Code fits to the City for each Company. I have a list of all cities and Zip codes from a certain Country. How can I implement the list into an if sentence?
Did someone Programm something similar before?
Thanks for ur help!
Sandra

A: Just a quick example of what one could do. It is, however, probably better to use fuzzy matching for your cities.
# City codes (all city codes can be found at https://www.allareacodes.com/)
my_city_codes <- data.frame(code = c(201:206),
                            cities = c("Jersey City, NJ", "District of Columbia", "Bridgeport, CT", "Manitoba", "Birmingham, AL", "Seattle, WA"),
                            stringsAsFactors = FALSE)

# Function for checking if city/city-code matches those in the registries
adress_checker <- function(adress, citycodes) {
  # Finding real city
  real_city <- my_city_codes$cities[which(adress$code == my_city_codes$code)]

  # Checking if cities are the same
  if(real_city == adress$city) {
    return("Correct city")
  } else {
    return("Incorrect city")
  }
}

# Adresses to check
right_city <- data.frame(code = 205, city = c("Birmingham, AL"), stringsAsFactors = FALSE)
wrong_city <- data.frame(code = 205, city = c("Las Vegas"), stringsAsFactors = FALSE)

# Testing function
adress_checker(right_city, my_city_codes)
[1] "Correct city"
adress_checker(wrong_city, my_city_codes)
[1] "Incorrect city"


Q: Drawbacks to nesting of child windows? Just for fun I'm developing a native Win32 port of Mozilla XUL. XUL allows to create complex nested structures of all kinds of layout boxes (hbox, vbox, grid, deck..). For my Windows implemenation it would be convenient to implement them as STATIC child windows. Because then I can position their child windows using x & y offsets independent of the position of the parent box.
However, this approach may lead to certain windows having a lot of nested child windows. And I wonder if there would be any disadvantages to such a situation. Does anyone here know?

A: I've been down this path, and I don't recommend you actually make deep hierarchies of windows.  Lots of Windows helper functions (e.g., IsDialogMessage) work better with "traditional" layouts.  Also, windows in Windows are relatively heavy objects, mostly for historical reasons.  So if you have tons of objects, you could run into limitations, performance problems, etc.
What I've done instead is to represent the deeply-nested layout as a tree of regular C++ objects that parallels the flatter hierarchy of actual windows.  Some nodes of the object hierarchy have the HWNDs of the "real" windows they represent.  You tell the hierarchy to lay out, and the nodes apply the results to the corresponding windows.
For example, the root of the hierarchy may represent a dialog window, and the leaf nodes represent the child windows.  But the hierarchy has several layers of non-window objects in between that know about layout.

A: A rough take on this:

*

*memory overhead for the window management on application- and os-side

*reduced speed due to calls to external library / os which do way more for windows than needed for your application

*possibly quite some overhead through long window message paths in complex layouts

It probably depends on wether you want a very fast implementation and do efficient buffered drawing by yourself or want it to work more reliably and with less time invested.


Q: Create VectorDrawable from String (path)? Is there a way to get SVG path string from the API and create VectorDrawable dynamically?
I have been trying to do this for hours without success. Even more, all (!) examples on the Internet explain creating VectorDrawable from XML resources.
In my case, XML resource file is pointless as I am trying to fetch SVG path from the Internet API.

A: Inflating a drawable from a XML file instead of from resources is actually impossible, because the drawable will try to cast the XmlPullParser to XmlResourceParser which is only implemented by private class XmlBlock.Parser. Even that parser is only used for parsing binary XML files. I tried every possible way of doing this without reflection, it's impossible.
So I found documentation on binary XML files and learned how they were made, helped with some compiled binary XML vector drawable files I had. The documentation dates back to 2011 and is still valid, I guess it will most likely remain this way, so future compatibility isn't an issue.
A previous version was tested for more than a thousand paths, without problem. The new version posted here should work just as well. (Previous versions are available in the answer history) Compared with loading a drawable directly from resources, I found that there's an average of 14 microseconds or so of extra loading, not noticeable.
Here's the code:
public class VectorDrawableCreator {

    private static final byte[][] BIN_XML_STRINGS = {
            "width".getBytes(),
            "height".getBytes(),
            "viewportWidth".getBytes(),
            "viewportHeight".getBytes(),
            "fillColor".getBytes(),
            "pathData".getBytes(),
            "path".getBytes(),
            "vector".getBytes(),
            "http://schemas.android.com/apk/res/android".getBytes()
    };

    private static final int[] BIN_XML_ATTRS = {
            android.R.attr.height,
            android.R.attr.width,
            android.R.attr.viewportWidth,
            android.R.attr.viewportHeight,
            android.R.attr.fillColor,
            android.R.attr.pathData
    };

    private static final short CHUNK_TYPE_XML = 0x0003;
    private static final short CHUNK_TYPE_STR_POOL = 0x0001;
    private static final short CHUNK_TYPE_START_TAG = 0x0102;
    private static final short CHUNK_TYPE_END_TAG = 0x0103;
    private static final short CHUNK_TYPE_RES_MAP = 0x0180;

    private static final short VALUE_TYPE_DIMENSION = 0x0500;
    private static final short VALUE_TYPE_STRING = 0x0300;
    private static final short VALUE_TYPE_COLOR = 0x1D00;
    private static final short VALUE_TYPE_FLOAT = 0x0400;

    /**
     * Create a vector drawable from a list of paths and colors
     * @param width drawable width
     * @param height drawable height
     * @param viewportWidth vector image width
     * @param viewportHeight vector image height
     * @param paths list of path data and colors
     * @return the vector drawable or null it couldn't be created.
     */
    public static Drawable getVectorDrawable(@NonNull Context context,
                                             int width, int height,
                                             float viewportWidth, float viewportHeight,
                                             List<PathData> paths) {
        byte[] binXml = createBinaryDrawableXml(width, height, viewportWidth, viewportHeight, paths);

        try {
            // Get the binary XML parser (XmlBlock.Parser) and use it to create the drawable
            // This is the equivalent of what AssetManager#getXml() does
            @SuppressLint("PrivateApi")
            Class<?> xmlBlock = Class.forName("android.content.res.XmlBlock");
            Constructor xmlBlockConstr = xmlBlock.getConstructor(byte[].class);
            Method xmlParserNew = xmlBlock.getDeclaredMethod("newParser");
            xmlBlockConstr.setAccessible(true);
            xmlParserNew.setAccessible(true);
            XmlPullParser parser = (XmlPullParser) xmlParserNew.invoke(
                    xmlBlockConstr.newInstance((Object) binXml));

            if (Build.VERSION.SDK_INT >= 24) {
                return Drawable.createFromXml(context.getResources(), parser);
            } else {
                // Before API 24, vector drawables aren't rendered correctly without compat lib
                final AttributeSet attrs = Xml.asAttributeSet(parser);
                int type = parser.next();
                while (type != XmlPullParser.START_TAG) {
                    type = parser.next();
                }
                return VectorDrawableCompat.createFromXmlInner(context.getResources(), parser, attrs, null);
            }

        } catch (Exception e) {
            Log.e(VectorDrawableCreator.class.getSimpleName(), "Vector creation failed", e);
        }
        return null;
    }

    private static byte[] createBinaryDrawableXml(int width, int height,
                                                  float viewportWidth, float viewportHeight,
                                                  List<PathData> paths) {
        List<byte[]> stringPool = new ArrayList<>(Arrays.asList(BIN_XML_STRINGS));
        for (PathData path : paths) {
            stringPool.add(path.data);
        }

        ByteBuffer bb = ByteBuffer.allocate(8192);  // Capacity might have to be greater.
        bb.order(ByteOrder.LITTLE_ENDIAN);

        int posBefore;

        // ==== XML chunk ====
        // https://justanapplication.wordpress.com/2011/09/22/android-internals-binary-xml-part-two-the-xml-chunk/
        bb.putShort(CHUNK_TYPE_XML);  // Type
        bb.putShort((short) 8);  // Header size
        int xmlSizePos = bb.position();
        bb.position(bb.position() + 4);

        // ==== String pool chunk ====
        // https://justanapplication.wordpress.com/2011/09/15/android-internals-resources-part-four-the-stringpool-chunk/
        int spStartPos = bb.position();
        bb.putShort(CHUNK_TYPE_STR_POOL);  // Type
        bb.putShort((short) 28);  // Header size
        int spSizePos = bb.position();
        bb.position(bb.position() + 4);
        bb.putInt(stringPool.size());  // String count
        bb.putInt(0);  // Style count
        bb.putInt(1 << 8);  // Flags set: encoding is UTF-8
        int spStringsStartPos = bb.position();
        bb.position(bb.position() + 4);
        bb.putInt(0);  // Styles start

        // String offsets
        int offset = 0;
        for (byte[] str : stringPool) {
            bb.putInt(offset);
            offset += str.length + (str.length > 127 ? 5 : 3);
        }

        posBefore = bb.position();
        bb.putInt(spStringsStartPos, bb.position() - spStartPos);
        bb.position(posBefore);

        // String pool
        for (byte[] str : stringPool) {
            if (str.length > 127) {
                byte high = (byte) ((str.length & 0xFF00 | 0x8000) >>> 8);
                byte low = (byte) (str.length & 0xFF);
                bb.put(high);
                bb.put(low);
                bb.put(high);
                bb.put(low);
            } else {
                byte len = (byte) str.length;
                bb.put(len);
                bb.put(len);
            }
            bb.put(str);
            bb.put((byte) 0);
        }

        if (bb.position() % 4 != 0) {
            // Padding to align on 32-bit
            bb.put(new byte[4 - (bb.position() % 4)]);
        }

        // Write string pool chunk size
        posBefore = bb.position();
        bb.putInt(spSizePos, bb.position() - spStartPos);
        bb.position(posBefore);

        // ==== Resource map chunk ====
        // https://justanapplication.wordpress.com/2011/09/23/android-internals-binary-xml-part-four-the-xml-resource-map-chunk/
        bb.putShort(CHUNK_TYPE_RES_MAP);  // Type
        bb.putShort((short) 8);  // Header size
        bb.putInt(8 + BIN_XML_ATTRS.length * 4);  // Chunk size
        for (int attr : BIN_XML_ATTRS) {
            bb.putInt(attr);
        }

        // ==== Vector start tag ====
        int vstStartPos = bb.position();
        int vstSizePos = putStartTag(bb, 7, 4);

        // Attributes
        // android:width="24dp", value type: dimension (dp)
        putAttribute(bb, 0, -1, VALUE_TYPE_DIMENSION, (width << 8) + 1);

        // android:height="24dp", value type: dimension (dp)
        putAttribute(bb, 1, -1, VALUE_TYPE_DIMENSION, (height << 8) + 1);

        // android:viewportWidth="24", value type: float
        putAttribute(bb, 2, -1, VALUE_TYPE_FLOAT, Float.floatToRawIntBits(viewportWidth));

        // android:viewportHeight="24", value type: float
        putAttribute(bb, 3, -1, VALUE_TYPE_FLOAT, Float.floatToRawIntBits(viewportHeight));

        // Write vector start tag chunk size
        posBefore = bb.position();
        bb.putInt(vstSizePos, bb.position() - vstStartPos);
        bb.position(posBefore);

        for (int i = 0; i < paths.size(); i++) {
            // ==== Path start tag ====
            int pstStartPos = bb.position();
            int pstSizePos = putStartTag(bb, 6, 2);

            // android:fillColor="#aarrggbb", value type: #rgb.
            putAttribute(bb, 4, -1, VALUE_TYPE_COLOR, paths.get(i).color);

            // android:pathData="...", value type: string
            putAttribute(bb, 5, 9 + i, VALUE_TYPE_STRING, 9 + i);

            // Write path start tag chunk size
            posBefore = bb.position();
            bb.putInt(pstSizePos, bb.position() - pstStartPos);
            bb.position(posBefore);

            // ==== Path end tag ====
            putEndTag(bb, 6);
        }

        // ==== Vector end tag ====
        putEndTag(bb, 7);

        // Write XML chunk size
        posBefore = bb.position();
        bb.putInt(xmlSizePos, bb.position());
        bb.position(posBefore);

        // Return binary XML byte array
        byte[] binXml = new byte[bb.position()];
        bb.rewind();
        bb.get(binXml);

        return binXml;
    }

    private static int putStartTag(ByteBuffer bb, int name, int attributeCount) {
        // https://justanapplication.wordpress.com/2011/09/25/android-internals-binary-xml-part-six-the-xml-start-element-chunk/
        bb.putShort(CHUNK_TYPE_START_TAG);
        bb.putShort((short) 16);  // Header size
        int sizePos = bb.position();
        bb.putInt(0); // Size, to be set later
        bb.putInt(0);  // Line number: None
        bb.putInt(-1);  // Comment: None

        bb.putInt(-1);  // Namespace: None
        bb.putInt(name);
        bb.putShort((short) 0x14);  // Attributes start offset
        bb.putShort((short) 0x14);  // Attributes size
        bb.putShort((short) attributeCount);  // Attribute count
        bb.putShort((short) 0);  // ID attr: none
        bb.putShort((short) 0);  // Class attr: none
        bb.putShort((short) 0);  // Style attr: none

        return sizePos;
    }

    private static void putEndTag(ByteBuffer bb, int name) {
        // https://justanapplication.wordpress.com/2011/09/26/android-internals-binary-xml-part-seven-the-xml-end-element-chunk/
        bb.putShort(CHUNK_TYPE_END_TAG);
        bb.putShort((short) 16);  // Header size
        bb.putInt(24);  // Chunk size
        bb.putInt(0);  // Line number: none
        bb.putInt(-1);  // Comment: none
        bb.putInt(-1);  // Namespace: none
        bb.putInt(name);  // Name: vector
    }

    private static void putAttribute(ByteBuffer bb, int name,
                                     int rawValue, short valueType, int valueData) {
        // https://justanapplication.wordpress.com/2011/09/19/android-internals-resources-part-eight-resource-entries-and-values/#struct_Res_value
        bb.putInt(8);  // Namespace index in string pool (always the android namespace)
        bb.putInt(name);
        bb.putInt(rawValue);
        bb.putShort((short) 0x08);  // Value size
        bb.putShort(valueType);
        bb.putInt(valueData);
    }

    public static class PathData {

        public byte[] data;
        public int color;

        public PathData(byte[] data, int color) {
            this.data = data;
            this.color = color;
        }

        public PathData(String data, int color) {
            this(data.getBytes(StandardCharsets.UTF_8), color);
        }

    }

}

A call to getVectorDrawable returns a VectorDrawable from a list of paths. The drawable can contain multiple paths with different colors. There are also parameters for the drawable and viewport size.
Here's an example:
List<PathData> pathList = Arrays.asList(new PathData("M128.09 5.02a110.08 110.08 0 0 0-110 110h220a109.89 109.89 0 0 0-110-110z", Color.parseColor("#7cb342")),
                    new PathData("M128.09 115.02h-110a110.08 110.08 0 0 0 110 110 110.08 110.08 0 0 0 110-110z", Color.parseColor("#8bc34a")),
                    new PathData("M207.4 115.2v-.18h-5.1l-61.43-61.43h-25.48v20.6h-6.5a11.57 11.57 0 0 0-11.53 11.53v26.09h.11c-.11.9.5 2 1.7 3.32.12.08.12.08.12.2l3.96 4-46.11 79.91c5.33 4.5 11.04 8.4 17 11.8a109.81 109.81 0 0 0 108.04 0 110.04 110.04 0 0 0 51.52-64.65c.38-1.28.68-2.57 1.1-3.78z", Color.parseColor("#30000000")),
                    new PathData("M216.28 230.24a6.27 6.27 0 0 0-.9-2.8l-31.99-55.57-10.58-18.48-19.85-34.21-15.08 15.12 18.6 32.28 10.2 17.73 30.92 53.37a5.6 5.6 0 0 0 1.97 2.12l15.42 10.5c.6.39 1.29.39 1.9.08.6-.37.9-.98.9-1.7z", Color.parseColor("#e1e1e1")),
                    new PathData("M186.98 115.02a58.9 58.9 0 0 1-30.5 51.6 58.4 58.4 0 0 1-56.7 0l18.6-32.28-15.13-15.12-62.48 108.22c-.5.9-.8 1.78-.9 2.8l-1.4 18.6c-.12.71.3 1.28.9 1.7.6.37 1.29.3 1.9-.12l15.41-10.4a7.87 7.87 0 0 0 1.97-2.07l30.92-53.53a78.74 78.74 0 0 0 77.23 0 76.65 76.65 0 0 0 16.6-12.4 79.3 79.3 0 0 0 24.07-56.89z", Color.parseColor("#f1f1f1")),
                    new PathData("M147.3 74.12h-6.43v-20.6h-25.48v20.6h-6.5a11.57 11.57 0 0 0-11.53 11.5v26.07h.11c-.11 1.02.5 2.12 1.82 3.4l23.05 23.14a8.3 8.3 0 0 0 5.75 2.38v-.07l.07.07c2.12 0 4.2-.75 5.71-2.38l23.1-23.1c1.32-1.32 1.81-2.53 1.81-3.4h.12V85.7a11.68 11.68 0 0 0-11.6-11.6zm-19.14 40.9h-.07a15.4 15.4 0 0 1 0-30.8v-.2l.07.2a15.46 15.46 0 0 1 15.31 15.38 15.46 15.46 0 0 1-15.3 15.42z", Color.parseColor("#646464")));

A: @Andre.Anzi To extend the class to support strokeColor and strokeWidth, you can try to arrange the attributes in an alphabetical order.


Q: Ionic Cordova Device UUID Hi i am developing a hybrid app using the Ionic framework and Cordova. I am looking to use the device uuid as an ID so i have added the cordova device plugin. Additionally i am using the NG-Cordova wrapper for calling my cordova plugins. However whenever i run my app in the xcode Simulator or on an actual Ipad all i get is {{uuid}} .
There does not seem to be any error message i can only assume that the Device Plugin is not working.
i have put my code below however im not sure this is the issue, Has anyone had this issue before and if so how did they work around it?
Controller:
angular.module('starter.controllers', []).controller('DashCtrl', function(
$scope, $state, $cordovaDevice) {
var init = function() {
    console.log("initializing device");
    try {
        $scope.uuid = $cordovaDevice.getUUID();
    } catch (err) {
        console.log("Error " + err.message);
        alert("error " + err.$$failure.message);
    }
};
init();

})
Html
<ion-view title="Dashboard">
  <ion-content class="padding">

Dash

    {{uuid}}
  </ion-content>
</ion-view>

app.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
    .run(function($ionicPlatform) {
        $ionicPlatform.ready(function() {
            if (window.cordova && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(
                    true);
            }
            if (window.StatusBar) {
                // org.apache.cordova.statusbar required
                StatusBar.styleDefault();
            }
        });
    }).config(function($stateProvider, $urlRouterProvider) {
        $stateProvider
        // setup an abstract state for the tabs directive
            .state('tab', {
                url: "/tab",
                abstract: true,
                templateUrl: "templates/tabs.html"
            })
            // Each tab has its own nav history stack:
            .state('tab.dash', {
                url: '/dash',
                views: {
                    'tab-dash': {
                        templateUrl: 'templates/tab-dash.html',
                        controller: 'DashCtrl'
                    }
                }
            });
        // if none of the above states are matched, use this as the fallback
        $urlRouterProvider.otherwise('/tab/dash');
    });

A: the reason behind my issue was due to using a custom build of ngCordova.
if i just the normal or Minified version of ngcordova it works perfectly.
Thanks for all the help.


Q: Docker Remote API to login to registry I am looking for documentation for docker login, I need to login to a registry to pull docker image and I need to do it remotely using docker remote APIs.
But unfortunately I am unable to find docker remote API docs, any help would be greatly appreciated.
API doc :
https://docs.docker.com/engine/reference/api/docker_remote_api_v1.19/
Thanks in advance.
Sarath Krishnan

A: you go as
 docker login your.domain.to.the.registr.without.protocol.or.port
 enter username
 enter password

now you can pull using docker pull your.domain.to.the.registr.without.protocol.or.port/youimage
Ensure your registry runs behind a SSL proxy / termination, or you run into security issues. Consider reading this in this case https://docs.docker.com/registry/insecure/


Q: Desligar o computador quando um determinado programa fechar Estou transformando um CPU antiga em um servidor de Minecraft. Ao ligar o computador, consigo via script fazer com que ele abra o servidor (iniciando um arquivo -jar), entretanto, gostaria de fazê-lo desligar assim que o programa -jar se encerrasse.
O script que tenho é esse, que só faz com que ele seja aberto
@ECHO OFF
start java -Xms1G -Xmx1G -jar minecraft_server.jar nogui
pause

Poderiam me indicar o código que faz o computador desligar assim que o "minecraft_server.jar" for fechado?

A: Para desligar o computador, você pode utilizar o comando shutdown passando como parâmetro /s, da seguinte forma:
shutdown /s

Como você deseja desligar somente depois do programa encerrar, você pode criar o seu script utilizando o parâmetro /wait do comando start, com isso o script aguarda o encerramento do programa executado pelo start.

Seu script ficaria mais ou menos da seguinte forma:
@ECHO OFF
start /wait java -Xms1G -Xmx1G -jar minecraft_server.jar nogui
shutdown /s

Assim que o java for encerrado, vai cair no comando de desligamento.

Documentações:
https://docs.microsoft.com/pt-br/windows-server/administration/windows-commands/shutdown
https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/start


Q: What is the optimal strategy when driving to my university: Wait or take alternative route and (possibly) wait? When bicycling to my university, I'm faced with a difficult decision. The situation is shown here:

I have to get to point marked with the $\times$, but in order to do so, I must cross a big road with a traffic light at both places where crossing is possible. If the first traffic light (at the bottom) is green, then there's no debate; I simply cross and go up $A$ with no waiting time at all. The choice arises when it is red (as is always the case anyway), since I can choose to wait for the first light to change, or go up a smaller road $B$ and then try to cross at the second light.
Let's assume that the two traffic lights are identical w.r.t. the percent of the time they are red (let's call this quantity $\Theta$), but that the second is phase-shifted with $\tau$ w.r.t. the first, s.t. the second changes to e.g. green a time $\tau$ after the first. The length $L$ of the paths are identical and I bicycle with a constant speed $v$ (although I suspect these last two are irrelevant to the solution). I don't know anything about the light before I arrive at it. The question then becomes

If I arrive at a random time during which the first traffic light is red, given $\Theta$ and $\tau$ (and $L$ and $v$), should I

*

*wait at the first light and go by path $A$, or should I

*go by path $B$

  in order to minimize waiting time?

The type of solution I'm looking for can better be formulated if we first look at two examples:

The $\mathbf{I}$'s represent the time during which the traffic light is red - the space in between them represent the green lights. The drawn lines represent my position if I chose to go by $B$. If I arrive at the first red light during the blue stretch, I should go by $B$; if I, on the other hand, arrive during the red stretch, I should go wait and go by $A$. As can be seen from the two scenarios $(a)$ and $(b)$ (where the lines represent my position should I choose path $B$, and where the slope is determined by $L$ and $v$), my choice depends on $\tau$, which is the only parameter that has been changed.

If we call the length of the blue strip $t_{\text{go}}$ and the length of the red strip $t_{\text{wait}}$, s.t. $t_{\text{go}}+t_{\text{wait}}=\Theta$, the solution should be of the form $$t_{\text{go}}(\tau)$$

I don't think $v$ and $L$ should play a role, since the effect of changing these can be incorporated into $\tau$, so we could probably set $v=L=1$. I'm guessing there should be a pretty simple geometric way of solving this, but for the time being it is eluding me.
Some random observations: If $v=\frac{L}{\tau}$ it doesn't matter what I choose. Also, if the second light was independent of the first, I should always go by $B$, since there I will at least have a $1-\Theta$ chance of getting a green light.
Any help is much appreciated!

A: Let's start by representing the phase of a light by the full circle, of which the first $\theta$ arc corresponds to a green light, and let $\tau$ represent the phase shift between the two lights. Let $\phi$ represent the phase shift induced by the time to go from the first light to the second light.

The picture shows in red the time when the first light is green, and in blue the time when the second light is green. If you take a point $s$ not in $[0,\theta]$, you'll be at the second light at $s+\phi$. So if you wait in front of the first light you would wait $2\pi -s$, and if you go for the second light you would wait $w(s)$ (see below).
The wait function when going to the other light is in three cases, either you arrive before the second light is green, after, or you arrive during this time.
$$
w(s) = \begin{cases}
t - (s+\phi) & \mathrm{ if }\; s+\phi <\tau\\
2\pi + \tau - (s+\phi) & \mathrm{ if }\;s+\phi >\tau + \theta\\
0 & \mathrm{ otherwise}
\end{cases}
$$
Now the strategy "let's go to the second light" is better than the "wait at the first light strategy" if and only if $\mathbb{E}[2\pi -s]$ is greater than $\mathbb{E}[w(s)]$ over $s \in ]\theta,2\pi[$ (assuming you have no additional information besides the color of the light when you arrive in front of the first light).
Edit:
I forgot some factors in my initial calculations, so the result was completely wrong. It seems that David K did things right anyway.
By the way, there's a very simple argument to see that going to the second light is always at least as good as waiting. The transformation $s \to s + \phi$ is measure-preserving, so what matters is how much of the circle is covered by its codomain; and since this area is at most $2\pi-\theta$ (which is attained when both lights are synchronized and with a phase shift of $2\pi$), this means that it cannot do worse than waiting at the first light.
(However this assumes that all lights stay green for the same amount of time, so this may not apply to the real-life example).

A: Let's choose a unit of time so that each light cycle is exactly
one unit long.
As you noticed,
if $v = \frac L\tau$ it does not matter which choice you make.
In fact, since you will arrive at the second light exactly $\frac Lv$ units of time later than you arrived at the first light
(if you choose to try the second light),
the expected waiting time at the second light will be exactly the same
as the expected waiting time of a light at the location of the first
light, but phase-shifted $\frac Lv$ units earlier than the second light,
which itself is phase-shifted $\tau$ units later than the first light.
So choosing to go to the second light is equivalent to
making an irrevocable choice to phase-shift the first light
$\tau - \frac Lv$ units later. Moreover, since phase-shifting by
any whole number of units of time has no effect,
we can say that choosing the second light is equivalent to phase-shifting
the first light by $\delta$,
where $0 \leq \delta < 1$ and there is an integer $N$
such that $N + \delta = \tau - \frac Lv$.
Let's suppose you arrive at the first light at time $t$, where
$t=0$ if the light is just turning red and $t=\Theta$ if the light
is just turning green again.
Assuming the first light is red when you arrive, $0 \leq t < \Theta$.
In addition to that constraint, there are three possible cases to consider:
\begin{align}
                         t &< \Theta + \delta - 1 \tag1 \\
\Theta + \delta - 1 \leq t &< \delta              \tag2 \\
             \delta \leq t &                      \tag3 \\
\end{align}
Which cases are even possible depends on $\Theta$ and $\delta$.
Essentially, by shifting the light cycle by $\delta$, you turn the light
green for some portion of the time when it would have been red.
Suppose the part of the cycle that was red and is now green starts at time
$\alpha$ and ends at time $\beta$.
If $\delta > 1 - \Theta$, then $\alpha = \Theta + \delta - 1$;
otherwise $\alpha = 0$, ruling out case $(1)$.
If $\delta < \Theta$, then $\beta = \delta$;
otherwise $\beta = \Theta$, ruling out case $(3)$.
If $\delta = 0$ then Case $(2)$ is ruled out (and it makes no difference
which path you take); but Case $(2)$ is possible whenever $\delta \neq 0$.
In case $(1)$, you get a green light at time $\Theta + \delta - 1$,
which is $1 - \delta$ units of time earlier than you would have gotten
without the phase shift.
In case $(2)$, the phase shift turns the light green,
and you can cross $\Theta - t$ units of time earlier than you would
have without the phase shift.
In case $(3)$, you arrived at the first light after the portion of the
light cycle that is turned green by the phase shift;
you end up crossing $\delta$ units of time later than you would have
without the phase shift.
Assuming that the distribution of your arrival time within the
light cycle is uniform, the expected change in waiting time
(positive for increased waiting, negative for decreased waiting),
given that you arrive at the first light when it is red, is therefore
\begin{align}
E[\Delta T]
&= \frac 1\Theta \int_0^\alpha (\delta - 1) \,dt
 + \frac 1\Theta \int_\alpha^\beta (t - \Theta) \,dt
 + \frac 1\Theta \int_\beta^\Theta \delta \,dt \\
&= \frac \alpha\Theta(\delta - 1)
 + \frac 1\Theta \left(\frac12 \beta^2 - \frac12 \alpha^2\right)
 - \frac{\beta - \alpha}{\Theta} \Theta
 + \frac{\Theta - \beta}{\Theta} \delta \\
&= \frac{1}{2\Theta}(\beta^2 - \alpha^2)
 + \frac \alpha\Theta(\delta - 1) + \alpha - \beta
 + \frac{\Theta - \beta}{\Theta} \delta \\
&= \frac{1}{2\Theta}(\beta^2 - \alpha^2)
 + \frac \alpha\Theta(\Theta + \delta - 1)
 + \frac{\Theta - \beta}{\Theta} (\Theta + \delta) - \Theta
\end{align}
The reason for the seemingly peculiar rearrangement of terms on the
last line of the equation above
is that we know that either $\alpha = 0$ (in which case the
term involving $\alpha$ disappears) or $\alpha = \Theta + \delta - 1$
(in which case the term becomes $\frac1\Theta (\Theta + \delta - 1)^2$);
we also know that either $\beta = \Theta$
(in which case the term involving $\beta$ disappears)
or $\beta = \delta$ (in which case that term becomes
$\Theta - \frac1\Theta \delta^2$).
We then have the following four possible answers, depending on whether
$\delta \leq 1 - \Theta$ (that is, $\alpha = 0$) and on whether
$\delta \geq \Theta$ (that is,  $\beta = \Theta$):
Case $\Theta \leq \delta \leq 1 - \Theta$:
$$E[\Delta T] = -\frac{\Theta}{2}.$$
Case $\delta \leq 1 - \Theta, \delta < \Theta$:
$$E[\Delta T] = -\frac{\delta^2}{2\Theta}.$$
Case $\delta > 1 - \Theta, \delta \geq \Theta$:
$$E[\Delta T] = \frac{(\Theta + \delta - 1)^2 - \Theta^2}{2\Theta}.$$
Case $1 - \Theta < \delta < \Theta$:
$$E[\Delta T] = \frac{(\Theta + \delta - 1)^2 - \delta^2}{2\Theta}.$$
You should wait at the first light if $E[\Delta T]$ is positive,
but go to the second light if $E[\Delta T]$ is negative.
If $E[\Delta T] = 0$ either choice is equally good.
In the first two formulas for $E[\Delta T]$,
where $\delta \leq 1 - \Theta$, clearly it is always advantageous
to try the second light if the first is red, unless $\delta = 0$
(in which case it makes no difference).
In the other formulas, where $\delta > 1 - \Theta$,
we have $\Theta + \delta - 1 > 0$, so
$(\Theta + \delta - 1)^2 - \Theta^2$ is negative if and only if
$\Theta > \Theta + \delta - 1$, that is,
if and only if $\delta < 1$, which is true.
For similar reasons,
$(\Theta + \delta - 1)^2 - \Theta^2$ is negative if and only if
$\Theta < 1$, which presumably is also true.
So it seems that except for the case $\delta = 0$
(where it obviously makes no difference which path you take),
it is always advantageous to go to the second light if the first is red.


Q: Nginx conditional rewrite I am trying to redirect domain1.com to domain2.com based on http/https.

*

*So a request to http://domain1.com will go to http://domain2.com.

*Request to https://domain1.com goes to https://domain2.com
My current Nginx vhost file setup as:
server {
    listen 80;
    listen 443 ssl;

    ssl_certificate /etc/nginx/xxx.crt;
    ssl_certificate_key /etc/nginx/xxx.key;

    server_name *.domain1.com;
    if ( $scheme = "https" ) {
        rewrite ^ https://domain2.com$request_uri? permanent;
    }
    rewrite ^ http://domain2.com$request_uri? permanent;
}

However visiting https://domain1.com just goes to http://domain2.com. I can't seem to detect https. What am I doing wrong? Thanks.
EDIT:
I have edited my vhost to the below but the same issue occurs.:
server {
    listen 80;
    listen 443 ssl;

    ssl_certificate /etc/nginx/xxx.crt;
    ssl_certificate_key /etc/nginx/xxx.key;

    server_name *.domain1.com domain1.com;
    return 301 $scheme://domain2.com$request_uri;
}

A: There is no need to use if and rewrite
return 301 $scheme://domain2.com$request_uri;


Q: Python: all index of list greater than x data = [10, 90, 20, 80, 30, 40, 70, 60]
A_list=[A,B,C,D,E,F,G,H]

How do I find all the values in data that are above 50.
Next how do I print so that it displays
B:90
D:80
H:60
G:70

Also I haven't used enumerate yet.

A: If you just want to print all the values higher then 50 a simple loop will do.
data = [10, 90, 20, 80, 30, 40, 70, 60]
for value in data:
    if value > 50:
        print(value)

If you need the indexes use this code. enumerate will give you an automatic counter.
data = [10, 90, 20, 80, 30, 40, 70, 60]
for index, value in enumerate(data):
    if value > 50:
        print(index)

If you need a list of indexes to print the values (your question is unclear at that point) then construct this list and loop over it.
data = [10, 90, 20, 80, 30, 40, 70, 60]
indexes = [index for index, value in enumerate(data) if value > 50]
for index in indexes:
    print(data[index])

According to the question in your comment you could do the following (based on the last solution).
data = [10, 90, 20, 80, 30, 40, 70, 60]
characters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
indexes = [index for index, value in enumerate(data) if value > 50]
for index in indexes:
    print('{}: {}'.format(characters[index], data[index]))

This code uses the index for both lists.
If this is homework and you can't use enumerate you have to construct the indexes list with a standard for loop.
indexes = []
for index in range(len(data)):
    if data[index] > 50:
        indexes.append(index)

A pythonic solution would be something like this.
data = [10, 90, 20, 80, 30, 40, 70, 60]
characters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
for char, value in zip(characters, data):
    if value > 50:
        print('{}: {}'.format(char, value))

A: In case you want the elements of the list which are greater than 50, you can simply use a list comprehension:
[el for el in lst if el>50]

where lst is your input list.
If you also wanted the index of those elements, you could:
[(i,el) for (i,el) in enumerate(lst) if el>50]

which would give you a list of tuples (index, element)

A: You want an if loop; if x is greater than one of the numbers, print it?
example:
myList = list(range(0,100))

for numb in myList:
    if numb > 50:
        print numb

Honestly, I'm not sure what OP wants to do. But this is just an example.

A: If you would like to use enumerate(), and you would like to store both the indexes of the numbers above 50 and the values themselves, one way would be to do it like so:
>>> a = [1,2,3,4,5,50,51,3,53,57]
>>> b, c = zip(*[(d, x) for d, x in enumerate(a) if x > 50])
>>> print b
(6, 8, 9)
>>> print c
(51, 53, 57)

Enumerate takes any object that supports iteration, and returns a tuple, (count, value), when the next() method of the iterator is called. Since enumerate() defaults to start its count at 0, and increments the count by one each iteration, we can use it to count the index of the array that the iteration is currently on.
Now, our list comprehension is returning a list of tuples, if we were to print the comprehension we would get:
>>> print [(d, x) for d, x in enumerate(a) if x > 50]
[(6, 51),(8, 53),(9, 57)]

Zip creates a list of tuples when given two arrays, for example:
>>> f = [1, 2, 3]
>>> g = [4, 5, 6]
>>> zipped = zip(f, g)
>>> zipped
[(1, 4), (2, 5), (3, 6)]

When used with the * operator, zip() will "unzip" a list.
So, when we "unzip" the list comprehension, two tuples are returned.
Hope this helps!


Q: rails multiple belongs_to assignments with nested attributes My problem is that how to assign multiple belongs_to associations with nested attributes?
I want to build a issue system. When I create a issue, I also want to create the first comment as the issue body.
So, I have following Models:
class Issue < ActiveRecord::Base
  has_many :comments, as: :commentable

  validates :title, presence: true

  accepts_nested_attributes_for :comments
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :commentable, polymorphic: true

  validates :content, :user, presence: true
end

and I have the IssuesController as follow:
class IssuesController < ApplicationController
  before_action :authenticate_user! #devise authentication

  def new
    @issue = Issue.new
    @issue.comments.build
  end

  def create
    @issue = Issue.new(issue_params)
    @issue.save
  end

  private

  def issue_params
    params.require(:issue).permit(:title, comments_attributes: [:content])
  end
end

and the following is my form (using slim template with simple_form and nested_form gems):
= simple_nested_form_for @issue do |f|

  = f.input :title

  = f.fields_for :comments do |cf|
    = cf.input :content

  = f.button :submit

In this case, I don't know how to assign current_user to the comment created by nested attributes.
Any suggestions or other approaches? Thanks!

A: As I wrote in the comments, there's two ways of doing this.
The first way is to add a hidden field in your subform to set the current user:
= simple_nested_form_for(@issue) do |f|
  = f.input :title
  = f.fields_for(:comments) do |cf|
    = cf.input(:content)
    = cf.hidden(:user, current_user)
  = f.submit

If you do not trust this approach in fear of your users fiddling with the fields in the browser, you can also do this in your controller.
class IssuesController < ApplicationController
  before_action :authenticate_user! #devise authentication

  def new
    @issue = Issue.new
    @issue.comments.build
  end

  def create
    @issue = Issue.new(issue_params)
    @issue.comments.first.user = current_user
    @issue.save
  end

  private

  def issue_params
    params.require(:issue).permit(:title, comments_attributes: [:content])
  end
end

This way you take the first comment that is created through the form and just manually assign the user to it. Then you know for the sure that the first created comment belongs to your current user.

A: You could also add user_id as current_user.id when you use params
class IssuesController < ApplicationController
  before_action :authenticate_user! #devise authentication

  def new
    @issue = Issue.new
    @issue.comments.build
  end

  def create
    @issue = Issue.new(issue_params)
    @issue.save
  end

  private

  def issue_params
    params[:issue][:comment][:user_id] = current_user.id
    params.require(:issue).permit(:title, comments_attributes: [:content, :user_id])
  end
end


Q: htaccess not get index file after rewrite rule My htaccess is this :
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^([0-9a-zA-Z-]+)?$ show.php?id=$1 [L]
</IfModule>

So whenever browser get 'any thing' after root folder then it will go show.php and parameter will be  'any thing' .
Note: it will not effect if it have extension or a folder.
But there is index file in my root folder. So browser should take index file first. So that, i added this in .htaccess file :
DirectoryIndex index.php

But not working. So is there anything to do, to show at least index file whenever root folder visited ?

A: You can have your .htaccess like this:
DirectoryIndex index.php

RewriteEngine On

# request is not for a file
RewriteCond %{REQUEST_FILENAME} !-f
# request is not for a directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9a-zA-Z-]+)/?$ /show.php?id=$1 [L,QSA]


Q: How do you diagram: "I will have had been known to do that."? I'm a middle school grammar teacher, and I am absolutely stumped on how to diagram the following sentence:
I will have had been known to do that.

*

*I know "I" is the subject.

*I know "that" is the object.

*I know "to do" is the infinitive so it goes up on stilts.

*I don't know anything else.

I realize this is a horrible sentence; a sentence that I'd never encourage my students to use. It's purely hypothetical, but it's been driving me bananas. The context of the sentence is as follows (so you can be certain that it is grammatically correct): I'm living in the future, and I travel to the past (which is the present) and then the people who live farther in the future from where I'm from, upon reflection, are saying I'm a notable time traveler.
Thank you for your consideration and help.
Most kindly, Ali