text:
Q: What is the proper use case for modules? I currently have a Backbone.js site that is functioning properly. However, this site is starting to get quite large and turning into Backbone Spaghetti really quick.
To address this I think Marionette.js is the way to go and I started looking at it last week and attempting to come up with a proof of concept using it. My initial thinking was that each set of routes (i.e. servers & servers/:id) of the site should be their own module. For example, the list of Servers and then when you open up a server, the form and related lists would all be one module and what is displayed depends on the route (servers or server/:id). Then when you navigate to some other route, I would stop that module, reset the content region and start up a different one.
So my question is this... am I using modules as they were intended? Or, should a module be the broader sense of the word, meaning individual "mini" apps (i.e. chat widget, notifications widget, etc), stuff that isn't "required" for the overall purpose of the site to keep on functioning regardless of that module's state (started or stopped)?

A: Modules are intended to be mini apps like you mentioned. An approach that is even more modern is organizing your code with RequireJS. It will force you to fit your code in a modular structure.
Routes that belongs together (/admin/users , /admin/users/2/view , /admin/users/2/edit, /admin/users/new, etc) you should group them in a Marionette controller.
After you're familiarized with Marionette, you'll likely find a way to use the recently launched feature: Behaviors. They promote reuse of code and make your views even more slim.


text:
Q: Style background of icon I want to style the background of an icon. My code gives me an egg-shape but vertical, and I want the egg-shape to be horizontal. Also that the "egg" covers my icon in full. Is that possible?
Updated Fiddle... Fiddle
HTML:

CSS:
.car .fa-calculator {
    color:black;
    font-size:200px;
    background-color:red;
    display:block;
    position:relative;
    border-radius:80%
}

A: Use this CSS it will work
.car .pull-left i {
    color:black;
    font-size:200px;
    background-color:red;
    display:block;
    position:relative;
    border-radius:80%;
    height:100px;
    width:80px;
}

A: How about this;
.car .fa-calculator {
    color:black;
    font-size:200px;
    background-color:red;
    display:block;
    border-radius:50%;
    padding:.5em;
    width:1.6em;
    text-align:center;
}

A:
I want the egg-shape to be horizontal. Also that the "egg" covers my icon in full.

For an 'egg' shape the element has to be wider than it is tall (if we are to use border-radius).
So setting uneven padding would seem to be an option.

.car .fa-calculator {
    color:black;
 font-size:100px;
 background-color:#FF0000;
    position:relative;
    border-radius:50%;
    padding: .2em .4em; /* adjust as required */
    text-align: center;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.css" rel="stylesheet"/>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scala: Is it possible to constrain a type parameter to be non abstract? Scala: Is it possible to constrain a type parameter to be non abstract?
Are any other constraints possible except view bounds, upper bounds and lower bounds for type parameters and abstract type members? In C# for example, which I'm familiar with, you have the additional generic constraints:
where T: Class //Not sure if this covered in Scala by T<: AnyRef
where T: interface
where T: struct
where U: T //naked type constraint
where T: new () //This ensures that a type parameter is non-abstract and allows one to instantiate an object of the type in the generic class.
The last one is particularly important as it allows you to construct your unknown type, although its a shame you can only proscribe a  parameterless constructor.
Can =:= <:< and <%< only be used on method parameters?
In response to the comments, the immediate trigger for the question was the need for a "T: new()" restraint or some equivalent mechanism.
class ExampleClass[T <: AnyRef] {
  val example: T = new T()//Won't compile as the compiler
} //doesn't know if such a constructor exists

The uses of some of the C# constraints are particular to the needs of C#. For example one restraint that you don't have in C# that people are always wanting is "T: numericType" That issue is already solved in Scala. I'm still very much boot strapping my way up the Scala language, so aside from the above, I was just trying to clarify exactly what tools are and are not available to me in this facet of Scala syntax, even though I don't know yet exactly how I might want to use them in the Scala context.
I'm not sure if this is fully related but sometimes it seems the compiler (Eclipse 2.1.0.M1 with Eclipse 3.7.2) won't let me instantiate collections of unknown element type. The following code now seems to compiles fine. So I'd like to know what the rules are:
abstract class Descrip [T <: DTypes]()
{
  val hexs: MutableList[T#HexT] = new  MutableList[T#HexT] //compiles fine
  val sides: MutableList[T#SideT] = new MutableList[T#SideT] //compiles fine
}

A: The need of new T() is normally resolved by using Manifests. For example this code compiles:
class ExampleClass[T: Manifest] {
  val example: T = manifest[T].erasure.newInstance().asInstanceOf[T]
}

The drawback is that if the T for which ExampleClass is instantiated doesn't have a no-arg constructor it will fail at runtime...
Regarding Numeric, Ordering, etc., they are type classes and are part of the standard library, not part of the language. You can build your own type classes. The case of Manifest is special because it do have support from the language to provide the implicit object.


text:
Q: Is it possible to monitor dconf for changes? I would like to monitor dconf for changes so that while I tinker with settings, applications and the like I can see what keys are changed, if any.
Is there a way I can accomplish this?

A: If you want real-time monitoring, you could run the dconf watch command in a terminal, either to monitor a specific schema path
dconf watch /desktop/gnome/remote-access/

or the whole tree
dconf watch /

which will show a running output as you change values, e.g. toggling the 'Desktop Sharing' security preference checkbox produces
/desktop/gnome/remote-access/notify-on-connect
  false

/desktop/gnome/remote-access/notify-on-connect
  true

If you just want a list of changes, you could use dconf dump redirected to a file to create before and after snapshots that you can then compare with diff.


text:
Q: How to make a binary executable able to write anywhere on linux? I am writing a tool for all users on a linux server, which can download files from somewhere and save them to current directory. I build this tool as sudo user vector to get a binary executable and ask others to use alias tool="path/to/binary" to access that executable. However this executable cannot write files other than in folders under home directory of vector. How can I do to make it accessable to all users and have permissions to write to their directory?

A: When you create the tool, vector can own it.
The tool should reside somewhere on the user's PATH.
/usr/bin or /usr/local/bin are usually included the PATH.
You can check the path with echo $PATH to see what it is set to.
Check the permissions to make sure it is executable by everyone.
chmod 755 /path/to/binary
When the user executes the tool, it should execute as the user.
Make sure the output of the tool is not hard-code to a location the user does not have access to write.
If you can have it write to STDOUT, then the user can redirect the output to a place of their choosing
cmd> /path/to/binary > ~/output.txt


text:
Q: how to call javascript function in html.actionlink in asp.net mvc? How can one call a javascript function in html.actionlink in asp.net mvc?
I want to call one method, which is in JavaScript, but how I call it within html.actionlink in the same page?

A: blabla..

There is nothing more in @Html.ActionLink that you could utilize in this case.
And razor is evel by itself, drop it from where you can.

A: you need to use the htmlAttributes anonymous object, like this:
<%= Html.ActionLink("linky", "action", "controller", new { onclick = "someFunction();"}) %>

you could also give it an id an attach to it with jquery/whatever, like this:
<%= Html.ActionLink("linky", "action", "controller", new { id = "myLink" }) %>

$('#myLink').click(function() { /* bla */ });

A: @Html.ActionLink("Edit","ActionName",new{id=item.id},new{onclick="functionname();"})

A: This is a bit of an old post, but there is actually a way to do an onclick operator that calls a function instead of going anywhere in ASP.NET
helper.ActionLink("Choose", null, null, null,
    new {@onclick = "Locations.Choose(" + location.Id + ")", @href="#"})

If you specify empty quotes or the like in the controller/action, it'll likely add a link to what you listed.  You can do that, and do a return false in the onclick.  You can read more about that at:
What's the effect of adding 'return false' to a click event listener?
If you're doing this onclick in an cshtml file, it'd be a bit cleaner to just specify the link yourself (a href...) instead of having the ActionLink handle it.  If you're doing an HtmlHelper, like my example above is coming from, then I'd argue that calling ActionLink is an okay solution, or potentially better, is to use tagbuilder instead.

A: For calling javascript in your action link you simply need to write actionlink like this:
@Html.ActionLink("Delete", "Your-Action", new { id = item.id },
                 new { onclick="return confirm('Are you sure?');"})

Don't get confused between route values and the html attributes.

A: This is the only one that worked for me in .cshtml file:
@Html.ActionLink(
   "Name",
   "Action",
   "Controller",
   routeValues: null,
   htmlAttributes:new Dictionary<string, object> {{ "onclick", "alert('Test');" }})

I hope this helps.


text:
Q: SQL Server HEAP Tables WITH Clustered Index , how is this possible? I have a database that shows a few tables as HEAP, even since I am sure all of them have Clustered indexes and some even have a few Non-Clustered indexes, since a long time ago.
my understanding for HEAP table is : "A heap is a table without a clustered index"
as seen in the image, this tables have a clustered index

Currently using SQL Server 2014 with Compatibility mode 120
then , why are this tables being shown as heap when they have a clustered index ?
Thanks!


text:
Q: Android - Toolbar and TabLayout scroll if drag them up/down How to avoid scrolling of Toolbar and TabLayout by dragging them ? In my example I have such main.xml
 <android.support.design.widget.CoordinatorLayout
    android:id="@+id/main_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark"
        android:fitsSystemWindows="true">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbarMain"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:background="?attr/colorPrimary"
            android:elevation="1dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways|snap"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/toolbar"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
        </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/tab_layout"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>

ViewPager contains fragment with recycleview. The problem is that I can scroll Toolbar and TabLayout by dragging them up and down even if recycleview is not instantiated. I want that Toolbar and TabLayout scroll only when I scroll recycleview. Do you have any ideas how to achieve it ?

A: In your activity class, you can put:
tabLayout.setClickable(false);

or
tabLayout.setEnabled(false);

And only enable again in the condition that you want.


text:
Q: No known package when getting value for resource number 0x020a0057 I just updated my app to API level 25 in an attempt to get a WebView displayed datetime-local to use the proper picker.  But now as soon as I tap on the element in the WebView my app crashes, with the following messages in logcat:
01-01 16:17:22.578 10219-10219/com.example.test548 W/ResourceType: No known package when getting value for resource number 0x020a0057
01-01 16:17:22.578 10219-10219/com.example.test548 W/System.err: android.content.res.Resources$NotFoundException: String resource ID #0x20a0057
01-01 16:17:22.578 10219-10219/com.example.test548 W/System.err:     at android.content.res.Resources.getText(Resources.java:335)
01-01 16:17:22.578 10219-10219/com.example.test548 W/System.err:     at android.content.Context.getText(Context.java:463)
01-01 16:17:22.578 10219-10219/com.example.test548 W/System.err:     at org.chromium.ui.picker.DateTimePickerDialog.<init>(DateTimePickerDialog.java:78)
01-01 16:17:22.578 10219-10219/com.example.test548 W/System.err:     at org.chromium.ui.picker.InputDialogContainer.showPickerDialog(InputDialogContainer.java:221)
01-01 16:17:22.578 10219-10219/com.example.test548 W/System.err:     at org.chromium.ui.picker.InputDialogContainer.showPickerDialog(InputDialogContainer.java:102)
01-01 16:17:22.579 10219-10219/com.example.test548 W/System.err:     at org.chromium.content.browser.input.DateTimeChooserAndroid.createDateTimeChooser(DateTimeChooserAndroid.java:1188)
01-01 16:17:22.579 10219-10219/com.example.test548 W/System.err:     at org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
01-01 16:17:22.579 10219-10219/com.example.test548 W/System.err:     at org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:41)
01-01 16:17:22.579 10219-10219/com.example.test548 W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
01-01 16:17:22.579 10219-10219/com.example.test548 W/System.err:     at android.os.Looper.loop(Looper.java:154)
01-01 16:17:22.579 10219-10219/com.example.test548 W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6119)
01-01 16:17:22.579 10219-10219/com.example.test548 W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
01-01 16:17:22.579 10219-10219/com.example.test548 W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
01-01 16:17:22.579 10219-10219/com.example.test548 W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
01-01 16:17:22.581 10219-10219/com.example.test548 A/chromium: [FATAL:jni_android.cc(236)] Please include Java exception stack in crash report
01-01 16:17:22.695 10219-10219/com.example.test548 W/google-breakpad: ### ### ### ### ### ### ### ### ### ### ### ### ###
01-01 16:17:22.695 10219-10219/com.example.test548 W/google-breakpad: Chrome build fingerprint:
01-01 16:17:22.695 10219-10219/com.example.test548 W/google-breakpad: 1.0.19
01-01 16:17:22.695 10219-10219/com.example.test548 W/google-breakpad: 20
01-01 16:17:22.695 10219-10219/com.example.test548 W/google-breakpad: ### ### ### ### ### ### ### ### ### ### ### ### ###
01-01 16:17:22.695 10219-10219/com.example.test548 A/libc: Fatal signal 6 (SIGABRT), code -6 in tid 10219 (le.test548)

None of the packages in the call stack are my code. What am I doing wrong?
How can I set string resource "0x20a0057" so the crash won't happen?


text:
Q: I would like to set the size of the text to be dynamic/flexible depending on the window size with Javascript I am trying to set the size of the text to be responsive to the window width.
I am using this script

    flexFont = function () {
    var divs = document.getElementsByClassName("flexFont");
    for(var i = 0; i < divs.length; i++) {
        var relFontsize = divs[i].offsetWidth*0.05;
        divs[i].style.fontSize = relFontsize+'px';
    }
    for(var y = 0; y < divs.length; y++) {
        var relLineHeight = divs[y].offsetWidth*0.1;
        divs[y].style.lineHeight = relLineHeight+'px';
    }
};

window.onload = function(event) {
    flexFont();
};
window.onresize = function(event) {
    flexFont();
};
  .text-content-title{
    font-family: Roboto, Arial, Helvetica, sans-serif;
    font-size: 1.8em;
    padding-bottom:20px;
  }

  .text-content{
    font-family: Roboto, Arial, Helvetica, sans-serif;
    font-size: 1em;
    font-weight: 400;
    line-height: 1.6em;
    padding:5px 0;
    color: #000;
/*     width:70vw; */
    padding: 20px 0;
  }

.text-container{
  width:35vw;
}

Language Skills

I have always been fascinated by different cultures, habits, mindsets, and the interaction and diversity of people with different backgrounds.
I firmly believe the best way to learn about another culture is to start to learn their language.

I am also convinced if you get in contact with people in the language they know the best that not only shows your interest but will make the communication smooth and comfortable.

This is the HTML part
My issue is that this overwrites my CSS settings and instead of making the size dynamic, sets a different size that is very different from how I would like it to be.
My question is: Should I make a different variable for each size or there is something that I am missing?


text:
Q: Using sum in having clause I have a simple query
select id,
(select sum(totalin) from xorderextra where xorderextra.id = xoi.id) as totalin,
from xorderinfo xoi
group by xoi.id
having (select sum(totalin) from xorderextra where xorderextra.id = xoi.id) > 1000

Now I would like to know is there a better way to replace sum filter in having statement. Is this a proper way to setup things, would this hurt a query, ie. would it have to sum numbers twice?
*New case *
select xoi.id,
       sum(xex.totalin) as totalin,
       sum(xooc.totalout) as totalout,
from xorderinfo xoi
inner join xorderextra xex on xex.id = xoi.id
inner join xorderout xoo on xoo.rid = xoi.id
inner join xorderoutcalc xooc on xooc.obracunid = xoo.obracunid
group by xoi.id
having sum(xex.totalin) > 1000

This is returning wrong results, how can I fix this?

A: You may do a join and will improve performance dramatically!
select id,
       sum(xex.totalin) as totalin,
from xorderinfo xoi
inner join xorderextra xex on xorderextra.id = xoi.id
group by xoi.id
having sum(xex.xorderextra) > 1000

A: You could rewrite it using a cte and SUM OVER:
WITH cte AS(
    SELECT id
    ,      SUM(xoi.totalin) OVER (PARTITION BY xoi.id) As TotalIn
    FROM xorderinfo xoi
)
SELECT cte.* FROM cte
WHERE TotalIn > 1000


text:
Q: Issue with Ajax and JSON Response I'm a pretty novice programmer who is making an application where there are multiple divs with a class of jcontainer. Each jcontainer has an id associated with it, which corresponds with a field called apptid in a database. In the Jquery, I send out an AJAX request every five seconds to a php page to retrieve a field called currentlocation in the database (that corresponds with the apptid), which happens for each jcontainer.
Here is my code:
HTML:

  <button class='checkIn' data-param='button_IDNUMBER'>Check In</button>
  <form method='post' class='myForm' action=''>
       <select name='locationSelect' class='locationSelect' data-param='location_IDNUMBER'>
            <option value='1'>Exam Room</option>
            <option value='2'>Exam Room 2</option>
            <option value='3'>X-Ray Room</option>
            <option value='1000'>Check Out</option>
       </select>
  </form>

Checked Out

jQuery:


text:
Q: How do I navigate using a symlink? How do I navigate using a symlink?
I created a symlink, let's say 'projects' to my '/Desktop/Work/Projects' folder. So if I type 'ls' in my root directory, I see a bunch of things, the symlink among them. 'cd projects' fails with the error:
-bash: cd: projects: No such file or directory

A: The symlink is broken. If by 'your' /Desktop/Work/Projects you mean /home/youruser/Desktop/Work/Projects, then that's the path you should symlink to:
ln -s "/home/youruser/Desktop/Work/Projects" "/home/youruser/projects"


text:
Q: Reset modified state of entity in OnObjectMaterialized When I save an entity to the database I encrypt the values in an OnSavingChanges event handler. When the entity is loaded back from the database I'm using OnObjectMaterialized to decrypt the values.
This works great except that if I call save on one of the entities after its been materialized, the object context thinks that the entity has been modified and saves it back to the database.
So how do I reset the modified state such that it thinks that the decrypted values are the values in the database?


text:
Q: Set weights for ewcdf {spatstat} [R] I want to compare a reference distribution d_1 with a sample d_2 drawn proportionally to size w_1 using the Kolmogorov–Smirnov distance.
Given that d_2 is weighted, I was considering accounting for this using the Weighted Empirical Cumulative Distribution Function in R (using ewcdf {spatstat}).
The example below shows that I am probably miss-specifying the weights, because when lenght(d_1) == lenght(d_2) the Kolmogorov–Smirnov is not giving a value of 0.
Can someone help me with this? For clarity, see the reproducible example below.
#loop for testing sample sizes 1:length(d_1)
d_stat <- data.frame(1:1000, rep(NA, 1000))
names(d_stat) <- c("sample_size", "ks_distance")

for (i in 1:1000) {

#reference distribution
d_1 <- rpois(1000, 500)
w_1 <- d_1/sum(d_1)
m_1 <- data.frame(d_1, w_1)

#sample from the reference distribution
m_2 <-m_1[(sample(nrow(m_1), size=i, prob=w_1, replace=F)),]
d_2 <- m_2$d_1
w_2 <- m_2$w_1

#ewcdf for the reference distribution and the sample
f_d_1 <- ewcdf(d_1)
f_d_2 <- ewcdf(d_2, 1/w_2, normalise=F, adjust=1/length(d_2))

#kolmogorov-smirnov distance
d_stat[i,2] <- max(abs(f_d_1(d_2) - f_d_2(d_2)))
}

d_stat[1000,2]

A:
I don't quite understand what you are trying to do here.
Why would you expect ewcdf(d_1) and ewcdf(d_2, w_2, normalise=F) to give
the same result for i=1000? The first one is the usual ecdf which jumps at
the unique values of the input vector with a jump size determined by the
number of times the value is repeated (more ties – larger jumps). The second
one jumps at the same unique values with a height determined by the sum of
the weights you have provided.
What does give identical results is ewcdf(d_2, w_2) and
ewcdf(d_1, w_1), but this is not the same as ewcdf(d_1).
To understand why the latter two are different, I would suggest a much
smaller handmade example with a couple of ties:
library(spatstat)
#> Loading required package: spatstat.data
#> Loading required package: nlme
#> Loading required package: rpart
#>
#> spatstat 1.60-1.006       (nickname: 'See Above')
#> For an introduction to spatstat, type 'beginner'
x <- c(1,2,3,3,4)
e <- ewcdf(x)

This is the usual ecdf which jumps with value 1/5 at x=1, 1/5 at x=2, 2*1/5 at
x=3 and 1/5 at x=4:
plot(e)

Now you define the weights as:
w <- x/sum(x)
w
#> [1] 0.07692308 0.15384615 0.23076923 0.23076923 0.30769231

Thus the ewcdf will jump with value 1/13 at x=1, 2/13 at x=2, 2*3/13 at
x=3 and 4/13 at x=4 (with the usual ecdf overlayed in red):
plot(ewcdf(x, w, normalise = FALSE), axes = FALSE)
axis(1)
axis(2, at = (0:13)/13, labels = c("0", paste(1:13, 13, sep = "/")), las = 2 )
abline(h = cumsum(c(1,2,6,4)/13), lty = 3, col = "gray")
plot(e, add = TRUE, col = "red")

A: Your code generates some data d1 and associated numeric weights w1. These data are then treated as a reference population. The code takes a random sample d2 from this population of values d1, with sampling probabilities proportional to the associated weights w1. From the sample, you compute the weighted empirical distribution function f_d_2 of the sampled values d2, with weights inversely proportional to the original sampling probabilities. This function f_d_2 is a correct estimate of the original population distribution function, by the Horvitz-Thompson principle. But it's not exactly equal to the original population distribution, because it's a sample. The Kolmogorov-Smirnov test statistic should not be zero; it should be a small value.


text:
Q: Using Cython with PyPy can speed up? I've written a transpiler in python which works well with PyPy. Now I'm thinking to speed up more my existing code base with cython.
Will Using Cython with pypy increase or decrease the performance?
I'm using PyPy 3.9 and here's my code
https://github.com/ad1b003/Ethan-A-Programming-Language

A: Cython should mostly work with PyPy.
As with all performance questions, the key is to test it, however:

*

*If you are mainly manipulating Python objects then you will probably slow PyPy down. You force it to use its cpyexp compatibility layer, which isn't hugely fast and restricts how much it can JIT compile the surrounding code.

*If you're manipulating large arrays through "typed memoryviews" then this should work well: you have fast access to a region of memory and you're not forcing PyPy to make much use of its compatibility layer.

A quick look at your GitHub repository suggests it's mostly the former, so I would not expect a benefit.


text:
Q: Extracting every single image (e.g. as .png or other formats) from a .tvips file using Python I have a .tvips file containing some TEM images (1024 x 1024) pixel acquired sequentially. I wonder if there would be a way to extract them from this kind of file as classic .png, .tif ... file images.
I saw that the liberTEM package allows to deal with .tvips files. However It is not clear to me how access to every single image/dataset contained in the .tvips file and save it as .png, .tif ... file.


text:
Q: Derive parametric equations for sphere How do you derive the parametric equations for a sphere?
\begin{align}
x & = r \cos(\theta)\sin(\varphi), \\
y & = r \sin(\theta)\sin(\varphi), \\
z & = r \cos(\varphi),
\end{align}
where $\theta$ is from $0$ to $2\pi$ and $\varphi$ is from $0$ to $\pi$.
There are no good explanations online.

A: $\phi$ is the angle which polar radius makes with the $z$ axis. Hence, multiplying by $\sin \phi$ you find the projection of the polar radius on the $xy$ plane. Then multiplying by $\cos \theta$ and $\sin \theta$ respectively you find projections on axes $x$ and $y$

A: If you're familiar with surfaces of revolution, the derivation is easy. A circle that is rotated around a diameter generates a sphere.
The parametric equations for a surface of revolution are:
$$
\left(f(u)\cos v, f(u)\sin v, g(u)\right)
$$
Where $\left(f(u), g(u)\right)$ are the parametric equations of the rotated curve. For a circle, they are $\left(r \cos u, r \sin u\right)$. Therefore, the parametric equations of a sphere are:
$$
\left(r \cos u \cos v, r \cos u \sin v, r \sin u\right)
$$
Change the variables from $(u, v)$ to $(\frac{\pi}{2} - \varphi, \theta)$ to get the equations in your question.

A: I thought that it would be interesting to parameterise a sphere by using only 2 parameters $r$ and $\theta$ as follows
\begin{align}
x&=r\sin(\theta)\cos(n\theta),\\
y&=r\sin(\theta)\sin(n\theta),\\
z&=r\cos(\theta),
\end{align}
where $\theta$ is from $0$ to $\pi$ and $n$ is a reasonably large integer e.g. 64.
This results in a spiraling curve which describes a sphere with radius r. Check out the visualisation here.


text:
Q: Templatefile inside dashboard_body I was wondering if its possible to use templatefile inside of a dashboard_body resource. I'm trying the following.
     dashboard_body = <<EOF
{
  "widgets": [
    {
      "type": "metric",
      "x": 0,
      "y": 0,
      "width": 12,
      "height": 6,
      "properties": {
        "metrics": [
          templatefile("${path.module}/backends.tmpl", { instances = aws_instance.web })
        ],
        "period": 300,
        "stat": "Average",
        "region": "us-east-1",
        "title": "EC2 Instance CPU"
      }
    }
  ]
}
EOF

With templatefile
%{ for instance in instances ~}
          [
            "AWS/EC2",
            "CPUUtilization",
            "InstanceId",
            "${instance.id}"
          ]
%{ endfor ~}

However I get the following error message when I run terraform apply.

Error: "dashboard_body" contains an invalid JSON: invalid character 'e' in literal true (expecting 'r')
on dashboards.tf line 1, in resource "aws_cloudwatch_dashboard" "main":
1: resource "aws_cloudwatch_dashboard" "main" {

Thanks in advance for your help.

A: Yes you can use a template file. It looks like you have a small syntax error here:
templatefile("${path.module}/backends.tmpl", { instances = aws_instance.web })

You should wrap the entire function in an interpolation block, like so:
${templatefile("${path.module}/backends.tmpl", { instances = aws_instance.web })}


text:
Q: How to concat the string fields of a struct ignoring the empty strings? I am really new to Go, so want some advice.
I have a struct:
type Employee struct {
    Name        string
    Designation string
    Department  string
    Salary      int
    Email       string
}

I want to concatenate the string fields into a type of employee description.
So that, I can say:
toString(employee) and get:
John Smith Manager Sales john.smith@example.com

I tried to fetch each field, check if they are empty and put them in a slice and join them at the end
employeeDescArr := make([]string, 0, 4)
if strings.TrimSpace(value) != "" {
    append(employee.GetName(), value)
}...
return strings.Join(employeeDescArr[:], " ")

I think this method is very verbose and shows lack of Go skills.
Is it better to use a string Builder instead?
Is there a way to iterate through all fields of a struct in a Reflection way and join them?

A: Loop through the string fields and collect non-empty strings. Join the fields.
func (e *Employee) String() string {
    var parts []string
    for _, s := range []string{e.Name, e.Designation, e.Department, e.Email} {
        if strings.TrimSpace(s) != "" {
            parts = append(parts, s)
        }
    }
    return strings.Join(parts, " ")
}

Because the strings.Join function is implemented using strings.Builder, there's no benefit to replacing strings.Join with application code that uses strings.Builder.
Here's how to use reflect to avoid listing the fields in the string function:
var stringType = reflect.TypeOf("")

func (e *Employee) String() string {
    v := reflect.ValueOf(e).Elem()
    var parts []string
    for i := 0; i < v.NumField(); i++ {
        f := v.Field(i)
        if f.Type() == stringType {
            s := f.String()
            if strings.TrimSpace(s) != "" {
                parts = append(parts, s)
            }
        }
    }
    return strings.Join(parts, " ")
}

If you want to include all fields (include non-strings and empty strings), then you can fmt.Sprint(e) to get a string. See https://play.golang.org/p/yntZxQ-Xs6C.

A: You can make it less verbose by writing an utility function to make the addition with the "non-blank-string" check.
Also, you could make your type implement implement an String() method which has the advantage it will make it print as you wish when used in fmt print functions.
This addToString function is generic so you could reuse it if doing this for other types:
func addToString(original string, addition interface{}) string {
    additionStr := fmt.Sprint(addition)
    if additionStr != "" {
        if original != "" {
            original += " "
        }
        original += additionStr
    }
    return original
}

Then you can implement it like this, which is not so verbose:
type Employee struct {
    Name        string
    Designation string
    Department  string
    Salary      int
    Email       string
}

func (e *Employee) String() string {
    theString := ""
    theString = addToString(theString, e.Name)
    theString = addToString(theString, e.Designation)
    theString = addToString(theString, e.Department)
    theString = addToString(theString, e.Salary)
    theString = addToString(theString, e.Email)
    return theString
}

And use it like this:
func main() {
    emp := &Employee{
        Name: "Jonh",
        Department: "Some dept",
    }
    fmt.Println(emp.String())
    fmt.Println(emp)
}

Which will output:
Jonh Some dept 0
Jonh Some dept 0

A: I think you would want to use the Stringer interface instead. ie:
package main

import (
  "fmt"
  "strings"
  "strconv"
)
type Employee struct {
    Name        string
    Designation string
    Department  string
    Salary      int
    Email       string
}
func main() {
  emp1:=Employee{Name:"Cetin", Department:"MS", Salary:50}
  emp2:=Employee{Name:"David", Designation:"Designation", Email:"david@nowhere.com"}
  emp3:=Employee{Department:"Space", Salary:10}

  fmt.Println(emp1)
  fmt.Println(emp2)
  fmt.Println(emp3)

}

func (e Employee) String() string {
    var salary string
    if e.Salary > 0 {
      salary = strconv.Itoa(e.Salary) + " "
    } else {
      salary = ""
    }
    return strings.TrimSpace(
        strings.TrimSpace(
        strings.TrimSpace(e.Name + " " + e.Designation) + " " +
        e.Department) + " " +
    salary +
        e.Email)
}

Playground: https://play.golang.org/p/L8ft7SeXpqt
PS: I later noticed you only want string fields, but didn't remove salary anyway.

A:
Package fmt
import "fmt"

type Stringer
Stringer is implemented by any value that has a String method, which
  defines the "native" format for that value. The String method is used
  to print values passed as an operand to any format that accepts a
  string or to an unformatted printer such as Print.
type Stringer interface {
        String() string
}

Write a String method for type Employee.
For example,
package main

import (
    "fmt"
    "strings"
)

type Employee struct {
    Name        string
    Designation string
    Department  string
    Salary      int
    Email       string
}

func appendItem(items *strings.Builder, item string) {
    if len(item) > 0 {
        if items.Len() > 0 {
            items.WriteByte(' ')
        }
        items.WriteString(item)
    }
}

func (e Employee) String() string {
    s := new(strings.Builder)
    appendItem(s, e.Name)
    appendItem(s, e.Designation)
    appendItem(s, e.Department)
    appendItem(s, e.Email)
    return s.String()
}

func main() {
    ee := Employee{
        Name:        "John Smith",
        Designation: "Manager",
        Department:  "Sales",
        Email:       "john.smith@example.com",
        Salary:      42000,
    }
    fmt.Println(ee)
}

Playground: https://play.golang.org/p/EPBjgi8usJ-
Output:
John Smith Manager Sales john.smith@example.com

I want to concatenate the string fields into a type of employee
  description.
Is there a way to iterate through all fields of a struct in a
  Reflection way and join them?

[Reflection is] a powerful tool that should be used with care and avoided unless strictly necessary. Rob Pike
The Go Blog: The Laws of Reflection
Reflection is never clear. Rob Pike
Go Proverbs - Rob Pike - Gopherfest - November 18, 2015
Go compiled code is efficient. The Go reflect package functions are interpreted at run time.
Iterating through all fields of a struct has the same bug as SELECT *  FROM table; in SQL. The values returned are determined at run time, not compile time.
If your case, The business requirement is to hide confidential fields, like salary, and limit the fields displayed to a few key descriptive fields. Inevitably, fields will be added to the struct. The "concatenate the string fields" specification is unlikely to be correct now or in the future.


text:
Q: Unify values in Python PANDAS I'm an intermediary in Python, and recently I am developing some projects for the company that I work using Pandas to manipulate and automate some spreadsheets in Excel.
One of the spreadsheets contains 4800 values of multiples companies that are owing to my company, and what I need to do with the code is to send an e-mail to the company that are owing with the value that she owes, and some values are out of order, but are from the same company, example below:
COMPANY | VALUE
COMPANY 1 | US$ 1400
COMPANY 2 | US$ 2200
COMPANY 1 | US$ 900
COMPANY 3 | US$ 1500

What I need to do and I'm having issues, is to formulate a code that read those columns even out of order, unify the lines that are from the same company to send an e-mail to her, example below:
 Hello COMPANY 1! You owe US$ 2300, according to these lines below:

    COMPANY 1 | R$ 1400
    COMPANY 1 | R$ 900

Obs: I'm using smtplib to send the e-mails.
The code to send the e-mails automatically I already have, I just need to know how can I make the program read the spreadsheet and get the values of the same company together to send by e-mail, here's my entire code below:
import pandas as pd
import smtplib

list_months = ['Spreadsheet 1']

# localize the columns and lines
owing_clients = pd.read_excel(r'C:\Users\youruserhere\Documents\Owing Clients.xlsx')

# change these as per use
your_email = "email"
your_password = "password"

# establishing connection with gmail
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(your_email, your_password)

# getting the names and the emails
names = owing_clients['Debtor Name']
emails = owing_clients['Email']
values = owing_clients['Value']
debtorcode1 = owing_clients['Debtor Code']

# iterate through the records
for i in range(len(emails)):

    # mark the name, email and value of the debtor:
    name = names[i]
    email = emails[i]
    value = values[i]
    debtorcode1 = debtorcode[i]

    # the message to be emailed
    message = f"Subject: Debt\nHello {name}, you owe {value}, your debtor code is {debtorcode1}"
    # send email
    server.sendmail(your_email, [email], message)
    print(f'Your e-mail was successfully send!')

# Close the server
server.close()

Here's the spreadsheet for example:

I can execute the entire code and he sends the e-mails, but he sends one by one, and you know that is like the corporate bureaucracy, my company doesn't want one by one, they want me to unify all the values of a single company and send it. Thanks for the help.

A: Preparing data:
import pandas as pd

data = {

    'Value': [1400, 2200, 900, 1500],

    'Company': ['C1', 'C2', 'C1', 'C3'],

}

df = pd.DataFrame.from_dict(data)

    Value   Company
0   1400    C1
1   2200    C2
2   900     C1
3   1500    C3

Groupby
df.groupby('Company').sum()

Output
    Value
Company
C1  2300
C2  2200
C3  1500


text:
Q: embedded newlib-nano printf causes hardfault I compile the "same" code on 2 targets (one Freescale, one STM32 both with cortex M4). I use --specs=nano.specs and I have implemented the _write function as an empty function and this causes the whole printf to be optimized away by GCC's -Wno-unused-function even with -O0 on the STM32 target (seen in map). This is fine and I would like to reproduce that on Freescale target.
But on the Freescale target (with same compile flags) the printf causes hardfault. But if I go step by step with the debugger (assembly stepping) the printf goes through the library without hardfaulting. Simple breakpoint breakpoint sometimes not hit and run from any location in printf causes hardfault too (so it is unlikely that it is a peripheral issue).
So far I checked that stack and heap are not overlapping and some other far-fetched disassembly.
Why isn't the printf optimized away on freescale target ?
What can cause the library code to hardfault ?
Why is it OK when doing assembly step by step debug ?
EDIT:

*

*Using arm-none-eabi-gcc 5.4.1 for both MCU with same libraries.

*I do not want to remove printf, this is only a first step to be able to use
them or not.

*Vector table has default weak vectors for all ISR so it should be OK

*Using the register dump it seems that the faulty instruction is at address 4 (reset vector) so the new question is now: why does the chip reset ?

A: When ARM applications seem to work properly until printf is used, the most common problem is stack misalignment. Put a breakpoint at the entry point of the function that calls printf and inspect the stack pointer. If the pointer isn't double-word aligned, you've found your problem.

A: The common reason for crashing in printf with newlib is incorrectly set up free storage, especially if you are using an RTOS (ie FreeRTOS). Since 2019 NXP (formerly Freescale) includes my solution in MCUXpresso. You can find code and detailed explanation here: https://github.com/DRNadler/FreeRTOS_helpers


text:
Q: Compute pdf of a k-th order statistic How to compute the density function of the k-th order statistic of a sample of $X_1, X_2, ..., X_n$ random variables distributed independently but not identically (i.e., $X_i \sim F_i$ with $F_i\neq F_j$)?
What would be the explicit solution if each $F_i$ is uniform on $[m_i,1]$ with $0<m_i<m_{i+1}<...<m_n<1$?

A: Preamble
As per the above comments, order statistics from non-identical distributions typically require complicated calculations, and generally yield complicated solutions, which makes them well-suited for solving with computer algebra systems. I am not aware that one can generally derive closed-form solutions as a function of the sample size $n$ and $k$-th order statistic (though it may be possible for your example)... but one CAN certainly obtain quite neat solutions to your problem, given any arbitrary integer value for $n$ and $k$ of your own choice. I am going to pursue the computer algebra approach here, because those tools are familiar to me, and because it makes short shrift of a lot of messy algebra.
The Problem
Let $X_i$ denote a continuous random variable with pdf $f(x; m_i)$, such that $(X_1,X_2,\dots,X_n)$ are independent but not identical variables due to differing parameters $m_i$, for $i = 1,\dots,n$.
For the OP's question, we have a $Uniform(m,1)$ parent where identicality is relaxed by replacing parameter $m$ with $m_i$, for $i = 1, \dots, n$. Thus, the pdf $f(x; m_i)$, can be written:

To illustrate, here is plot of the family of pdf's, when $n = 4$, and $m_i = \frac{i}{5}$.

Solution
If $X_i$ has pdf $f(x; m_i)$, then, for any sample size $n$, the pdf of the $k$-th order statistic is given by:
$\qquad \qquad $OrderStatNonIdentical[k, {$f_i$}, {n}]
where OrderStatNonIdentical is a function from the mathStatica package for Mathematica, and where $n$ and $k$ are integers. For the OP's question, in a sample of size $n = 4$, the pdf of the 2nd smallest order statistic is given immediately by:

Here is a plot of the pdf of the 2nd order statistic (just derived), when the sample size is $n=4$, and $m_i = i/5$:

*

*Similarly, the pdf of the 3rd order statistic is:

... and here is a plot of same:

Monte Carlo check
When doing symbolic work, it is always a good idea to check one's work using numerical methods, to make sure no errors have crept in. Here is a quick Monte Carlo check of the $k = 2$ case solution derived above, again with $m_i = i/5$, and $n = 4$. The ragged blue line is the empirical pdf (blue), plotted on top of the theoretical solution (dashed red line) derived above:

All looks fine :)
General Solutions by Induction
It appears possible to attain general symbolic solutions by induction, at least for the 1st and 2nd order statistics. In particular:

*

*the pdf of the 1st order statistic, irrespective of the size of $n$, has form:

$$ \begin{cases}
\frac{n(1-x)^{n-1}}{\prod_{i=1}^n (1-m_i)} & m_n < x < 1 \\
\quad \quad \dots & \quad \quad \dots  \\
\frac{3(1-x)^2}{(1-m_1)(1-m_2)(1-m_3)} & m_3 < x \leq m_4 \\
\frac{2(1-x)}{(1-m_1)(1-m_2)} & m_2 < x \leq m_3 \\
\frac{1}{1-m_1} & m_1 < x \leq m_2 \\
0 & \text{otherwise}
\end{cases}$$

*

*the pdf of the 2nd order statistic has form:

$$ \begin{cases}
\frac{(n-1)(1-x)^{n-2}}{\prod_{i=1}^n (1-m_i)}(n x-\sum_{i=1}^n m_i) & m_n < x < 1 \\
\quad \quad \dots & \quad \quad \dots  \\
\frac{2(1-x)^1}{(1-m_1)(1-m_2)(1-m_3)} (3x-m_1-m_2-m_3) & m_3 < x \leq m_4 \\
\frac{1(1-x)^0}{(1-m_1)(1-m_2)} (2x-m_1-m_2) & m_2 < x \leq m_3 \\
0 & \text{otherwise}
\end{cases}$$


text:
Q: Interpolate the number of arrangements in a set I am working the integral
$$\int_0^\infty e^{x(k-\alpha) - e^x} dx$$
where $k$ is a positive integer and $\alpha$ a positive real.
WolframAlpha shows that for $\alpha=0$ and $k=1,\ldots,7$ the integral has a value proportional to $1,2,16,65,326,1957,13700$ which I identified in OEIS as the sequence $a_n$ of the number of arrangements of a set of size $n$, that is
$$ \sum_{k=0}^n \frac{n!}{k!} $$
Now, I want to put $\alpha > 0$, and the question is if there are an evident way to interpolate this function in the same fashion that the factorial is by the Gamma function.
A direct integration works for me also :)
Thanks in advance!

A: Mathematica v9.0 gives $\int_0^{\infty } \exp (k x-\exp (x)) \, dx$ = $\Gamma (k,1)$ with
$\Gamma (k,1)$ = $\frac{\sum _{i=0}^{k-1} \frac{(k-1)!}{i!}}{e}$  on condition the real part of k >0
Obviously, increasing your $\alpha$ is equivalent to decreasing 'my' k in the result above.
Remark that $\Gamma (z,1)$ is defined for complex z, not just integer x. See http://mathworld.wolfram.com/IncompleteGammaFunction.html


text:
Q: Reference to popup window in Chrome content script gets lost In the content script of chrome extension, I would like to open a popup window and get the reference, so that I could send messages to the window, and close it in the onbeforeunload event.
However, it seems the reference only exists in the local scope, and it gets lost in any other closures.
e.g. If I use the following code in the content script:
var popup = window.open("https://example.com/", 'popwin');
console.log("@1", popup);
setTimeout(function(){
  console.log("@2", popup);
}, 2000);

Here is what I see in the console window

@1 Window {window: Window, self: Window, location: Location, closed: false, frames: Window, …}
@2 global {}

And it's even the same if I use a global window property to store the reference, i.e.
window.popup = window.open("https://example.com/", 'popwin');
console.log("@1", window.popup);
setTimeout(function(){
  console.log("@2", window.popup);
}, 2000);

@1 Window {window: Window, self: Window, location: Location, closed: false, frames: Window, …}
@2 global {}

Any idea about this? Thanks a lot.


text:
Q: To find the highest level variable amongst 2 ID attributes in SAS My input dataset looks as follows:
DRUG Table
DRUG_CD PARENT_DRUG_CD
DRG_1   DRG_5
DRG_2   DRG_5
DRG_3   DRG_4
DRG_4   --
DRG_5   DRG_6
DRG_6   --

I need to build a dataset with only those DRUGS (and all the attributes of this DRUGS) who does not have a parent anymore and an extra column (CHD_DRUG_CD) which contains the lowest level of DRUG_CD.
Resulting DRUG Table
DRUG_CD CHD_DRUG_CD
DRG_6   DRG_1
DRG_6   DRG_2
DRG_6   DRG_5
DRG_4   DRG_3

A: Parent-child relationships are relatively common in the literature, and you should be able to find plenty of examples out there.  Here's a place to start:
http://support.sas.com/kb/25/968.html
The basic concept is that you need to iterate over the dataset to find the child for each parent.  You can do that either by creating your own iterator, using POINT= (as in the paper linked) or a DOW loop, or you can do this using other techniques such as a hash table.  Hash iterator is probably the fastest solution, although the most complex to understand and to code.  Then when you find your child, you identify which one you found (in an array, for example, as in the paper) and return the loop to the beginning to find the next one (or, exit with none found).


text:
Q: SSH keys: ed25519 vs RSA performance demystified It is claimed that ed25519 keys are better than RSA, in terms of security and performance. In terms of security, I understand that 4096 bits RSA keys are practically unbreakable for the foreseable future, so I am not asking about that.
What I would like to understand is the performance difference (in terms of speed). When people claim that ed25519 keys are faster, what does it mean? I am asking from the viewpoint of a user. I consider a couple of possibilities:

*

*It is faster to login into the server with ed25519 keys, but after that server-client communication is of the same speed.

*Initial login, and server-client communication, is faster with ed25519 keys.

*If you copy a file from/to the server, is the transfer speed any different?

*If I do ssh tunneling through the server, will I notice any speed differences?

Which is it? All of them? Neither of them?
So I am not asking about the mathematical differences between them, nor the algorithmic complexities to break their encryption, or the security guarantees. I am asking about the speed, in real world user applications.

A: The cipher/algorithm used for ssh keys is independent of the algorithm/ciphers used for encrypting the session/connection.
So a faster key algorithm will only speed up operations relating to key generation and validation, i.e. authenticating and establishing a session.
For faster or more secure transfer speeds, you can  tune the preferred  Ciphers in the servers sshd_config and/or the ssh client with the same config file option or the -c cipher_spec command line option.
You can test on your own machine how for example how RSA 1024, 2048 and 4096 compare in that regard with  ed25519 using openssl speed rsa1024 rsa2048 rsa4096 ecdsap256 ed25519  :
                                sign    verify    sign/s  verify/s
rsa 1024 bits                0.000078s 0.000006s  12852.6 175638.7
rsa 2048 bits                0.000519s 0.000016s   1926.4  62959.0
rsa 3072 bits                0.001570s 0.000033s    636.8  30670.3
rsa 4096 bits                0.003496s 0.000055s    286.1  18200.7
 256 bits ecdsa (nistp256)   0.0000s   0.0001s    41044.8  16044.8
 253 bits EdDSA (Ed25519)    0.0000s   0.0001s    21079.9   9383.2


text:
Q: How to check if a symlink target matches a specific path? I'm creating a bash script to check if a symlink target matches a specific path so, in case it doesn't match, script removes the symlink. I've tried with readlink:
#!/bin/env bash

target_path=$HOME/Code/slate/.slate.js

if [ `readlink $HOME/.slate.js` == "$target_path" ]; then
    rm -rf "$HOME/.slate.js"
fi

but it doesn't work:
%source test
test:5: = not found

A: In case $target_path does not match the link text exactly, you can check that they are, in fact equivalent (regardless of name). But since a hardlink is preferable you might want to check that case, too (see below).
A more generic solution is:
[ "$(readlink $HOME/.slate.js)" -ef "$target_path" ]

Or, as in your example:
target_path=$HOME/Code/slate/.slate.js

if [ "`readlink $HOME/.slate.js`" -ef "$target_path" ]; then
    rm -rf "$HOME/.slate.js"
fi

But that all assumes that your $HOME/.slate.js is a symbolic link. If it is a hard link (which is preferable, when possible), then it is simpler:
 … [ "$HOME/.slate.js" -ef "$target_path" ] …

Maybe something like (check whether it is a symlink, if so, then check that link matches target; otherwise check whether the files same—either a hard link or actually the same file):
 … [ \( -L "$HOME/.slate.js" -a "`readlink $HOME/.slate.js`" -ef "$target_path" \) \
     -o \( "$HOME/.slate.js" -ef "$target_path" \) ] …

You should also check whether the file is, in fact, the same file (and not a hard link), otherwise you will delete the one and only copy.

A: You should use double quotes as follow when you compare strings (and yes, the output of readlink $HOME/.slate.js is a string):
[ "$(readlink $HOME/.slate.js)" = "$target_path" ]


text:
Q: Google Maps marker title not showing all content When clicking on a marker on google maps in my application, the marker only shows the first part of the title, but then adds "..." and not showing the rest, even though there ain't that much text.

The code is as below (only took the necessary part:
...
...
String name = (String) hashmap.get("Name");
double rating = (double) hashmap.get("Rating");
String category = (String) hashmap.get("Category");

googlemap.addMarker(new MarkerOptions().position(oldSpot).title(name + "\n rating: " + rating + "\n" + category))
....
....

I know that an option is to create and handle a infowindow(), but the above solution is much simpler and should be possible, I think.
Do anyone have an idea of what I can do (or why it cuts if off) - besides creating an "infowindow()-class", add further design, etc..
The "name" is simply t3 by the way. Rating is '1' and category is 10 chars long, so approx 15 chars all together.
And I use java and Firestore, for notice.

A: I think the issue may be that you are using the default info window which only supports a single line title. You would need to do some tricky things in order to get the second line or just set up a custom info window so that you can get all the information you want in it without the window looking weird and be able to get the display however you want.


text:
Q: !map:HashWithIndifferentAccess convert to JSON or other formats When I query via the rails console to get the data of an invoice. It returns a !map:HashWithIndifferentAccess text. See example below.

"--- !map:HashWithIndifferentAccess \nformat: xml\ninvoice:
  !map:HashWithIndifferentAccess \n  reference: 5-00000003R\n
  invoice_lines: \n  - !map:HashWithIndifferentAccess \n    price:
  \"2.50\"\n    product_id: \"177698\"\n    quantity: \"-1.00\"\n
  discount_text: 10%\n    retail_price: \"25.00\"\n    subtotal:
  \"-2.50\"\n  payments: \n  - !map:HashWithIndifferentAccess \n
  payment_type_id: \"6\"\n    amount: \"-20.09\"\n    tender:
  \"-20.09\"\n  invoice_date: \"2015-06-04T05:56:44Z\"\n  remark:
  CANCELLED ORDER\n  customer_id: \"182029\"\n  tax_inclusive:
  \"true\"\n  invoice_tax_rates: \n  - !map:HashWithIndifferentAccess \n
  rate: \"0.12\"\n    amount: \"0.27\"\naction: create\ncontroller:
  api_invoices\n"

What I need is to get all the product ids in the invoice lines attribute of the invoice. How do I parse this text?


text:
Q: $_POST sem fechar modal bootstrap Tenho que abrir um formulario em um modal usando bootstrap e ao enviá-lo quero receber os dados sem fechar o modal
Abro o modal assim:
Consultar CNPJ

O arquivo consulta.php tem o seguinte formulario:
<form id="formulario" action="resultado.php" method="post">
    <input type="text" name="CNPJ" id="CNPJ" maxlength="19" required />
    <input id="submit" name="enviar" type="submit" value="Consultar" />
</form>

Desta forma ao enviar o formulario o modal fecha automaticamente. Quero que seja enviado o post e me mostre a pagina resultado.php no mesmo modal.

A: Com essa forma de enviar, a página atualiza completamente e retorna a modal para padrão inicial(que é hidden).
Use jquery e ajax para dar um submit no formulário.
<form id="formulario" action="resultado.php" method="post">
   <input type="text" name="CNPJ" id="CNPJ" maxlength="19" required />
    <input id="submit" name="enviar" type="submit" value="Consultar" />
</form>


text:
Q: Unable to the get the gallery inserted between shortcodes I am customizing this theme . I am using get_the_gallery() function to get the gallery from the custom post . I am able to do so, but when the gallery is inserted between the shortcodes...
For eg:
[two-third]

[gallery ids="18,17,8,7,6"]

[/two-third]

then i am not able to get the gallery..I am using the following code
<?php
    if ( get_post_gallery() ):
       $gallery = get_post_gallery( $post, false );
       $w3_ids = explode( ",", $gallery['ids'] );
?>

<?php
    $gallery_count=1;
    foreach( $w3_ids AS $w3_id ):
        $src = wp_get_attachment_image_src($w3_id,'full');
?>
    <div class="item <?php if($gallery_count==1)echo "active"; ?>">
       <img src="<?php echo $src[0]; ?>" alt="" />

<?php
    $gallery_count++;
    endforeach;
    endif;
?>

What can be done... Please help

A: I don't know why the code is not working.
But this is how i did this may be helpful for some noob like me
<?php
    $name = get_the_content();
    preg_match('/\[gallery ids="([^]]*)\"]/', $name, $match);
    $w3_ids = explode( ",", $match[1] );
    $gallery_count=1;
    foreach( $w3_ids AS $w3_id ):
       $src = wp_get_attachment_image_src($w3_id,'full');
?>
    <div class="item <?php if($gallery_count==1)echo "active"; ?>">
        <img src="<?php echo $src[0]; ?>" alt="" />

<?php
    $gallery_count++;
    endforeach;
?>

A: <?php
    $id=the_ID();
    $gallery_count = $wpdb->get_var("SELECT COUNT(ID) FROM {$wpdb->prefix}posts WHERE post_type = 'attachment' && ID=$id");
    echo $gallery_count;
?>

I think...!!! Try this for Particular gallery.


text:
Q: display a confirmation popup on button click based on condition I have a p:commandButton on click of which I need to add a few values to a list. In my managed bean, I'm validating the value that has to be added, and if it validates to false, I have to display a confirmation popup. This is my code -
<p:commandButton id="add" value="Add" type="submit"                                      action="#{bean.doAdd}" ajax="false"
update=":List"/>

And in the bean, on click of the "Add" button,
public String doAdd() throws Exception {
        if(response != null) {
            if(keyList.contains(response))  {
                if(!responseList.contains(response)) {
                    responseList.add(response);
                }
            } else {
               //Have to display confirmation popup.
            }
            response = "";
        }

        return response;
    }

I'm using jsf 2.0 and primefaces 3.0. Can someone please tell me how to display the popup from the bean?

A: You can use RequestContext to run js code inside your managed bean
Make sure its an ajax call  - got no ajax="false"
like this
RequestContext context = RequestContext.getCurrentInstance();
context.execute("YourDialogwidgetVar.show()");

I assume you got some dialog defined...
<p:confirmDialog id="confirmDialog" message="Hello"
                header="Header" widgetVar="YourDialogwidgetVar">
</p:confirmDialog>

A: This code may helpfull to you.
private boolean valid = true;

public void doAdd() {
    valid = false;
}

<p:dialog id="basicDialog" header="Basic Dialog" visible="#{!testBean.valid}">
    <h:outputText value="Message!" />
</p:dialog>

<h:commandButton id="modalDialogButton" value="Modal" action="#{testBean.doAdd}"/>


text:
Q: How can I get the Last Successful Build time and Last Failed Build time Jenkins Using the XML API, how can I construct the query string parameters to get the Last Successful Build time and Last Failed Build time for all jobs?
I have "/api/xml?tree=jobs[name,color]" but need these 2 additional field so I can get an overall status of all jobs on the server.

A: you can get it by calling Jenkins server with path:
/job/[job name]/lastSuccessfulBuild/

/job/[job name]/lastFailedBuild/


text:
Q: CSS3 Animation affects the weight of all text on the page, even on elements the animation is applied. Any idea? I'm encountering a strange display bug where CSS3 Animation affects the weight of all text on the page, even on elements the animation is not applied. Any idea why this is happening?
(You can reference this page: https://gtrot.com/chicago)
Notice that upon hovering over the logo in the center of the blue header, the logo wiggles. I do this by applying 2 classes on hover: 'animated' and 'wobble'
@keyframes wobble {
    0% { transform: translateX(0%); }
    15% { transform: translateX(-5%) rotate(-4deg); }
    30% { transform: translateX(4%) rotate(3deg); }
    45% { transform: translateX(-3%) rotate(-1deg); }
    60% { transform: translateX(1%) rotate(1deg); }
    75% { transform: translateX(-1%) rotate(-1deg); }
    100% { transform: translateX(0%); }
}

and
.animated_slow {
    -webkit-animation-duration: .8s;
    -moz-animation-duration: .8s;
    -ms-animation-duration: .8s;
    -o-animation-duration: .8s;
    animation-duration: .8s;
}

Thanks in advance,
Matt

A: Add this to the html styles and it should solve your problem:
html {
    -webkit-font-smoothing: antialiased;
}


text:
Q: Efficient multi-queue iteration
We are given a subroutine which takes two positive int arguments and returns an int, let's say it's def f(m,n): return (m+n)**2-n**2.  The input values must be positive integers.  The returned value is increasing with respect to both of the inputs: that is f(m,n)<f(m+1,n) and f(m,n)<f(m,n+1) for all m and all n.  We want to iterate over all possible pairs of m and n in an order that gives the returned values in increasing order, until it passes a test.  We don't care about the test: we know some pair of values will pass it, and we want the smallest returned value which passes.  We also don't know if the test will be passed in the first million values of m and n each, so we can't just build the entire list of values and sort it.
How do we iterate over m,n in the correct order, reasonably efficiently?

I visualize this as a multi-queue, which can't be the right name: what is it called?
I have an array nextN[] indexed by m-1, storing the largest visited n for that m. Another array nextV[] indexed by m-1 stores the returned value of f(m,nextN[m-1]) so we don't call f() more than once for any pair (this can be omitted as a pre-optimization, but it's a necessary optimization when f takes a long time to run or has side effects).  At each step we take the smallest stored value and test it, and update those elements in the two arrays with the next value of n.
The question is: what data structures and methods should be used to make this multi-queue efficient and understandable?  I have the quick hack, but I want a better, more understandable and maintainable solution.
I'm writing in Python, but the same question applies to Java, C, etc.  Give your answer in whatever language you like.  (I won't select an answer in a language chosen for its obscurity, but I will +1 it if I can understand it and it's helpful.)
Here is some sample code:
from array import array
from math import sqrt

def findSmallestV(f,test):
    # initialize with m,n=1,1 filled out
    nextN = array('I', [1])
    nextV = array('I', [f(1,1)])
    while True:
        v = min(nextV)
        m = nextV.index(v)+1
        n = nextN[m-1]
        if test(v):
            return (m,n,v)
        nextN[m-1] += 1
        nextV[m-1] = f(m,n+1)
        # if we've just operated on the last column, put a value into the next column
        if m == len(nextN):
            nextN.append(1)
            nextV.append(f(m+1,1))

# example value function
def g(m,n): return (m+n)**2-n**2

# example test function
def h(v): return len(str(v))>5 and int(sqrt(v))**2 == v

ans = findSmallestV(g,h)
print("Smallest V: m=%d, n=%d -> %d" % ans)

I feel like this will spend a long time on min(nextV) when the size of nextV gets large.  What's the better way?

A: What you could do is break the problem into two steps:

*

*Find some (m, n) that passes the test.

*Use a binary search technique to find the lowest (m, n) that pass.

You could potentially use a binary search technique for the first part, too.
It's hard to know what "passes the test" means. Do you know if the returned value is too large or too small? If so, you can adjust m and n by halving or doubling until you find a solution.
Given your restrictions (i.e. the relationships you described), the binary search on two variables shouldn't be too difficult.
You can keep track of intermediate passing values in a priority queue. So when you find one that passes you can put it on the queue. That can be the starting point for your next time through. You'll also want to keep track of the highest and lowest passing values that you've found, so that you can more easily bracket the search.
And, I suppose, you'll want to keep a hash table of some kind that will prevent you from generating the same (m,n) more than once.
This becomes easier if m and n have some defined range. If it's "all positive integers," the technique I describe is possible, but it's a lot easier if they're bracketed.

A: A priority queue, as suggested in the comments, leads to a good solution.
At any point during the running of your algorithm, you will have considered some points and not considered others. You'll put the points on the boundary of this divide into a priority queue. More specifically, you maintain a priority queue (probably implemented as a binary heap) of triples (m,n,v), sorted by v, where (m,n) is a point on this boundary and v its value.
At every iteration, extract the lowest valued point from your queue and test it. If it passes, it's the answer. If not, put the points to its right and above it into your queue, together with their values.
This will work as is, but it's inefficient, because every point gets processed many times. To prevent this from happening, also maintain growable arrays of the lowest coordinate in every column that's in your queue, and an array for the leftmost entry in every row. Whenever you would enter a point into the queue, first check if there's already a lower point in that column or a point further to the left in the same row. If so, just don't enter it - it'll come later anyway.


text:
Q: Xcode won't add bundle resources I'm trying to make sure that certain resources get copied as Bundle Resources when my iOS app gets built inside of Xcode.
When I select my target, go to Build Phases, expand the Copy Bundles Resources accordion pane and click the "+" icon I see:

So far so good. However, I want to select the Models.scnassets folder under my Resources folder, and add everything inside of it. But Xcode won't let me select the whole Models.scnassets folder, only its contents.
Perhaps I need to refactor the Models.scnassets folder to be a special type of folder first?
Either way, what's the solution here: how do I add the entire Models.scnassets folder as a bundled resource?

A: Can't you shift+click and select all under folder? That or make it a folder reference rather than a group. (blue folder not brown folder)
I was able to make a folder reference by doing the following:

*

*Make a folder somewhere (for instance I just made it on my Desktop) called what you want your folder in Xcode to be (for you that would be Models.scnassets). It may give you a warning about becoming a single file, just click ok.

*Add in whatever assets you want (I just did some random pictures)

*Drag and drop that folder into your Xcode, ensuring the Create folder references option is selected (See Image):

Now you should be able to click on only that folder to add to your Bundle Resources


text:
Q: Links In Sidebar not displaying Ive placed a link in the sidebar, however its not showing up at all!
Any ideas? The link is the blackburn text in the post.
http://pcdconsultancy.co.uk/
thanks
Kirsty

A: I'm guessing that text is an excerpt - and so any mark-up will be stripped out.


text:
Q: Having some trouble with my html5 custom audio control I am dealing with dynamic loaded file from php. My custom audio control can only play the first audio file from the database but cannot play others.
I will greatful if anyone can help me.
This is my code:
 echo " <audio id='aud' controls>
      source='$aud_dir' type='audio/$audio_type'>
      </audio>

";

This is my javascript code:
var aud, playbtn;

function intializeplayer() {
  aud = document.getElementById('aud');
  playbtn = document.getElementById('playpausebtn');

  playbtn.addEventListener('click', playpause, false);
}
window.onload = intializeplayer;

function playpause() {
  if (aud.paused) {
    aud.play();
  } else {
    aud.pause();
  }
}

A: The javascript appears to work ... I altered the html a little - it appears your HTML for the audio tag is invalid - there is a > after controls which closes the opening tag, and then the source and type attributes are floating inside the tag...
See working example below:
Update
Per your comments, you mentioned that you needed to have the Play/Pause button work for multiple audio players. I have updated the sample to handle all audio tags, though you could add a class attribute to specific audio elements and find the desired elements using that class name (e.g. var audioPlayers = $('.selectedAudioPlayers');. And per the html standard (4 I believe) the id attributes must be unique (refer to the MDN documentation and validity rules are explained in this SO answer, so as you are generating the <audio> tags with your server side code (PHP, right?), you can make the id attributes unique by appending an id to it - e.g. echo "<audio id='aud_$id'...". Does that make sense?

    var audPlayers, playbtn;

    function intializeplayer() {
      audPlayers = document.getElementsByTagName('audio');
      playbtn = document.getElementById('playpausebtn');

      playbtn.addEventListener('click', togglePlayers, false);
    }
    window.onload = intializeplayer;
    function togglePlayers() {
        Array.prototype.forEach.call(audPlayers,playpause);
    }

    function playpause(aud) {
      if (aud.paused) {
        aud.play();
      } else {
        aud.pause();
      }
    }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<audio id='aud_1' controls src="http://www.noiseaddicts.com/samples_1w72b820/3717.mp3">
</audio>
<audio id='aud_2' controls src="http://www.noiseaddicts.com/samples_1w72b820/1456.mp3"> </audio>


text:
Q: gauge chart is not displaying any thing i am trying to display the latest speed in mysql database on guage chart. i have tried so many things but gauge is not display plz any can help me...my code is attached and php part shows the correct value but dont know why guage is not display
<?php

$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="mysql"; // Database name
$tbl_name="gpsdb"; // Table name

// Connect to server and select database.
$con=mysql_connect("$host", "$username")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$data = mysql_query("SELECT speed FROM gpsdb WHERE DeviceId=1234 ORDER BY TIME DESC LIMIT 1")
or die(mysql_error());

while ($nt = mysql_fetch_assoc($data))
{
$speed = $nt['speed'];
 $jsonTable = json_encode($speed);
 echo $jsonTable;

}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
  Google Visualization API Sample
</title>


text:
Q: Maven Grails Building with 'mvn clean install' doesn't work I've built a Maven Grails project which can be build fine using command mvn grails:war.
However, using the standard mvn install fails to work - I get exceptions complaining that a util Java class (held under the grails-app/util folder) can't compile because it can't find one of the domain classes.
I'm not using any package structures, so the domain class isn't imported to the util class.
I suppose my first question is - does Maven fully support the building of a mavenised Grails project? Should I be expecting mvn install to work?
My second question is - If i'm forced to build the app using mvn grails:war - how do I enforce this when the parent project / pom has it as a dependant module?

A:
I suppose my first question is - does Maven fully support the building of a mavenised Grails project? Should I be expecting mvn install to work?

According to Developer - Maven Integration, yes, definitely. Did you follow the steps detailed in Maven Integration? Did you use the grails archetype to create your project? Is it really using a packaging of type grails-app?

My second question is - If i'm forced to build the app using mvn grails:war - how do I enforce this when the parent project / pom has it as a dependant module?

According to the lifecycle of a project with a packaging of type grails-app, the grails:war goal is bound to the package phase. In other words, nothing forces you to call grails:war, just call mvn package (and actually, you should do this) or any other standard phase posterior to package.
So, to answer your question, just use a <packaging>grails-app</packaging> for the grails module and maven will do its job during a reactor build.


text:
Q: Win32: CredUIConfirmCredentials behaves unexpectedly I'm using CredUIConfirmCredentials in combination with
CredUIPromptForCredentials.
I set the EXPECT_CONFIRMATION, and when the credentials are first provided by
the user the call to CredUIConfirmCredentials returns NO_ERROR as expected.
However, on all subsequent calls to CredUIConfirmCredentials, with the same
credentials, ERROR_INVALID_PARAMETER is returned. This is described by the
SDK docs as:

An attempt to confirm a waiting
  credential failed because the
  credential  contained invalid or
  inconsistent data.

which is rather confusing as they are exactly the same credentials that were successfully saved originally.
The same result is returned if you enter a different password for the same
username. What is even more confusing is that the new credentials are
actually persisted - which seems to indicate that the return value is
actually indicating that the persisted credentials were overwritten - not
that there was a error. Am I missing something, or is the documentation
incorrect?

Background
You can use Window's credential system to store credentials for your own application. You tell Windows you want to prompt for "generic" credentials for some "target":
pseudo-code:
CredUIPromptForCredentials("My Application", ref username, ref password);

will then cause Windows to display a dialog box:

It is then your job to check the credentials the user has entered. If they are valid, you tell Windows this by calling ConfirmCredentials. This is to ensure that only valid credentials are saved:
CredUIConfirmCredentials("My Application", true);

Once the credentials have been confirmed as valid, Windows will save them in the secure store, which you can see through the Control Panel:

Keywords: credui, CredUIConfirmCredentials

A: i found the answer: by design
CredUIConfirmCredentials will return an error "when there's nothing to do". This means:

*

*if the credentials are the same as what's already in the credential store

*the user didn't check the Rembember my password check box

*you didn't set the CREDUI_FLAGS_EXPECT_CONFIRMATION flag

The fact that CredUIConfirmCredentials fails when the credentials are the same as what's already in the store documented on MSDN. (i know it's documented because i added to the documentation page.)


text:
Q: nvd3, multibar with time series data, x-ticks are appearing separately for each check box item I am trying to use nvd3 for MultiBar chart with Time Series data. But in x-axis, the ticks are appearing separately for check box item. How can I fix this to make appear as normal multibar chart with dates on x-axis. Please find my plunker at http://plnkr.co/edit/GX5PH5xI2JZfylobO8M4?p=preview.
The following are my option settings:
  $scope.options = {
                chart : {
                            type : 'multiBarChart',
                            height : 400,
                            text : 'Credit Recovery',
                            x : function(d) {
                                return d[0];
                            },
                            y : function(d) {
                                return d[1];
                            },
                            useVoronoi : false,
                            clipEdge : true,
                            transitionDuration : 1000,
                            useInteractiveGuideline : true,
                          xScale : d3.time.scale(), // <-- explicitly set time scale
                            xAxis : {
                               ticks : d3.time.months, // <-- add formatter for the ticks
                                 tickFormat : function(d) {
                return d3.time.format('%m-%y')(new Date(d))
        },
                                showMaxMin : false
                            },
                            yAxis : {
                                tickFormat : function(d) {
                                    return '$' + d3.format('.02f')(d )
                                }
                            }
                        }

    };

A: i think your data object is wrong, check his plunker i correct your data structure and the x,y attributes in the chart object.
also the order function.
plunker fixed
$scope.data = [ {
          "values":[
            {x:1359072000000, y:10,label:'C1.1'},
            {x:1365116400000, y:30,label:'C1.2'},
            {x:1357516800000, y:40,label:'C1.3'},
            ],
        "bar":true,
        "key":"Carrier1"

        },
        {
          "values":[
            {x:1359072000000, y:30,label:'C2.1'},
            {x:1365116400000, y:10,label:'C2.2'},
            {x:1357516800000, y:79,label:'C2.3'},
            ],
          "bar":true,
          "key":"Carrier2"

        }
        ];


text:
Q: Access sql groupby I Have a Table1
 pbsc   qty   wt

 pbsc1   1    0
 pbsc2   2    10
 pbsc3   1    0
 pbsc2   2    9
 pbsc1   0    8
 pbsc4   9    9

I'm trying to get 2 results sets(2 query tables) from Table1
Sum up qty and wt if pbsc has similar data,for that query i used

SELECT Table1.pbsc, sum(Table1.qty) As quantity , sum(Table1.wt) As
> Weight
>       FROM Table1 group by Table1.pbsc;

which gives me
pbsc    quantity    Weight
pbsc1   1             8
pbsc2   4            19
pbsc3   1             0
pbsc4   9             9

But i'm trying to get only pbsc1,pbsc2 as one result set since they occur more than once in a Table1, as result1
  pbsc    qty    wt
  pbsc1     1     8
  pbsc2     4     19

result2 should be like (since pbsc3,pbsc4 occur only once)
  pbsc   qty   wt
  pbsc3   1    0
  pbsc4   9    9

A: --More than one pbsc.
SELECT Table1.pbsc,
       sum(Table1.qty) As quantity ,
       sum(Table1.wt) As  Weight
  FROM Table1
 group by Table1.pbsc
 having count(*) > 1;

--Only one record for pbsc.
SELECT Table1.pbsc,
       sum(Table1.qty) As quantity ,
       sum(Table1.wt) As  Weight
  FROM Table1
 group by Table1.pbsc
 having count(*) = 1;

A: SELECT Table1.pbsc,
       SUM(Table1.qty) AS Quantity,
       SUM(Table1.wt) AS  Weight
FROM Table1
WHERE Table1.pbsc IN (psc1, pbsc2)
GROUP BY Table1.pbsc

SELECT Table1.pbsc,
       SUM(Table1.qty) AS quantity,
       SUM(Table1.wt) AS  Weight
FROM Table1
WHERE Table1.pbsc IN (psc3, pbsc4)
GROUP BY Table1.pbsc


text:
Q: OpenCV Android - color issue using CameraBridgeViewBase I'm encountering a strange problem using Android emulators & OpenCV CameraBridgeViewBase.
Using onCameraFrame I get a picture that looks like it wasn't decoded properly.
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    return inputFrame.rgba();
}

Using 'inputFrame.gray()' I get what's expected - black and white image without artifacts or any other issues.
That's what I get:

One more picture (a bigger one)
What I've tried so far:

*

*Different API levels (from 15 up to 21).

*Different emulators: Genymotion & Google Android emulator.

*Different platform architectures - both ARM and Intel x86.

*Launching emulator on different laptop with Linux: it works as expected, the issue is gone!

*Launching apps, using OpenCV, downloaded from Play Store. They DO work! However:

*

*Launch app that works as expected, then close it.

*Launch your app (or one of the OpenCV tutorials), then close it.

*Launching app from the 5.1 again I see that it's affected by the same bug!

*Different OpenCV versions (2.4.9 and 2.4.10).

*Different versions of the OpenCV manager (one from the Play Store and 2.4.9 & 2.4.10 from OpenCV package).

*Finally, as I noticed in 5.2, precompiled tutorial .apk files from the OpenCV package are affected by the issue too.

Everything works as expected on my real android devices.
After looking at sources of the CameraBridgeViewBase and Java/Native camera classes I came to the decision that the problem occurs while decoding image. Probably there is a problem with platform-specific camera output format (YUV, NV21). However, it's strange that .gray() gives out a proper image (without artifacts).
I'm using Mac OS X 10.10 Yosemite and MacBook Air with "Facetime HD" camera if that matters.
Any ideas on how to overcome this problem & help in finding the root of the problem are greatly appreciated!

A: So, after drilling into the problem I've found the root of the issue.
Let's take a look at the OpenCV JavaCameraView class and its CameraBridgeViewBase base class.
The problem was that camera frames received as byte[] array in onPreviewFrame method were decoded incorrectly.
The exact place of code where the decoding process takes place is an implementation of the Mat rgba() method in inner JavaCameraFrame class of the JavaCameraView:
    public Mat rgba() {
        Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
        return mRgba;
    }

As we see, Imgproc.cvtColor(...) method is used in order to convert frame from YUV to RGBA. NV21 YUV -> RGBA conversion takes place there. During the initialization process we set the format to NV21, so this should be right. Moreover, every Android device should support NV21. Also, we can check whether device accepted the format using debugger:
protected boolean initializeCamera(int width, int height) {
    ...
    params.setPreviewFormat(ImageFormat.NV21);
    ...
    mCamera.setParameters(params);
    ...
    params = mCamera.getParameters();
    Log.d(TAG, String.format("Actual preview format is 0x%X", params.getPreviewFormat()));
}

Both phone (HTC Sensation) and emulator reported to be using NV21 indeed.
However, if we change COLOR_YUV2RGBA_NV21 to COLOR_YUV2RGB_I420 (YV12 and I420 is the same thing, just with Y and V inverted;) we'll see that emulator will get a proper color space finally.  Changing NV21 to YV12 in params.setPreviewFormat(ImageFormat.NV21); we'll get similar results. Looks like there's bug either in Imgproc.cvtColor, or in Android.
Here comes the solution.
Change public Mat rgba() the following way:
    public Mat rgba() {
        if (previewFormat == ImageFormat.NV21) {
            Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGBA_NV21, 4);
        }
        else if (previewFormat == ImageFormat.YV12) {
            Imgproc.cvtColor(mYuvFrameData, mRgba, Imgproc.COLOR_YUV2RGB_I420, 4);  // COLOR_YUV2RGBA_YV12 produces inverted colors
        }
        return mRgba;
    }

previewFormat is a new int variable, it's declared this way:
private int previewFormat = ImageFormat.NV21;

Add following changes to the initialization:
protected boolean initializeCamera(int width, int height) {
        ...
                params.setPreviewFormat(ImageFormat.NV21);
                // "generic" = android emulator
                if (Build.BRAND.equalsIgnoreCase("generic")) {
                    params.setPreviewFormat(ImageFormat.YV12);
                }
                ...
                mCamera.setParameters(params);
                params = mCamera.getParameters();
                previewFormat = params.getPreviewFormat();
        ...
}

Important:
Please note: this is just a temporary solution in order to make OpenCV usable with emulator in my case. Further research should be done. It's quite easy to check whether device uses correct image format in onPreviewFrame. I'll get back to this when I have some time.

A: For those of you who use genymotion, the BRAND won't be call generic.
To solve this just simply change the code to
...
if (Build.BRAND.equalsIgnoreCase("generic") | Build.BRAND.equalsIgnoreCase("Android")) {
...

and it should works, or just printout the BRAND you are using and replace it on the "Android"
P.S The second condition will include the case that you are using genymotion which is also an emulator.
Cheers

A: This issue is fixed now in the code in git, as the Pull Request https://github.com/opencv/opencv/pull/8168 has been merged. It should be available in the next released version.


text:
Q: how to add list values to existing dictionary in python Im trying to add each values of score to the dict names i,e score[0] to names[0] and so on...
names=[{'id': 1, 'name': 'laptop'}, {'id': 2, 'name': 'box'}, {'id': 3, 'name': 'printer'}]
score = [0.9894376397132874, 0.819094657897949, 0.78116521835327]

Output should be like this
names=[{'id': 1, 'name': 'laptop','score':0.98}, {'id': 2, 'name': 'box','score':0.81}, {'id': 3, 'name': 'printer','score':0.78}]

How to achieve this? thanks in advance

A: I'd do it with a comprehension like this:
>>> [{**d, 'score':s} for d, s in zip(names, score)]
[{'id': 1, 'name': 'laptop', 'score': 0.9894376397132874}, {'id': 2, 'name': 'box', 'score': 0.819094657897949}, {'id': 3, 'name': 'printer', 'score': 0.78116521835327}]

A: Without list comprehension.
for i, name in enumerate(names):
    name['score'] = score[i]

print(names)

A: This is an easy-to-understand solution. From your example, I understand you don't want to round up the numbers but still want to cut them.
import math

def truncate(f, n):
    return math.floor(f * 10 ** n) / 10 ** n

names=[{'id': 1, 'name': 'laptop'}, {'id': 2, 'name': 'box'}, {'id': 3, 'name': 'printer'}]
score = [0.9894376397132874, 0.819094657897949, 0.78116521835327]
n = len(score)
for i in range(n):
    names[i]["score"] = truncate(score[i], 2)

print(names)

If you do want to round up the numbers:
names=[{'id': 1, 'name': 'laptop'}, {'id': 2, 'name': 'box'}, {'id': 3, 'name': 'printer'}]
score = [0.9894376397132874, 0.819094657897949, 0.78116521835327]
n = len(score)
for i in range(n):
    names[i]["score"] = round(score[i], 2)

print(names)


text:
Q: SMS Open Up With Message I have created an application that uses the SMS and after the user clicks the sms button it opens up with my number already in and no message (thats their job). But when it loads up the sms message page it set the curser thing is up where the recipients are not where the message is. To explain that better, after the sms loads if they were to just start typing they would be adding another person to send the message to, not typing the message. For example if I would like to load up to a specific row on my UIPicker on startup I would:
[picker selectRow:3 inComponent:0 animated:NO];

sms load up:
- (IBAction)sms {
    MFMessageComposeViewController *textComposer = [[MFMessageComposeViewController alloc] init];
    [textComposer setMessageComposeDelegate:self];
    if ([MFMessageComposeViewController canSendText]) {
        [textComposer setRecipients:[NSArray arrayWithObjects: @"support@nicmacengineering.com", nil]];
        [textComposer setBody:@""];
        [self presentViewController:textComposer animated:YES completion:NULL];
    } else {
        NSLog(@"Can't Open Text");
    }
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    switch (result) {
        case MessageComposeResultCancelled:
            NSLog(@"Cancelled");
            break;
        case MessageComposeResultFailed:
            break;
        case MessageComposeResultSent:
            break;
        default:
            break;
    }
    [self dismissViewControllerAnimated:YES completion:NULL];
}

A: First, your question is fairly hard to understand. Here's my impression of it:

Can I set the cursor to the message field by default in an SMS controller?

And the answer is:
No.
Since it is an Apple framework, with no public method to switch fields (here's the class reference).
Because of this, you won't be able to automatically set the position of the cursor.


text:
Q: Warning:  is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements I have a problem with React, I've added some Bootstrap form and got the error. I know that there is a lot of the same problems but didn't find solution.
<Card className="mb-3 border-dark">
            <Card.Header as="h5">Personal Informations</Card.Header>
            <Card.Body>
              <Form>
                <Form.Row>
                  <Form.Group as={Col} variant="flush">
                    <Form.Label as="h5">Name</Form.Label>
                    <Form.Control as="elementType">{patient.name}</Form.Control>
                  </Form.Group>

                  <Form.Group as={Col} variant="flush">
                    <Form.Label as="h5">Age</Form.Label>
                    <Form.Control as="elementType">{patient.age}</Form.Control>
                  </Form.Group>

                  <Form.Group as={Col} variant="flush">
                    <Form.Label as="h5">Sex</Form.Label>
                    <Form.Control as="elementType">{patient.sex}</Form.Control>
                  </Form.Group>

                  <Form.Group as={Col} variant="flush">
                    <Form.Label as="h5">Birth</Form.Label>
                    <Form.Control as="elementType">
                      {patient.birth}
                    </Form.Control>
                  </Form.Group>
                </Form.Row>
              </Form>
            </Card.Body>
          </Card>

A: You can use the read-only, plaintext version of
Form.Control:

*

*the value must be supplied as value, not as a child

<Form.Control plaintext readOnly value={patient.name} />>

A: The as prop is expecting an element, not a type.  If using a standard HTML element, use lowercase.  If using a custom react component of your own construction, it expects an uppercase name, as that is what is required by react for it to know its a custom component and not an existing HTML element.


text:
Q: Flagging cells in grid (Minesweeper in plain JavaScript + p5.js framework) I've been trying to make a function that flags cells when right-clicked. I already have the rightclick and all the stuff. The only problem is that all the revealed cells get flagged on click.
If you have any questions with p5.js, visit the reference here.
I have this for now:

sketch.js
var grid;
var cols;
var rows;
var w = 40;

var totalBoom = 10;

function make2DArray(cols, rows) {
  var arr = new Array(cols);
  for (var i = 0; i < arr.length; i++) {
    arr[i] = new Array(rows);
  }
  return arr;
}

function setup() {
  createCanvas(400, 400);
  cols = floor(width / w);
  rows = floor(height / w);
  grid = make2DArray(cols, rows);
  for (var i = 0; i < cols; i++) {
    for (var j = 0; j < rows; j++) {
      grid[i][j] = new cell(i, j, w);
    }
  }

  var spots = [];
  for (var i = 0; i < cols; i++) {
    for (var j = 0; j < rows; j++) {
      spots.push([i, j]);
    }
  }

  for (var n = 0; n < totalBoom; n++) {
    var index = floor(random(spots.length));
    var choice = spots[index];
    var i = choice[0];
    var j = choice[1];
    spots.splice(index, 1);
    grid[i][j].boom = true;
  }

  for (var i = 0; i < cols; i++) {
    for (var j = 0; j < rows; j++) {
      grid[i][j].adjacentCells();
    }
  }
}

function gameOver() {
  for (var i = 0; i < cols; i++) {
    for (var j = 0; j < rows; j++) {
      grid[i][j].revealed = true;
    }
  }
}

function win() {
  if (boom.checked = true) {

  }
}

function mousePressed() {
  if (mouseButton == LEFT) {
    for (var i = 0; i < cols; i++) {
      for (var j = 0; j < rows; j++) {
        if (grid[i][j].hasBoom(mouseX, mouseY)) {
          grid[i][j].showBoom();

          if (grid[i][j].boom) {
            gameOver();
          }
        }
         else if (mouseButton == RIGHT) {
          console.log("RIGHTCLICK");
        }
      }
    }
  }
}

function draw() {
  background(200);
  for (var i = 0; i < cols; i++) {
    for (var j = 0; j < rows; j++) {
      grid[i][j].show();
    }
  }
}

cell.js
function cell(i, j, w) {
  this.i = i;
  this.j = j;
  this.x = i * w;
  this.y = j * w;
  this.w = w;
  this.neighborCount = 0;

  this.boom = false;
  this.revealed = false;
  this.checked = false;
}

cell.prototype.show = function () {
  stroke(0);
  noFill();
  rect(this.x, this.y, this.w, this.w);
  if (this.revealed) {
    if (this.boom) {
      fill(floor(random(10, 200)), 0, 0);
      ellipse(this.x + w * 0.5, this.y + w * 0.5, this.w * 0.5);
    } else {
      fill(125);
      stroke(12);
      rect(this.x, this.y, this.w, this.w);
      if (this.neighborCount > 0) {
        textAlign(CENTER);
        textSize(this.w * 0.5);
        fill(0);
        text(this.neighborCount, this.x + this.w * 0.5, this.y + this.w * 0.75);
      }
    }
  }
}

cell.prototype.adjacentCells = function () {
  if (this.boom) {
    this.neighborCount = -1;
    return;
  }
  var total = 0;

  for (var xoff = -1; xoff <= 1; xoff++) {
    for (var yoff = -1; yoff <= 1; yoff++) {
      var i = this.i + xoff;
      var j = this.j + yoff;
      if (i > -1 && i < cols && j > -1 && j < rows) {
        var neighbor = grid[i][j];
        if (neighbor.boom) {
          total++;
        }
      }
    }
  }
  this.neighborCount = total;
}

cell.prototype.hasBoom = function (x, y) {
  return x > this.x && x < this.x + this.w && y > this.y && y < this.y + this.w;
}

cell.prototype.showBoom = function () {
  this.revealed = true;
  if (this.neighborCount == 0) {
    this.floodFill();
  }
}

cell.prototype.floodFill = function () {
  for (var xoff = -1; xoff <= 1; xoff++) {
    for (var yoff = -1; yoff <= 1; yoff++) {
      var i = this.i + xoff;
      var j = this.j + yoff;
      if (i > -1 && i < cols && j > -1 && j < rows) {
        var neighbor = grid[i][j];
        if (!neighbor.boom && !neighbor.revealed) {
          neighbor.showBoom();
        }
      }
    }
  }
}

If you want to see how the code is running, click here

By the way, don't use class constructors or any of these shenigan code thingies, they confuse me ;-;

A: After going through your code, I found that you have a nested loop inside the mouseevent method which is used to detect the current clicked cell and need the correct index for different action based on the RIGHT | LEFT click.
You are checking for the RIGHT click inside the condition of LEFT click and it will never be true. So, here is a modified code.
function mousePressed() {
    for (var i = 0; i < cols; i++) {
      for (var j = 0; j < rows; j++) {
        /*
         * on every mouse event, we go through each cell.
         * If the click is RIGHT we will mark it check and get out of the loop.
         */
        if(mouseButton == RIGHT) {
          grid[i][j].checked = true;
          return;
        }
        if (grid[i][j].hasBoom(mouseX, mouseY)) {
          grid[i][j].showBoom();

          if (grid[i][j].boom) {
            gameOver();
          }
        }
      }
    }
}


text:
Q: Computation of the moment of order 3 of Gamma distribution https://i.gyazo.com/9ab33847b7a2f8f7378f12e1ab5960b9.png
A continuous random variable $X$ has the $\mathsf{Gamma}(\alpha, \lambda)$ distribution with probability density
$$f_X(x) = \frac{\lambda^\alpha}{\Gamma(\alpha)}x^{\alpha - 1}e^{-\lambda x},
\text{ for } x > 0.$$
Prove from first principles that $E(X^3) = \frac{\alpha(\alpha + 1)(\alpha + 2)}{\lambda^3}.$
I don't know what it means when it says from first principles. Any help? Thanks.

A: Given that $$f(x)=\frac{\lambda^\alpha}{\Gamma(\alpha,\lambda)}x^{\alpha - 1}e^{-\lambda x},
\text{ for } x > 0$$
and
$$\Gamma(\alpha,\lambda)=\lambda^{\alpha} \int_0^\infty x^{\alpha-1} e^{-\lambda x}\,dx = \lambda^{\alpha} \left( \left[ \frac{x^{\alpha} e^{-\lambda x}}{\alpha} \right]_0^{\infty} + \int_0^\infty \lambda \frac{x^{\alpha} e^{-\lambda x}}{\alpha}\,dx \right) = \frac{1}{\alpha} \Gamma(\alpha+1,\lambda).$$
We see that $$E(X^3)=\int_0^{\infty} x^3 f(x)\,dx = \frac{\int_0^{\infty} \lambda^{\alpha} x^{\alpha+2} e^{-\lambda x}\,dx}{\Gamma(\alpha,\lambda)}.$$
Note that $\int_0^{\infty} \lambda^{\alpha+3}x^{\alpha+2} e^{-\lambda x}\,dx = \Gamma(\alpha+3,\lambda)$ so our numerator is $\frac{\Gamma(\alpha+3,\lambda)}{\lambda^3}$ and
$$E(X^3) = \frac{\Gamma(\alpha+3,\lambda)}{\lambda^3 \Gamma(\alpha,\lambda)} = \frac{\alpha(\alpha+1)(\alpha+2)}{\lambda^3}.$$
QED.


text:
Q: Configure Yarn with Hadoop 2.7.4 resources issue I have configured hadoop 2.7.4 by following this tutorial. DataNode, NameNode and SecondaryNameNode are working properly.
But when I run yarn, NodeManager goes down with the following message

org.apache.hadoop.yarn.exceptions.YarnRuntimeException:
  org.apache.hadoop.yarn.exceptions.YarnRuntimeException: Recieved
  SHUTDOWN signal from Resourcemanager ,Registration of NodeManager
  failed, Message from ResourceManager: NodeManager from  localhost
  doesn't satisfy minimum allocations, Sending SHUTDOWN signal to the
  NodeManager.

My system has 8 cpu with 8 GB RAM. How to configure yarn with these resources? I have found a lot such as this but could not find any solution that solve my problem.

A: I had the same problem during a course. We were using Amazon virtual machines with 2 cores.
After various modifications in yarn-site.xml, we got our NodeManager running setting the following properties
<property>
    <name>yarn.nodemanager.resource.memory-mb</name>
    <value>4096</value>
</property>

<property>
    <name>yarn.nodemanager.resource.cpu-vcores</name>
    <value>2</value>
</property>

In your case, you may need to establish 8 virtual cores.