How to set a generic list of a type to a generic list of its interface?

Question: How to set a generic list of a type to a generic list of its interface?
I have a Car class which inherits from ICar.
I have a Client class which accepts a List<ICar> objects in the constructor, I don't want to explicitly write List<Car> for the Client class.
But it's not possible to set
var carsList = new List<Car>();
List<ICar> cars = carsList // compile error
var client = new Client(cars);

How would you achieve this?
I realized if I make it IList it would work but I'd have to explicitly cast my carsList object.
Comment: http://stackoverflow.com/questions/2033912/c-sharp-variance-problem-assigning-listderived-as-listbase
Answer: You're not going to be able to use the .NET Framework List and doing the type of implicit conversion you want.
I'll steal something from another thread to demonstrate the fundamental problem:
Consider:
List<Animal> animals = new List<Giraffe>();
animals.Add(new Monkey());

Or using your code:
interface ICar{}
class Car:ICar{}
class BatMobile:ICar{}

List<ICar> cars = new List<Car>()
cars.Add(new BatMobile()) // We can't add a BatMobile to a List of Car.

IEnumerable is ok with this type of variance because you ensure the user cannot modify the collection via the IEnumerable interface. With a list this cannot be guaranteed.
https://stackoverflow.com/a/2033931/299408
Answer: You can't directly cast a List<Car> to a List<ICar>, because you could try to add a OtherCar to your List<ICar> hiding a List<Car> and that wouldn't work.
Instead you could:

Make the constructor parameter a covariant interface, such as an IEnumerable<Car>, and create a list from it inside the constructor, or
Convert the list outside the constructor via List<ICar> cars = carsList.ToList<ICar>();
Answer: there are three way exists:
1) define carsList as List<ICar>
2) use framework 4.0 and IEnumerable<ICar>
3) manually convert

Answer: Define the list as a List of ICars...
var carsList = new List<ICar>();
List<ICar> cars = carsList; // compile error gone :)

Answer: You have to do it the other way around.
var carsList = new List<ICar>(); // Hey, why not?
var client = new Client(cars);

Have you tried casting?
List<ICar> carsList = (List<ICar>)implementationList;


Was Tendulkar's infamous "shoulder before wicket" the right decision?

Question: What does "Shoulder Before Wicket" mean in cricket?
Why was Sachin Tendulkar's dismissal against Australia considered "Shoulder Before Wicket" and was it the right decision?
Answer:
What does "Shoulder Before Wicket" mean in cricket?

In terms of the Laws of Cricket, "shoulder before wicket" means nothing at all; it is not a term defined within the Laws.

Why was Sachin Tendulkar's dismissal against Australia considered "Shoulder Before Wicket"[?]

In terms of the official results, it wasn't. As the scorecard shows, Tendulakar was dismissed lbw. However, as Tendulkar was dismissed as a result of being hit on his upper arm while ducking a bouncer, the media have not unsurprisingly called this shoulder before wicket.

was it the right decision?

There are really two questions here:

Can a batsman be dismissed "lbw" even if it is not their leg which the ball contacts? This one is a definite "yes"; quoting from Law 36.1:

The striker is out LBW if [...] the striker intercepts the ball, either full-pitch or after pitching, with any part of his/her person.

(my emphasis)*.

Was the ball going to hit the wicket? No-one will ever really know the answer to this, but Daryll Harper, the umpire gave him out so he was out.

* Pedantically, you would need to refer to the 1980 Code of the Laws for the wording which applied when Tendulkar was dismissed. The older Codes used to be on the MCC site but I can't find them any more. However, the spirit of the wording hasn't changed since then even if the exact words may have done.


Get all linearlayout child elements

Question: I have layout:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:fillViewport="true">
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical"
  android:id="@+id/exchangeView">

     <TextView
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:background="#fff000"
         android:gravity="center"
         android:text="Sticker 1"
         android:textColor="#372c24"
         android:textSize="20dp" />

  <LinearLayout
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:gravity="bottom"
   android:layout_alignParentBottom="true"
   android:orientation="horizontal"
   android:id="@+id/next">

   <Button
   android:id="@+id/btn_next"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:layout_weight="1"
   android:layout_alignParentBottom="true"
   android:text="Next" />

  </LinearLayout>
 </LinearLayout>
</ScrollView>

and related code:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.exchange);

    layout = (View) findViewById(R.id.exchangeView);
}

next thing I want to do is to get all children elements in this layout with Id=exchangeView, but when I type layout.getChildCount() android studio IDE compiler says:

Cannot resolve method 'getChildCount()'

However, if I put breakpoint on line where I assign layout a value, then if I evaluate expression I can execute method layout.getChildCount()

All I want to do is to execute layout.getChildCount() during runtime.
Thanks in advance!
Answer: You can try to use getChildCount() and also getChildAt() like this may be
int childcount = ll.getChildCount();
for (int i=0; i < childcount; i++){
  View v = ll.getChildAt(i);
}

Answer: Change this line
layout = (View) findViewById(R.id.exchangeView);

to
layout = (LinearLayout) findViewById(R.id.exchangeView);

I am assuming you have declared the variable layout as
View layout;

If so, change that to
LinearLayout layout;

The View class doesn't have the method getChildCount(), it is a method in the ViewGroup class. LinearLayout extends ViewGroup, and hence has access to it. View does not. This is related to polymorphism, which I suggest you look up.
Cheers.
Comment: Yeap, that was the reason of my issue. Thanks a lot!
Answer: Try this:
LinearLayout layout = setupLayout();
int count = layout.getChildCount();
View v = null;
for(int i=0; i<count; i++) {
    v = layout.getChildAt(i);
    //do something with your child element
}

Get all linearlayout child elements


Language selector for Apache Solr search form

Question: How can I do something like this with Apache Solr in Drupal 7?

This will be the front page of my site, and depending on the language the user chooses, he will be redirected to the language-specific subdomain of my site with the respective search results:

en.mysite.com/search/search=type+here&lang=en
es.mysite.com/search/search=type+here&lang=es
jp.mysite.com/search/search=type+here&lang=jp

Of course, only results with the user's language should be shown.
Answer: The Solr Multilingual module should do what you appear to want.

... provides a way to offer language-specific searches for different
  languages at once on multilingual websites ...

I'm using the not-yet-released 7x dev version with some success.  A registered-user's primary language selection, or override from a drop-down in the site-wide menu sets a $var which I carry through to the Solr search module, language-specific content, and Drupal language overlays for standard markup, etc.


Not receiving emails after latest update "CRM Online 2015 Update 1"

Question: This weekend had Update 1 for my organization on CRM Online 2015 (220.127.116.1149) and since then we are not receiving emails into CRM. We use email router, everything has been checked, version, tested connection, approved emails, .... . We are able to send emails from CRM but we are not getting responses back.
Anyone else going through the same problem? Any ideas to get it solved?
We use Gmail for most of our mailing and POP/SMTP through EmailRouter to get it in and out of CRM.
Already opened a service request, but last response was "an internal investigation was submitted to our Operations Team...." with no estimate for a response time.
Thanks in advance,
Comment: To make things worse, not just haven't received a response back from Microsoft Support, but now can't send emails neither.

Error Log: 10/23/2015 10:36:15 : #23379 - Could not verify the version of Microsoft Dynamics CRM at https://disco.crm.dynamics.com/yourorgname. An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.
Answer: In this case updating the Email Router was the problem. Looking into windows update noticed EmailRouter was updated (Update 1.1 - 7.1.0001) the day before the problem started. Looking further about this update found this thread.
Uninstalling Update 1.1 resolved the issue.
Also disabled automatic updates for other Microsoft products on windows update settings.
Comment: Disable auto updates on prod Environments is highly recommended, it's very Forrest Gump.
Answer: I solved a similar issue (crm online, upgrade to 7.1, router no longer working) doing this:

delete all configurations inside email router
update email router to latest version (it wasn't the latest)
re-create all configurations from scratch, ending up with the exact same settings I had before


Can someone provide an example for the ImageCompare methods?

Question: I'm attempting to compare two images using Visual Studio 2013 Pro. The MSDN provides information (http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.uitesting.imagecomparer.compare.aspx) on ImageComparer.Compare, alas I'm failing to get it implemented in my code. On the last line of my code I'm told that "The name 'Compare' does not exist in the current context". Can someone please help? Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UITesting;

namespace Intranet.SmokeTests
{
public class Intranet_Login : Intranet_Setup
{
    public List<string> IntranetLoginTest(string BrowserURL, string Host, int Port)
    {
            Image expected = Image.FromFile(@"\\webdriver\ImageVerification\Expected\IntranetHome.png");
            Image actual = Image.FromFile(@"\\webdriver\ImageVerification\Actual\IntranetHome.png");

            bool equal = Compare(actual, expected);
    }
}
}

Answer: You must do it like this:
bool equal = ImageComparer.Compare(actual, expected);

When you want to use a class's static member in c# you must always qualify it with the class first. Otherwise the compiler will try to locate the member on the current class.
Another problem you might be having with your IntranetLoginTest is that it's supposed to return an instance of List<string>, but it doesn't. I must also say I find it strange that you are making an image comparison test in a method that would suggest it performs authentication mechanisms testing.
Comment: When I try that, I get the same error. I suspect that I'm missing a reference or something 'minor'. But I've already added the Microsoft.VisualStudio.TestTools.UITesting reference to the project.
Comment: You can't possibly be having the *exact* same error. In this case if you missed a reference then the message would be that `ImageComparer` cannot be found. In any case, make sure your test project has a reference to Microsoft.VisualStudio.TestTools.UITesting. If it does and that your `Using` statements on top of your file are the same as in your example, this should compile just fine. Otherwise you're having another problem, elsewhere.
Comment: In that case it seems like my problem is elsewhere... Thanks for confirming my thoughts.
Comment: @WarioX You are welcome but still I'm very curious what your problem could be. :) If you can share whatever new information / error message you have using my solution I'll be glad to help.
Answer: 1- Using nuget Install System.Drawing.Common
2- Reference Microsoft.VisualStudio.TestTools.UITesting.dll from C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\Extensions\TestPlatform
        Image expected = Image.FromFile(@"2020-09-01_15h31_24.png");
        Image actual = Image.FromFile(@"2020-09-01_15h31_30.png");
        Image difference = null;

        var isTestPass = ImageComparer.Compare(actual, expected, out difference);

        if (!isTestPass)
            difference.Save("diff.png");

        Console.ReadLine();

Expected

Actual

Difference
Answer: It turns out that the correct version of the referenced dll was not being added. The complete answer is here: How can I make the namespace locally match what is listed on MSDN?


Special Characters in File Paths on Windows (c++)

Question: I seem to be stuck on special characters (like äöü) in windows file paths. They are legal names for folders (users can set them).
A part of my program has to be able to traverse the filesystem. When trying to enter a childfolder with the name 'öö' (testcase) I get the error that the directory does not exist.
I am rather sure that the problem is this 'line':
wstring newPath = oldPath + ffd.cFileName + L"\\";

From
void reevaluateJob(wstring newPath) {
    WIN32_FIND_DATA ffd;
    HANDLE findFileHandle = FindFirstFile((newPath + L"\*").c_str(), &ffd);
    //skipping invalid case handling and loop
    if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
        if ((wcscmp(ffd.cFileName, L".") != 0) && (wcscmp(ffd.cFileName, L"..") != 0))
            reevaluateJob(newPath + ffd.cFileName + L"\\");  //<=== new path here
    } else {
        //skipping file part
    }
}

Because printing the new path (or ffd.cFileName as wstring) results in different characters. Is there another data type that doesn't have this problem?
EDIT:
This works totally fine as long as the folder names do not contain special characters (like äöü etc.).
Comment: The `L"\*"` doesn't look like real code. Also, it indicates that `newPath` is not backslash-terminated. That's most likely the basic error here. In addition you have probably introduced a misinterpretation of your data by "printing" the `wstring".
Comment: L before a string is used for an extended character set. http://stackoverflow.com/questions/6384118/what-does-the-l-in-front-a-string-mean-in-c
Comment: I'll randomly guess that newPath + ffd.cFileName is missing a backslash.  Debugger ought to be helpful.
Comment: Did you try using `#define UNICODE`?
Comment: @Cheersandhth.-Alf Does using wstring break chars like üöä? I use wcout << path; as output.
Comment: @Arkbob: using `wstring` doesn't break those characters. but output using `wcout` translates to the active narrow codepage of the console. most likely you have a default active code 437. if so then what you see in the console is not what you have internally. well i already said this, misinterpretation. check it out.
Comment: @ArnonZilca: `\*` is not a valid escape sequence.
Answer: As pointed out by @ArnonZilca, #define UNICODE solved half of the problem. Sadly not all windows functions stick to that rule. Some also want #define _UNICODE.
In the process of trying to fix the problem, I also changed my whole code to use WCHAR* instead of wstring. I assume (but cannot be 100% sure) that this does NOT make a difference.
Comment: I just changed back to an older version of my code. Using wstring works too, as long as there is #define _UNICODE and #define UNICODE at the top.
Comment: Huh.  Ordinarily I would expect the compiler to define those for you.  Perhaps your build settings are wrong?
Comment: I start using c++ lik 5 days ago. So it's just a fresh visual studio 2013 with a windows console c++ project.
Comment: In Configuration Properties, under General, what does it say for "Character Set"?  What about "Preprocessor Definitions" under C/C++ Preprocessor?  C/C++ Command Line shows you the command line for the compiler; does it include `/D "_UNICODE"` and `/D "UNICODE"` ?


How does Markov random field (bs=mrf) in mgvc gam handle repeated measures on the spatial units?

Question: I am attempting a spatio-temporal model in mgcv gam.
I am using a factor smooth to define each of 27 areal units in a shapefile ("id") as subjects (essentially) which have undergone 23 repeated measurements in time ("year").
I am using the Markov random field to define the neighbor relationships of the area units.
I have combed through Wood (2017) and other resources and have not found an answer to my question, which is: how is the mrf handling the repeated measures?  My model is:
model <- gam(response) ~ s(year) +
                         ti(year,id, bs="fs", m=1) +
                         s(id, bs = 'mrf', xt = list(nb = neighbors), k=5),
                         family=tw(), data=data)

Thank you.
Answer: The neighbors object defines, for the levels of id, which other locations are neighbours of the $i$th id. Your data object contains a an id for each observation. The MRF defines a spatial effect such that the effect of the MRF for any unit varies smoothly over the neighbours of that unit. This implies that the MRF is smooth over neighbouring units of those neighbours and so on.
How smooth the MRF is will depend on the rank of the MRF; if you estimate a low-rank MRF (use fewer knots than levels of id - 1) the field will be smooth, increasingly so the fewer the knots. If you fit a full-rank MRF then you will get a "rougher", with effectively one coefficient per unit.
How this plays out in the model, and you can see this if you use predict() with type = "terms", is that for a particular id the MRF smooth contributes the same value/effect to the fitted value for all of the 23 observations for that particular id.
You will get a similar effect if you put a fixed effect factor into the model; all the observations from id == 1 will get a contribution to the fitted value for belonging to that level of id (typically the intercept plus the coefficient for the $i$th level of id if observation is not from the reference level of the factor). Similarly, if you included a factor random effect; the fitted value for each observation is pulled up or down relative to the model intercept by some amount given by the "estimate" of the random effect for the unit that it belongs to.
The difference between the factor fixed effect or random effect and the MRF is that the MRF takes into account the spatial arrangement (or any other arrangement you can represent as a graph) of the levels of the factor.
Specifically for your model, the low-rank MRF effect is constant over the year observations. The factor smooth interaction  given by the ti(year, id, bs = 'fs', m = 1) (this could really be s(year, id, bs = 'fs', m = 1)) implies a factor random effect (random intercept) plus a random smoother for year for each observation. The random intercept component of this smoother will account for non-spatial differences in the expected values due to the units.
If you wanted the MRF to vary over time, then you'd need to include it as a tensor product with the year term, for example:
te(year, id, bs = c("tp", "mrf"),
   xt = list(year = NULL, id = list(nb = neighbors)))

This doesn't include the random year smooths, which if you just wanted to estimate the smooths and not have the global smooth of year would be
te(year, id, bs = c("fs", "mrf"),
   xt = list(year = NULL, id = list(nb = neighbors)))

Doing the global smooth plus difference smooth of year and the MRF is trickier.
Comment: Dear Dr. Simpson, thank your for this answer.  Seeing was believing with predict ( ),
Comment: (sorry hit enter too soon before) Dear Dr. Simpson, thank you for this answer.  Seeing was believing with predict ( ), type="terms".  Also I had almost gotten there with the time-varying mrf but hadn't figured out the xt = list(year = NULL... so that was most helpful. If I may ask a follow-up question: how concerned should a modeler be with the high concurvity (>= 0.9) between a global smooth of year and among random terms that include year or year/space?


How to show that for $a,b\in \mathbb{C}: |a-b|=|1-a\overline{b}| \Leftrightarrow |a|=1 \, \lor \, |b|=1$

Question:
How to show that for $a,b\in \mathbb{C}: |a-b|=|1-a\overline{b}|
 \Leftrightarrow |a|=1 \, \lor \, |b|=1$

I defined $a:=x+iy$ and $b:=u+iv$ which resulted in quite an algebra mess. Is there a simpler method to solve such statements?
Answer: $$|a-b|=|1-a\overline{b}|$$
$$\Longleftrightarrow(a-b)(\overline{a}-\overline{b})=(1-a\overline{b})(1-\overline{a}b)$$
$$\Longleftrightarrow (a\overline{a}-1)(b\overline{b}-1)=0$$


Huge memory usage when running huggingface transformers run_language_modeling.py with GPT2

Question: I tried to test run_language_modeling.py with a small test file and it run out of memory after using more than 32 GB of RAM. Why does it need so much RAM or what am I doing wrong?
Command line:
python run_language_modeling.py --output_dir foo --model_type gpt2 --model_name_or_path gpt2 --do_train --train_data_file test.txt --no_cuda --eval_data_file test.txt

Testfile size: 29600 bytes, 546 lines.
With the original OpenAI implementation I have no problem to run the training script.
Answer: Their new run_clm.py script does not have the problem and the old script seems now to be unsupported anyway.


Is $\frac{n!}{\left(n/2\right)!\left(n/2\right)!}$ a natural number for $n$ even?

Question: Probably this is a easy question, but I was unable to solve it. Let $n$ be a even natural number. Is true that the following number is natural for all $n$? $$\frac{n!}{\left(n/2\right)!\left(n/2\right)!}$$
I can see, for example, that $(n/2)!$ divides $n!$, but then I can't conclude by using this arguing.
Thank you
Comment: It's a binomial coefficient, hence an integer.
Comment: Yes, because the symmetric group on $n$ objects contains a direct product of two copies of the symmetric group on $n/2$ objects (those fixing the first $n/2$ objects and those fixing the last $n/2$ objects).
Comment: Also, $k!$ divides any product of $k$ consecutive integers. (which is due $\begin{pmatrix}n\\k\end{pmatrix}$ being an integer, of course.)
Answer: Yes, it is. Suppose that $n=2m$; then
$$\frac{n!}{(n/2)!(n/2)!}=\frac{(2m)!}{m!m!}=\binom{2m}m\;,$$
which is the number of $m$-element subsets of a set of $2m$ things. This clearly must be an integer. For more information, see the Wikipedia article on binomial coefficients.
Comment: So simple, thank you.
Comment: @Tomás: You're welcome.
Answer: Yes. This is just $\displaystyle {n \choose n/2}$.


prove that $f(x)=\sum_{|\alpha|\leq k}\frac{1}{\alpha !}D^{\alpha}f(0)x^{\alpha} + O(|x|^{k+1})$

Question: If $\alpha$ is multiindex and $f$ is smooth,prove that $f(x)=\sum_{|\alpha|\leq k}\frac{1}{\alpha !}D^{\alpha}f(0)x^{\alpha} + O(|x|^{k+1})$. The hint is to use taylors form for $g(t)=f(tx)$. If i do this i will found that
$g(t)=\sum \frac{g^{n}(0)}{n!}t^n = \sum \frac{ D^nf(0)x^n t^n}{n!}$. How i continued? i need to do induction over size of $\alpha$. Any hint please, thank you.
Comment: You incorrectly computed $g^{(n)}(0)$ (note that $f^{(n)}$ does not make sense since $f$ is a multivariate function). Be careful when using the chain rule with the total derivative.
Answer: The key is to show using the chain rule that $$g^{(n)}(0) = \sum_{|\alpha| = n} D^\alpha f(0) x^\alpha.$$
Combining with your first step and plugging in $t=1$ yields $$f(x) = g(1) = \sum_{n \ge 0} \frac{1}{|\alpha|!}\sum_{|\alpha| = n} D^\alpha f(0) x^\alpha.$$
Can you take it from here?
Comment: I think that need a litle more please, don't need induction over size of $\alpha$ thank you


Entity frame work CreateDatabase() methode does not create stored procedure

Question: I have a SQL Server 2008 DBMS, and I have created an EDM (generated from the database), my application is almost finished and everything works great.
However, in my application, I want to let the end-user create the database so I created a form to let the user specify the server and database name and provided a create button. When the user clicks the create button, a new database is created on the specified server. To do this, I have used the CreateDatabase() method like this:
string connString = ...;
MyEntity context = new MyEntity(connString);
context.CreateDatabase();

The code works and the database is created. My problem is that this method does not create stored procedures. Please help me and let me know if there is another way to do this.
P.S.: when I generated the EDM from the database, I chose it to be included in the EDM and I used the function import to use this stored procedure in my code to ensure that it is included in my EDM.
Answer: This will never ever create stored procedures for you. How should EDMX know what logic was included in stored procedures? One characteristic of stored procedures is that they wrap / hide their implementation so the caller knows only the name, parameters and result but not internals. You must include creation script for stored stored procedures as separate file / resource and execute it after the database is created.
Comment: Yes you are right, sorry this was a stupid question how i didn't think of that.thank you very much


Playing instrument voices through PC from my keyboard

Question: I wanted to play different instrument voices from my Yamaha P-115 Digital Pianoby connecting it to a PC. So I asked for suggestions, and people said, "Get a DAW."
So I downloaded LMMS from lmms.io, which seems to be a free DAW, and recommended by many.
Now, I downloaded lmms, but can't figure out how to get and play different instrument voices. It talks of projects, soundfonts, VSTs and what not. I don't want to produce music, I am not recoding and saving any project. Just want to play live from my digi piano or a MIDI keyboard (not purchasing unless I get this right).
Any pointers? Thanks.
Comment: Which OS are you using? On Windows, any simple MIDI sequencer should be able to route a MIDI input to the built-in software synthesizer.
Comment: I'm on Windows 10.
There is a built-in synthesizer in Windows 10??!!
Comment: Yes, you should have a "Microsoft GS Wavetable SW Synth", which uses a castrated version of the samples of the Roland SC-55 (i.e., it is, er, better than nothing). But you'd still need software to be able to connect the MIDI ports.
Answer: The P115 will allow you to play through a computer. Though it doesn't have native  MIDI ports it does have a MIDI USB driver which will allow the keyboard to be recognised as a MIDI device in your computer. So start by installing the USB-MIDI driver supplied by Yamaha for your instrument.
Now, as aleeady commented, to play a software instrument in the PC you don't strictly need  DAW.
Some software instruments ("soft synths" for short) can operate in standalone mode. In that case you just need to install the software and configure it to use your keyboard as MIDI input. There are some free standalone synths out there, and many commercial ones.
For example sforzando is a free soundfonts player that can run in standalone. Soundfonts is a standardised file format for sample based synthesis and there are literally  thousands of free sounfont files (.sfz extension) out there in the web. So a soundfonts standalone player is the simplest way to play many different sounds in the PC using your kb as a controller.
Another possible approach is to use a so called plugin instrument host. Many soft synths support one  (or several) types of sw interface(s) that allows them to be called and used in a integrated way with a host program.
In order just to perform (i.e. no recording and no editing of music), a dedicated host program is suficcient, a  fully fledged DAW is not required.
The most common plugin interface in use nowadays is the VST standard, so a VST host program is most advisable for this approach.
VSThost is a free and excellent VST host program. So get this program and install it and start looking for VST compatible soft synths. Sforzando also supports VST, so it can be used in this approach too. But there are thousands of free VST compatible synths, just search the Web for "free VST synths" (and welcome to the "yet another VST to play with" syndrome :-)
Now, a DAW is not strictly required, but most DAWs  (or all, depending on your definition of DAW) are also hosts for VST and probably some other plugin interfaces.
So just get a plugin soft synth and install so that it is recognised by the DAW (in the simplest case a .DLL file is to be copied to a plugins folder).
In any of the three approaches described, the keyboard has to be configured in the software  (standalone synths,  VST host or DAW) as a MIDI input device, so don't forget that step.
Just to wrap up, LMMS (which I didn't know and from the description seems to be quite a nice product, so thanks for showing that) advertises VST native support, soundfonts native support and a couple of soft synths integrated in the package. So it's just a matter of following the configuration steps above without the need for any additional software.


Is there a simple `parallel for` in golang like OpenMP?

Question: I'm trying to optimise a puzzle with parallel processing, for better performance.
Ideally, in C99 w/ OpenMP, I should be able to do that with the help of a #pragma omp parallel for prior to a for loop in question, and then it should be up to the system to distribute the load between the CPUs.
The official documentation for Go at https://golang.org/doc/effective_go.html#parallel, however, seems to suggest that for parallel processing I must, (0), manually get the number of cores from the runtime environment, (1), loop over said cores, (2), effectively code up a distinct for loop for each core, (3), loop over the cores once again to make sure all the stuff got processed.
Am I missing something?  For the simplest case, is OpenMP with the ancient C superior to the brand new Go that's touted as C's best replacement?  For a more complicated example, how exactly do you split up a range between the CPUs?
Comment: @Amd, superficial edits (as well as introducing spelling mistakes) are against ToS
Answer: Effective Go is outdated about that, Go automatically sets GOMAXPROCS to the number of processors (you can still manually set it to force the number you want).
Here's a very simple example for parallel processing of a slice:
data := make([]float64, SZ)
var wg sync.WaitGroup
for i := range data {
    wg.Add(1)
    go func(v *float64) {
        // note that using rand is a bad example because global rand uses a mutex
        *v = rand.Float64()
        wg.Done()
    }(&data[i])
}
wg.Wait()

playground
Comment: @cnst http://stackoverflow.com/questions/14298523/why-does-adding-concurrency-slow-down-this-golang-code
Comment: Note also that this example code, above, is creating goroutines. Please understand that goroutines are not like native operating system threads, they are an abstraction above them. The runtime time-slices the goroutines across cpu cores, avoiding you from doing that explicitly. In many cases, having an excess number of goroutines w.r.t the number of cores is a good thing (indeed there is theoretical work to support this [Valiant and others]).
Comment: looks good, however, i've tried it, and it doesn't seem to offer any performance increase, my for loop over about 2k elements actually runs 39 seconds and still uses only 12.5% of CPU (according to top), whereas a non-go-routine version completes in 29 seconds.


C# Excel VSTO - Deselect all cells

Question: So when you open an Excel Workbook, each sheet saves the last selection of cells you made from the previous time you used the sheet.  In C#, i would like to deselect (de-focus, whatever...)  all cells in every sheet.
Answer: There's always an active cell on the sheet which is active. The only thing you can do is select the least annoying cell, such as the first one.
Comment: Thanks. I did that, and saved the initial state before starting the add-in (using activesheet, activecell) and just return to the saved state after I do my work.

C# Excel VSTO - Deselect all cells


Hermite's solution of the general quintic in terms of theta functions

Question: Can someone point me at or produce a translation or modern exposition of Hermite's solution of the general quintic in terms of theta functions? (the "before" and "after" steps are on the mathworld page for the quintic, but I'm interested in Hermite/Kronecker's process/proof)
Comment: I'm currently far away from my library, but as I seem to recall [these](http://www.springerlink.com/content/978-0-8176-4836-7/) [two](http://books.google.com/books?id=fcp9IiZd3tQC) books tackle the solution of the quintic via modular/theta functions.
Answer: David Mumford's three volumes of "lectures on theta..." or some similar title, published by Birkhauser c. 1980, give a good more-general context for using modular forms to solve algebraic equations of all degrees. He gives careful attributions, which at the moment I do not remember, and do not have those at home to look at.
Comment: I have the first volume, all digitally: /Tata Lectures on Theta/: the second contains Hiroshi Umemura's /Resolutions of Algebraic Equations by Theta Constants/.
Answer: See Beyond The Quartic by R. Bruce King (Birhauser)


How to transform formulas with vectors systematically

Question: I am learning PCA and I encounter this formula transformation in the derivation
$\sum_{i=1}^{n}(w^Tx_i)^2=w^T(\sum_{i=1}^{n}x_ix_i^T)w$
If I concretize $i$ with 3 and assume $x \in R^{3x1}$ and $w \in R^{3x1}$...then I can expand this formula and see their equivalences. But with shaky background in linear algebra, I can' really derive this formula myself. How can I learn to handle vector/matrix calculation in such forms in general? I know this last question might be too big, but I would like to know whether I just need more practice or there is some systematic method that I don't know.
Answer: I'd say:  Get familiar with the formalism  of vector and matrix manipulations,  but not tied to a particular space dimension  (3  in your example), or a particular coordinate system.
For instance, the identity you presented stems from simple manipulations:
$$
\begin{split}\sum_{i=1}^{n}(w^Tx_i)^2  &= \sum_{i=1}^{n}(w^Tx_i)(w^Tx_i)\\
&=\sum_{i=1}^{n}(w^Tx_i)(w^Tx_i)^T&\quad\text{(because }w^Tx_i\text{is just a number)}\\
&=\sum_{i=1}^{n}(w^Tx_i)(x_i^Tw)&\\
&=\sum_{i=1}^{n}w^T(x_ix_i^T)w&\quad\text{(associative property)}\\
&=w^T\left(\sum_{i=1}^{n}x_ix_i^T\right)w&\quad\text{(distributive property)}
\end{split}$$
Note that not once have I relied on computing the particular component of a vector or product.  I haven't relied on a particular dimension of  the space. It's all a certain formalism that you need to get used to. And for that, you need practice.


Chaining amplifiers together

Question: I just bought an Ampeg B5R head and I'm curious about how to combine this with my Ampeg V4. I want to use both amps to get more volume.
Both amps have the "POWER AMP INPUT" and "PREAMP OUTPUT" features, but do either of these actually allow both amps to be used at the same time? It seems like these features simply substitute one amp's preamp for the other, or one amp's power amp for the other.
The manual for the B5R says that when the PREAMP OUTPUT is in use:

Using this output does not break the connection to the internal power amplifier

It seems like this is the way to use two amps at once if you do not have a stereo output pedal or splitter, but I'm not sure.
Whether I use this method or get a splitter to send a signal to both amps, I'm still not clear on what output configuration to use.
Both amps support two 1/4" outputs, but only the V4 has an impedance switch.
The cabinet (Ampeg SVT-410HLF) I'm using takes two 1/4" inputs but it's not clear what the impedance is for one or both when looking at the back panel.
How do I connect these two amps to the cab without blowing something up?
Answer: Important note: You can't connect both amps to that cab without blowing something up. You need two cabinets.
There are some cabinets that support bi-amping, which is using two amps with one cabinet. Your cabinet does not. Your cabinet has two 1/4" inputs wired together in parallel so you can daisy-chain additional cabinets.
Yes you can drive both power amps from one preamp by connecting the preamp out from one head to the power amp input on the other head. When you do this, the head that you take the preamp out from is the one you should plug your bass into. The gain and EQ controls on that head will be the ones that control the sound, the preamp and its controls on the other head will be bypassed.
Then you can plug the speaker outputs of each head to separate speaker cabinets.

Now let's talk about making your rig louder. In order to make your rig sound twice as loud by buying more amps, you have to increase your total wattage by ten times. That means if you have a 100 Watt head now, you'll have to have a total of 1000 Watts to double the loudness of your current head. Plus you'll have to have speakers that can handle that load.
A much better way to increase loudness is to get a better speaker cabinet that is more efficient and reproduces more high frequencies. Yes, I wrote higher frequencies. If you are pumping lots of Watts but still can't hear your bass, then the problem is more likely EQ than power. Make sure you're not cutting your highs and mids too much and just boosting lows. High mids are very important for making the bass heard with the rest of the band. You mainly want the lows to go with the kick drum.
Try turning that high frequency control on the back of your cabinet all the way up
After looking through all your links and gear, I recommend using the B5R only, buy and use a Speakon cable (because 1/4" speaker cables are bad and dangerous at high levels - dangerous to gear, not people) to connect the B5R to your cabinet, crank that high frequency control on the back of the cabinet all the way up, and work with the Ultramid control on the B5R to make yourself heard. Yes, you'll "only" be pushing 300 Watts RMS into 4 Ohms, but you'll have a good amount of headroom which is worth solid gold for bass and PA amplification.
Comment: @JacobIRR Tube output stages that have impedance switches are allowing you to select from multiple taps on a single output transformer. Transistor driven solid state outputs do not need to have a transformer, since they are inherently low impedance.
Comment: The calculation to get twice as loud - not too sure about that. Agreed that 200watts is only half as much power again compared with 100 watts. But loudness isn't directly related to number of watts, I don't think. And if it is, then that's only when everything is flat out - a rare occurrence. The speakers themselves will have a very important bearing on actual volume, some being far more efficient than others. So, just using more efficient speakers in itself should give more volume. Would any of this make sense?
Comment: @Tim I wrote in my answer that more efficient speakers are the way. 10 times the power (Wattage) results in a 10 dB increase in output intensity ("SPLs"), assuming there is headroom available for that, which is roughly heard as twice as loud by most listeners. Finding a more efficient speaker cabinet and/or increasing the headroom of the rig to have more dynamic range is a much better option. Actually, with a 2 Ohm cabinet with the same sensitivity and the B5R head, that might be about twice as loud, since the B5R can do 500W RMS into 2 Ohms and probably peaks around 1000W.
Comment: That all makes sense. I'm curious about how to know what impedance I'm using. If you look at the back of the B5R, it says "300w @ 4ohms, 500w @ 2ohms". How do you "access" these various impedances?
Comment: @JacobIRR The impedances are the impedances of whatever cabinet you plug the B5R into. The B5R is a solid state head that probably uses BJTs or similar output transistors which have very low output impedances, below 2 Ohms. The only reason why there's a 2 Ohm load minimum is because as you decrease the impedance you increase the operating current and overcurrent will burn out the output transistors, otherwise the amp could run into very low impedances. Tube amps like the V4 are different and should be impedance matched from the output transformer to the speaker cabinet.

Chaining amplifiers together


Proving that a relation is or is not an equivalence relation

Question: So I have relation $R$ that is defined by $aRb$ if $ab>0, a,b \in Z-${$0$}
and I get that it's only an equivalence relation if
$aRa$
$aRb \rightarrow bRa$
$aRb, bRc \rightarrow aRc$
but I'm not sure how I can prove that it is or is not an equivalence relation. What steps are sensible to take, and how can I define the equivalent classes of the equivalence?
Comment: What have you tried? It is very easy to check the first two conditions. Here's a hint for the third one: In which cases is the product of two integers >0? Either both of them are positive or both of them are negative.
Comment: I just hadn't understood what the relation of the assignment and the rules the statement had to pass were, but Fabio Somenzi helped me understand it
Answer: To verify whether $R$ is an equivalence relation, you check each property in turn.
Let's start with the reflexive property and take $a \in \mathbb{Z} - \{0\}$.  Is it true that $aa > 0$?  Of course; hence $aRa$ and $R$ is reflexive.
For symmetry, you ask, "if $ab > 0$ is it true that $ba > 0$?"  I'm sure you can answer that.
For transitivity, you ask, "if $ab > 0$ and $bc > 0$ is it true that $ac > 0$?"  This takes a moment's thought to decide.  If $a$ and $b$ have the same sign, and $b$ and $c$ have the same sign (so that their products are positive) what can we say of the signs of $a$ and $c$?
Reformulated this way, the answer should be easy to get to.
As for the equivalence classes of $R$, if you followed the argument above, you probably noticed that the sign of a nonzero integer is really all that matters in deciding whether it is related to another nonzero integer.  This means that there are very few equivalence classes for $R$.  Can you see them?
Comment: You got it.  Those are the two equivalence classes.
Comment: Those will work for the positive numbers.  You could also write $\{\, a \in \mathbb{Z} \mid a > 0 \,\}$ and $\{\, a \in \mathbb{Z} \mid a < 0 \,\}$, or $\{\, a \mid a \in \mathbb{N} - \{0\} \,\}$ and $\{\, a \mid -a \in \mathbb{N} - \{0\} \,\}$.  There are other ways as well.
Comment: You are describing sets of integers.  What you call the variables, as long as you are consistent, doesn't matter.  In particular, $\{\, a \in \mathbb{Z} \mid a > 0 \,\}$ and $\{\, b \in \mathbb{Z} \mid b > 0 \,\}$ denote the same set.  You only need one of them.  Including both only cause confusion.
Comment: Would the equivalence classes then be "All positive integers" and "All negative integers" - if I've correctly understood of equivalence classes are applied to rules and vise versa.
Comment: How would one express this? I was thinking something along the lines of {$a \in N-${$0$}} and {$b \in N-${$0$}} and the same for negative integers, but I'm quite sure that this is at least lacking something
Comment: Is it enough for me to do it solely for $a$, or is it expected to include all related variables which would be in this case, $a$ and $b$?


Socket.io P2P connection in nodejs (more than one ports on same server)

Question: I want to ask that on a Socket.io P2P connection in node.js when two clients connected on the same server, It is possible that they are connected by different ports on the same server.and can share means chat with each other.
Comment: Wierd question, If a node server is running, it can only open one port, so the answer is simply no if you have asked the question correctly. I would read up on how socket.io works, https://socket.io/
Comment: thanks for your answer.....
Answer: You can do this by creating multiple instances of the node.js server and initialize multiple instance os socket.io on each of the ports
<code>var app = require('express')();
var http1 = require('http').Server(app).listen(8080);
var http2 = require('http').Server(app).listen(9090);
var io1 = require('socket.io')(http);
var io2 = require('socket.io')(http);
</code>
But then also as there will be a single process all the requests will be ultimately transferred from the main port only. The original server.  Due top this there is no benefit of using more then one socket.
Refer this for more info
Comment: I am also trying this for the first time and haven't tried it for chatting. I don't actually think it will work due to the link I posted. But you can always give it a shot. Work or not you will learn something new


Table locking again, am I doing it correct?

Question: I had a problem with table locking, solved in this question:
Table 'watchdog' was not locked with LOCK TABLES on custom module
I want to share my current code, because I'm still not sure if I am doing it correct.
I have two tables:

eventi_list, for storing users reservation for selected event if there are free places of this event
eventi_wait, for storing users reservation if there are no free places for selected event. If any user withdraw her/his reservation, the oldest reservation for current event (if exists) from this table move to eventi_list table.
function eventi_book($nid) {
    $nid = (int) $nid;
    if (_eventi_if_node($nid)) {
        global $user;
        $uid = (int) $user->uid;
        $is_booked = _eventi_is_booked($uid, $nid);
        if (! $is_booked) {
            $is_booked = _eventi_is_booked($uid, $nid, 'eventi_waits');
        }
        if (! $is_booked) {
            db_query('LOCK TABLES content_type_event WRITE, eventi_list WRITE, eventi_waits WRITE, watchdog WRITE');
            $amount =  _eventi_places_amount($nid);
            if ($amount > 0) {
                _eventi_add($uid, $nid);
                db_query("UPDATE {content_type_event} SET field_event_places_amount_value = field_event_places_amount_value - 1 WHERE nid=$nid");
              //  cache_clear_all();
            } else {
                _eventi_add($uid, $nid, 'eventi_waits');
            }
            db_unlock_tables();
        }
    }
   // _eventi_redirect_to_prev();
}

function _eventi_if_node($nid) {
    $query = db_query("SELECT COUNT(nid) as count FROM {node} WHERE nid=$nid AND type='event'");
    $result = db_fetch_array($query);
    return $result['count'] > 0;
}

function _eventi_is_booked($uid, $nid, $tbl_name = 'eventi_list') {
    $tbl_name = '{'.$tbl_name.'}';
    $query = db_query("SELECT count(nid) AS count FROM $tbl_name WHERE nid=$nid AND uid=$uid");
    $result = db_fetch_array($query);
    return $result['count'] > 0;
}

function _eventi_places_amount($nid) {
    $query = db_query("SELECT field_event_places_amount_value AS amount FROM {content_type_event} WHERE nid=$nid");
    $result = db_fetch_array($query);
    return (int) $result['amount'];
}

function _eventi_add($uid, $nid, $tbl_name = 'eventi_list') {
    $tbl_name = '{'.$tbl_name.'}';
    $t = time();
    return db_query("INSERT INTO $tbl_name (uid, nid, created_at) VALUES($uid, $nid, $t)");
}

I want to make sure that I never end up with negative number of free places of selected event.
So I have to atomic access to places amount:
$amount =  _eventi_places_amount($nid);

and then I can update places amount, when I am sure that $amount is greater than 0:
db_query("UPDATE {content_type_event} SET field_event_places_amount_value = field_event_places_amount_value - 1 WHERE nid=$nid");

I don't like this solution, because I must to lock many tables. Is there a better way of doing this in Drupal?
Comment: You still have possible security issues in your code, re-read http://drupal.stackexchange.com/questions/2806/table-watchdog-was-not-locked-with-lock-tables-on-custom-module/2809#2809 and http://en.wikipedia.org/wiki/SQL_injection
Comment: You may want to look at transactions in mysql, and possibly post this to a mysql specific forum. It looks like your issue is there rather than drupal and you may get better advice.
Comment: Thanks you guys for help. I'll correct my code to be more secure just in case.
Answer: MyISAM performs a table-level lock to do any SQL on a MyISAM Table.
If you convert everything to InnoDB, row-level locking is implicitly done for you. Multiversioning Concurrency Control (MVCC) allows each user to lock only row(s) needed.
Additionally, you may want to perform all atomic writes in a BEGIN...COMMIT transaction to group together several table updates as one unit. That's what InnoDB will do for you. InnoDB is ACID complaint. The A stands for ATOMICITY, a transaction's ability to be atomic.


Rule to send an email on node save printing a field value of a referenced node

Question: I am using Drupal 7, and the modules References and Rules.
I created two content types: A and B.
A has a field (A:b_nodes) which is multiple node references of B which has field (B:time).
How can I configure a rule so that when A is saved, an email will be sent with body text like the following:
<code>here are the B nodes time data contained in A

B1 : 2 januari 2013
B2 : 5 may 2013
B3 : 15 august 2013
</code>
Answer: Go to /admin/config/workflow/rules/reaction/add and create a rule. Then in rules action section under system category select Send email. Then you will be redirect to a new page, here you can define the subject,content,recipient of mail. By using Replacement Patterns you can add dynamic variable in to mail content.
Comment: I've done that. But the email only show B1 - B3 title. the time is empty...


Inverse Trigonometry System of Equations

Question: $$2\tan^{-1}\left(\sqrt{x-x^2}\right) = \tan^{-1}\left(x\right)\: +\, \tan^{-1}\left(1-x\right)$$
I have a feeling solution includes drawing triangles but cannot make the leap to get the solution
Comment: What are you trying to do? Solve that equation for $x$?
Answer: Take tangent of both sides (apply double angle and sum of angle formula and remember that $\tan(\tan^{-1}y) = y$):
$$\frac{2\sqrt{x-x^2}}{1 - (x-x^2)} = \frac{x+1-x}{1-x(1-x)}$$
and solve that equation.
Comment: @JeffreyChiu Does my edit help?
Comment: How did you get the above equation? Could you elaborate what you did after simply taking the tangent?
Comment: @JeffreyChiu : He used the double-angle formula and the sum of angles formula for tangent.
Comment: Yes I see now, thanks a lot
Comment: @Deepak, Taking tan can be erroneous, right as $\tan(m\pi+u)=\tan u$ for integer $m$
Comment: @labbhattacharjee Would taking $\frac{2\sqrt{x-x^2}}{1 - (x-x^2)} = \frac{x+1-x}{1-x(1-x)} + k\pi, k \in \mathbb{Z}$ fix this issue?
Comment: @Deepak, It can not be arbitrary $k$. Please check one of the links in my answer.
Answer: We need $x(1-x)\ge0\iff x(x-1)\le0\iff0\le x\le1$
$\implies\dfrac{x+1-x}2\ge\sqrt{x(1-x)}$
Now use $$\arctan x+\arctan y= \arctan\frac{x+y}{1-xy}$$ if $xy<1$
See Inverse trigonometric function identity doubt: $\tan^{-1}x+\tan^{-1}y =-\pi+\tan^{-1}\left(\frac{x+y}{1-xy}\right)$, when $x<0$, $y<0$, and $xy>1$
OR  showing $\arctan(\frac{2}{3}) = \frac{1}{2} \arctan(\frac{12}{5})$


Can a C# Safe Navigation Operator (?.) be used to check if Object is null, as well as property?

Question: This is mainly a syntactic sugar/best-practice question.
Here is a code example in question:
if (_instanceData?.DataSourceType != null && Util.IsEntityBacked(_instanceData.DataSourceType) {// code}

I understand that the safe navigation operator will continue execution if _instanceData is null, but in this case will the first boolean in the conditional be evaluated as expected?  Is this going to successfully null check on both _instanceData and DataSourceType?
Another Example:
if (LockAcquired && _instanceData?.ObjInfo != null) {// code}

In this case, it is possible that _instanceData is null, or it is not, but ObjInfo is null.  Is it better practice to just old-fashioned null check both object and property, or will this get the job done as expected?
edit: The question is better described as:
Is if (obj?.prop != null) equivalent to
 if (obj != null && obj.prop != null)
Comment: It's not entirely clear to me what you're asking - but in the first example, if either `_instanceData` or `_instanceData.DataSourceType` is null, then the result of `_instanceData?.DataSourceType` will be null, so the first operand of the `&&` operator will be evaluate to false, so the second operand won't be evaluated.
Comment: You seem to see a difference between an object and a property ? There isn't any, the ?.Operator can be applied to objects or structs, not matter where they come from, also from properties. "Save navigation" is a curious title for the operator.
It just saves you to writte if (x!=null && x.y != null && x.y.z!=null) to if (x?.y?.z != null). It means `If  value is already null the result of the expression is null, otherwise  take the value of the following member`.
Comment: If that isn't enough information, I suggest you try to put together a [mcve] - which I suspect will answer your question anyway, just by running it.
Comment: Your above code snippets are valid and is the expected use case.
Comment: `?.` isn't doing anything at all to `DataSourceType`. Your `!= null` check is doing that. but like others have said, it's not clear what you're actually asking.
Comment: The name `safe navigation` comes from the fact that you can navigate to nested properties safely without exception if somewhere along the tree resolves to null. The name comes from the fact that it saves you layering `if` blocks to get to some inner property. It saves a bit of space for conditional expressions like this scenario but it can save dozens of lines when just accessing a property far down an object tree.
Comment: @Jake you can check what IL converts your code into from here https://sharplab.io/
Answer: The first is equivalent to
if (_instanceData != null && _instanceData.DataSourceType != null && Util.IsEntityBacked(_instanceData.DataSourceType) {// code}

The second is equivalent to
if (LockAcquired && _instanceData != null && _instanceData.ObjInfo != null) {// code}

So it will check if _instanceData is null, then check if _instanceData.DataSourceType is null, then the last condition. As you said, this is just syntactical sugar so you don't have to write two != null conditions. The IL code that results is exactly the same, so its a matter of preference whether or not to use the operator.
It does save a TON of space when accessing deeply nested properties, which is where its most useful
if(Parent != null)
{
    if(Parent.Child != null)
    {
        if(Parent.Child.GrandChild != null)
        {
             Parent.Child.GrandChild.GreatGrandChild.name = "Parent IV";
        }
     }
}

becomes
Parent?.Child?.GrandChild?.GreatGrandChild.name = "Parent IV";

Saves a lot of space! Even if you collapsed all the ifs into one statement it still saves loads of keystrokes and screen noise.


Como colocar login em projeto WEB asp.Net MVC No Authentication?

Question: Bem, criei um projeto WEB e de início imaginei que não iria ser necessário acrescentar o sistema de login, então usei o template No Authentication (até aí tudo bem...). O problema é que agora eu gostaria de acrescentar o login sem ter que migrar meu projeto para um novo. Não sei se fazendo manualmente o módulo de login ele ficaria realmente seguro. Alguém pode me ajudar?
Comment: Ficar fica, mas antes preciso saber se você gostaria de usar um *template* comum de projeto ASP.NET MVC ou faz questão de escrever manualmente o seu mecanismo.
Comment: Prefiro usar o _template_ mesmo.
Comment: Posso escrever uma resposta mais dentro do seu problema ou algo mais didático. O que prefere?
Comment: Obrigado desde já meu amigo. Bem, eu gostaria de resolver meu problema, mas também gostaria de aprender um pouco mais. Você teria tempo e disponibilidade para fazer algo bem didático? (Obs: Sou iniciante)
Comment: Parece que o @CiganoMorrisonMendez vai fazer.
Answer: Como resposta mais simples e que dá menos trabalho, o melhor seria gerar uma outra solução com Individual User Accounts e transferir os fontes da solução antiga para a solução nova, mas vale a pena adensar a explicação para o caso de uma solução totalmente customizada de autenticação.
A segurança é um aspecto que pode sim ser obtido através da implementação manual do seu próprio esquema de autenticação. Como o ASP.NET Identity é extensível, a alfaiataria se torna muito simples, embora o conjunto de elementos não seja). Apesar de bem trabalhosa, a reimplementação das classes pode ser muito vantajosa para quem quiser ter total controle sobre cada aspecto que envolve autenticação e informações relativas a ela. Apenas atente para o objetivo de cada componente, o que vou explicar abaixo.
Classe SignInManager
Esta é a classe que realiza a autenticação de fato. Ao gerar um projeto com Individual User Accounts, por exemplo, é gerado um Controller (AccountsController.cs) que faz uso de SignInManager. Até a data desta resposta, SignInManager não é documentada na MSDN. O que existe são exemplos e o código fonte. Mesmo os exemplos não são específicos para uma alfaiataria adequada.
No mesmo projeto gerado, temos ainda a seguinte classe que deriva de SignInManager:
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
    public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
        : base(userManager, authenticationManager)
    {
    }

    public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
    {
        return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
    }

    public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
    {
        return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
    }
}

Aqui:
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>

Especifico claramente que SignInManager irá usar como classe de usuários ApplicationUser, e o Id (identificador) de um usuário será string. Você poderia muito bem indexar usuário usando números inteiros, por exemplo. Basta mudar o tipo passado de string para int.
Já ApplicationUser é derivada de IdentityUser. Para o caso do Individual User Accounts, que é um projeto que usa Entity Framework, usar IdentityUser está ok. Caso seu projeto use outra tecnologia para abstração do banco de dados, ApplicationUser não poderia derivar IdentityUser.
Classe IdentityUser
IdentityUser implementa vários conceitos que podem deixar sua autenticação bem abrangente. O protótipo padrão da classe sem especificação das classes genéricas é:
public class IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser, IUser<string>

string é a representação da chave do usuário. Assim como em ApplicationSignInManager, estamos considerando que o identificador de um usuário é uma string;
IdentityUserLogin possui os dados de login e os dados de um provedor de login. Suponha que sua aplicação irá autenticar usando um login do Google. Esta classe permite que isto seja feito;
IdentityUserRole é uma classe que pode associar um usuário a uma Role (a melhor tradução para role é "perfil"). Isto existe para preservar o antigo esquema de permissionamento por perfil que existia na arquitetura anterior, conhecida como ASP.NET Membership;
IdentityUserClaim associa um usuário a uma claim. Em língua portuguesa, claim seria algo como uma "credencial", mas é mais granular que isso. Uma claim é qualquer informação que faz parte da identificação de um usuário na aplicação. Por exemplo, seu CPF pode ser uma claim. Seu RG também.

E como um usuário é criado? A resposta esta na próxima classe.
Classe UserManager
UserManager é uma (enorme) classe cujos métodos criam, alteram ou excluem qualquer usuário ou informações relativas a ele, como roles e claims. Para um verdadeiro esquema customizado dentro do ASP.NET Identity, é preciso reimplementar esta classe. A título de curiosidade, o fonte dela está aqui.
Outros Esquemas de Autenticação
O ASP.NET Identity pode ser tremendamente complexo para quem está começando a escrever sua própria camada de autenticação. Neste âmbito, vale a pena voltar um pouco atrás e dominar o ASP.NET Membership, mais limitado, porém mais simples. Aqui no site já dei várias respostas sobre ele que podem ser úteis:

Tela de login com membership e mvc5
Segurança e autorização usando Roles
Como criar uma página de login e senha no ASP.NET?
Comment: você é fera cara! Muito obrigado mesmo por toda essa explicação. Fiz tudo como o indicado, tive alguns problemas, mas consegui resolver lendo outras ajudas.
Answer: Se for usar o ASP.NET Identity, que é ótimo, veja esse post em que o usuário que recebeu a recompensa mostra como incluir o ASP.NET Identity de um template SEM o ASP.NET Identity - Sem autentição incluída - opção de template marcado com o No Authentication: Exemplo do ASP.NET Identity usando o SQL Server
Todavia, seria talvez interessante você criar um outro projeto do ASP.NET MVC com o ASP.NET Identity e copiar as classes e configurações. Por conta das mudanças que já teve.
Comment: Uma curiosidade sobre essa resposta que você mencionou. A pessoa na época não terminou a resposta e usou outro usuário dela mesma pra atribuir a recompensa. Vou escrever outra resposta mais completa.
Comment: @Cigano, interessante.
Comment: Ficarei muito grato!
Comment: Só não entendi o que tem haver.. rs
Comment: Na verdade preciso contar uma historinha aqui. O autor da pergunta na época pediu pra que a resposta ensinasse como fazer especificamente usando *No Authentication* mas sem entender o *Individual User Accounts*, então escrevi uma resposta explicando o *Individual User Accounts*. Embora seja a resposta aceita, o autor da pergunta tinha 2 usuários: um ele usava pra responder, e o outro pra votar a favor do primeiro e transferir reputação. Reparem que a resposta ficou pela metade. Ele nem fala de `SignInManager`, que é a parte mais importante da autenticação. Vou responder para ficar mais claro.
Comment: @Cigano, reclamação computada.
Comment: @Jedaias, siga ele que te ajudará
Comment: Ficarei na expectativa, mas desde já agradeço.


Botão Aplicar - Celulas visíveis

Question: Eu tenho um formulário onde há um Listview, e textbox para input de dados e já pelo login eu consigo filtrar uma coluna, pra aparecer apenas os campos que eu quero.
Onde vem o problema ? a intenção é, eu clicar na linha do ListView, inputar os valores de previsto e realizado e esse aplicar, colocar esse valor tanto no Listview (Que está funcionando) e Adicionar na linha filtrada no excel (que é o problema)
Ele não puxa a célula que eu selecionei, ele sempre joga na 1 célula do excel.. então no caso, acredito eu que preciso de alguma forma que este botão insira apenas valor na célula visível que eu selecionei.
Segue o print do formulário e o código do botão aplicar!

Private Sub CommandButton5_Click()
    Sheets("Treinamentos Tableau").Select

    Dim PosiçãoAtual As Variant
    PosiçãoAtual = Treinamentos.SelectedItem.Index + 1

    Cells(PosiçãoAtual, 3).Value = TextBox6.Text
    Cells(PosiçãoAtual, 4).Value = TextBox7.Text

    With Treinamentos
        .SelectedItem.SubItems(2) = TextBox6.Text
        .SelectedItem.SubItems(3) = TextBox7.Text
    End With

End Sub

---------------- EDIT, EXPLICAÇÃO COM OS PRINTS ---------------
Explicação 1 : Eu fiz o login e a senha, com uma unidade e ele filtrou apenas aquela unidade, correto ? logo eu vou clicar em cima da linha que quero, colocar os valores de previsto e realizado no textbox e clicar em aplicar.

Explicação 2 : Cliquei em aplicar, no listview, ele foi no local correto, show, tá em taquari, dezembro como foi a linha que selecionei

Explicação 3 : Quando eu vou na planilha do excel, ele não puxa a linha filtrada que eu inputei o valor, ele ta indo pra linha que eu não filtrei, que no caso tão pegando então as linhas invisíveis após eu aplicar o filtro
Comment: Não entendi muito bem, possui um [mcve]?
Comment: Coloquei uma explicação agora, completa e com prints Daniel.
Answer: Problema
Você está inserindo na planilha "Treinamentos Tableau" a posição da tabela ListView, porém,  não é essa que deve ser procurada. Pois os índices da ListView mudam ao filtrar, ou seja, não são os mesmos da planilha.
Solução
Realizar um loop nas células visíveis da planilha e verificar se a coluna "E" é igual ao valor selecionado Treinamentos.SelectedItem.SubItems(1). Se sim, preenche as colunas "C" e "D" com os valores de TextBox6.Text e TextBox7.Text, respectivamente.
Código
Este código de exemplo possui a parte de Autofiltro para a unidade, porém, como este filtro já é realizado. Esta parte pode ser retirada do código.
A explicação do código está comentado no mesmo.
Sub teste()
    Dim ws As Worksheet
    Dim unidade As String, data As String
    Dim UltimaLinha As Long, linha As Long
    Dim VisibleRange As Range

    Set ws = ThisWorkbook.Sheets("Treinamentos Tableau")
    'Inserir unidade, no seu caso o valor para filtrar
    unidade = "b"

    With ws
        'Encontra a ultima linha da coluna A
        UltimaLinha = .Cells(.Rows.Count, "A").End(xlUp).Row

        'Filtro Unidade
        .Range("A1").AutoFilter Field:=1, Criteria1:=unidade

        On Error Resume Next
        Set VisibleRange = .Range(.Cells(2, 1), .Cells(UltimaLinha, 1)).SpecialCells(xlCellTypeVisible)
        On Error GoTo 0

        If Not VisibleRange Is Nothing Then
            'Loop nas células visíveis após aplicação do AutoFiltro
            For Each Cell In VisibleRange
                'Linha
                linha = Cell.Row
                'Verifica se a coluna 5, ou seja, coluna Data é igual ao selecionado
                If Treinamentos.SelectedItem.SubItems(1) = .Cells(linha, "E") Then
                    'Se sim, escreve na célula de mesma linha
                    .Cells(linha, 3).Value = TextBox6.Text
                    .Cells(linha, 4).Value = TextBox7.Text
                End If
            Next
        End If
        '"zera" o autofiltro, mostrando todos dados filtrados
        If .FilterMode Then
            .ShowAllData
        End If
    End With
End Sub

Botão Aplicar - Celulas visíveis


What is the difference between normal MVC and Azure MVC forms authentication systems?

Question: I see in Visual Studio 2013 when creating a default MVC application and creating a Windows Azure cloud service MVC application that the Forms authentication tables differ:
Normal MVC:

UserProfile
webpages_Membership
webpages_OAuthMembership
webpages_Roles
webpages_UsersInRoles

Azure MVC:

AspNetRoles
AspNetUserClaims
AspNetUserLogins
AspNetUserRoles
AspNetUsers

Questions:

What is the name for each system (for Googling)?
Why are they different?
Which is the more recent\better system that I should use?

Even the code for AccountController.Register() differs:
Normal MVC:
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
WebSecurity.Login(model.UserName, model.Password);

Azure MVC:
var user = new ApplicationUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, model.Password);

Answer: The Azure way is called ASP.NET Identity and is MVC 5. The old way is called ASP.NET membership.
The new way is more powerful.
Resources are here: http://www.asp.net/identity/overview/getting-started/aspnet-identity-recommended-resources
Comment: ASP.Net Identity is not connected to Azure, stand-alone component. You can have web-applications in Azure with either Identity or with Membership. Makes no difference for the hosting platform.


Html content panel slide in

Question: Im looking to create an effect something similar to what is seen here
http://www.templatemonster.com/demo/42436.html
When a button on the nav bar is pressed the content slides in from the left hand side and rests in the center, when another button is pressed the new content does the same and the old content box leaves on the right hand side. Any help would be greatly appreciated, I tried making this by using a large slider but the navigation was off so any suggestion would be a huge bonus!
Comment: Maybe [this](http://twitter.github.com/bootstrap/examples/carousel.html) will help
Comment: I suggest using CSS3 animations as they will be much faster than jquery.  Basically add the class that animates the div to move in from the left and add a class to the current one that animates the div to move to the right.
Answer: A possible solution to this is to use the jQuery Plus Anchor plugin.
http://css-plus.com/2011/03/plusanchor-jquery-plugin/
Answer: create the menus correspondent divs in the same order as the menu items and give each of them divs same class, and css properties (width, height, position: absolute), then use this code:
<code>$(document).ready(function(){
$('.active').css('left', ($(window).width() - $('.active').outerWidth())/2);
$('li').click(function(){
var ind = $(this).index(),
    activeSlide = $('.active'),
    slide = $('.slide').eq(ind);
    if(!slide.hasClass('active')){
   slide.stop().animate({'left': ($(window).width() - slide.outerWidth()) / 2}, 300);
        activeSlide.animate({'left': $(window).width()}, 300, function(){
            activeSlide.css('left', - activeSlide.outerWidth());
        });
        activeSlide.removeClass('active');
        slide.addClass('active');
    }
});
$(window).resize(function(){
    $('.active').css('left', ($(window).width() - $('.active').outerWidth()) / 2);
});
});
</code>
see the DEMO here for more details about the HTML structure and CSS properties:
Comment: thanks again for your help! just a quick question, what if I wanted to start with a slide already open and in view, what would I change? sorry to bother you again
Comment: add second class active to the div which you want to show at page load and position it using css in jquery at document ready. see the updated code and demo, i also included resize function which you'd probably need when resizing the browser.
Comment: you are welcome :), i updated the demo, now li click change the style of the clicked menu item, see the updated demo if you need this feature or just use the code above if you don't need it.

Html content panel slide in


Featured Content block inside node

Question: I'm using Drupal 7 and trying to include the Featured Content block between the write up and the comments, i.e. I want it inside a node.
I tried the method explained here, but am not getting the block appear.
This is the code I've used in my node.tpl.php
<code>$block = module_invoke('featured_content', 'block_view', '1');
print render($block);</code>
The featured content block's URL contains this:
admin/structure/block/manage/featured_content/1/configure
Any suggestions? What could I be missing out?
Answer: As suggested in another post, I used this code:
<code>$block = block_load('featured_content', '1');
$output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
print $output;
</code>
This worked perfectly!

Featured Content block inside node


Allen Hatcher algebraic topology proof of theorem 4.5 Whitehead

Question: It was stated as the last answer in this post:
Idea behind the proof of Whitehead's Theorem and Compression Lemma
I copy here what is asked there:
I am reading as well the proof of Whitehead's theorem in AHAT and trying to grasp the idea of what happens in the general case when $f$ is not cellular without using cellular approximation.
The final line of the argument ''$( X \times I \sqcup Y, X \times \partial I \sqcup Y) \rightarrow (M_f, X \cup Y) \rightarrow (M_f, X)$ gives a deformation retraction of $M_f$ onto $X$'' is, if I understand right, quotient by $(x,1) \sim f(x)$ in the first arrow and the homotopy $g$ explained in the book in the second. Clearly, this composition would give the deformation retraction we seek if taking the quotient in the first arrow would give a homotopy equivalence, which I am not so sure why is so.. this may be an easy algebraic fact but I'm not on algebra so if it is a silly questions I excuse myself from now lol, anyway,  Thank you very much in advance for any help on this matter.
Comment: Could you please include the question in this post? So far it just says "It was stated".
Answer: Applying the compression lemma to the inclusion $(X \cup Y,X) \to (M_f,X)$, we obtain a homotopy rel $X$ from $X \cup Y \to M_f$ to a map $X\cup Y \to X$. Since $(M_f,X \cup Y)$ has the homotopy extension property, this homotopy extends to a homotopy rel $X$ from $\text{id}_{M_f}$ to a map $g:M_f \to M_f$ such that $g(X\cup Y)\subset X$. Now apply the compression lemma again to the composition
$$ g \circ q: (X\times I \amalg Y, X\times \partial I \amalg Y) \to (M_f, X\cup Y) \to (M_f, X)$$
where $q: X\times I \amalg Y \to M_f$ is the standard quotient map. Then we obtain a homotopy $F: (X\times I \amalg Y)\times I \to M_f $ rel $X\times \partial I \amalg Y$ from $g \circ q$ to a map $X\times I \amalg Y \to X$. Since the homotopy $F$ is "rel $X\times \partial I \amalg Y$", it passes to the quotient and induces a homotopy $\bar{F}:M_f \times I \to M_f$  rel $X\cup Y$ from $g$ to a map $h:M_f \to X$. Therefore, we have $\text{id}_{M_f} \simeq g \simeq h$ rel $X$, and hence $X$ is a deformation retract of $M_f$, as desired.
Comment: Ok, so taking the quotient is actually not necesarily a h.e., but being relative does not take into account what happens in there so taking the quotient does not affect the homotopy. Is this what you mean?
Comment: @Astro Yes, the map $q$ is not necessarily a homotopy equivalence. The significant fact is that $X\times \partial I \amalg Y$ is fixed during $F$, so $F$ can pass to the quotient (by the universal property of quotient spaces).
Comment: Thank you, that was exactly what I was missing from the facts.


Can't see database diagram in SQL Server 2008 R2 Management Studio

Question: I wonder how to enable database diagram in my SQL Server 2008 R2 database. When I create new db I am able to open database diagram:

but when I connect to existing db from Azure I can't generate database diagram:

It's connected with DB rights?
Comment: I don't think Azure supports database diagrams (among many other things). See [this blog post](http://alexandrebrisebois.wordpress.com/2013/10/26/create-database-diagrams-of-your-windows-azure-sql-databases/), for example.
Comment: Yes that is solution.
Answer: In database properties, do check if you are the owner - under "Files" tab.
When restored from another server, owner may not be the same.
Set yourself ("computer"\"user") as owner, there are your diagrams


Send a broadcast to an Activity that is not in the foreground

Question: I have a background service that has a CountdownTimer. As the CountdownTimer counts down i send a broadcast to an Activity. When the CountdownTimer has counted down then the Activity is alerted and i can stop the service and unregister the receiver.
I have moved the normal receiver unregistering method from onStop and onPause into my own method that i call once a broadcast is received with "timer_finished". This is so i can move away from the Activity without unregistering.
Everything works fine if the user is currently viewing the Activity. If the user moves away from the Activity, the CoundownTimer is still running but the Activity is not receiving the broadcasts.
How can I do this so that the Activity receives the final broadcast "timer_finished"?
<code>public class CountDownBroadcastService extends Service {

    private static final String TAG = CountDownBroadcastService.class.getSimpleName();

    public static final String COUNTDOWN_BR = "com.carefreegroup.rr3.countdown_br";
    Intent bi = new Intent(COUNTDOWN_BR);

    CountDownTimer cdt = null;
    Context mContext;

    @Override
        public void onCreate() {
            super.onCreate();

            mContext = this;

            Log.i(TAG, "Starting timer...");

            cdt = new CountDownTimer(10000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                    Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
                    bi.putExtra("countdown", millisUntilFinished);
                    bi.putExtra("timer_status", "timer_not_finished");
                    sendBroadcast(bi);
                }

                @Override
                public void onFinish() {
                    Log.i(TAG, "Timer finished");

                    bi.putExtra("timer_status", "timer_finished");

                    sendBroadcast(bi);

                }
            };

            cdt.start();
        }

        @Override
        public void onDestroy() {

            cdt.cancel();
            Log.i(TAG, "Timer cancelled");
            super.onDestroy();
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            return super.onStartCommand(intent, flags, startId);
        }

        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
}
</code>
.
<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "start of oncreate");

        setContentView(R.layout.loneworker);

        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setIcon(R.drawable.ic_launcher);
        setTitle("Lone Worker");
        nfcscannerapplication = (NfcScannerApplication) getApplication();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        tvCountDown = (TextView)findViewById(R.id.tvloneworkercountdown);
        callFinished = (Button)findViewById(R.id.buttonlwcallfinished);

        callFinished.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Log.e(TAG, "inside callFinished");
                //maybe alert carer is safe***************************************

                setCountDownFinished();

            }
        });

        startService(new Intent(this, CountDownBroadcastService.class));
        Log.i(TAG, "Started service");

    }//end of onCreate

    private BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateGUI(intent); // or whatever method used to update your GUI fields
        }
    };

    public void onResume() {
        super.onResume();
        registerReceiver(br, new IntentFilter(CountDownBroadcastService.COUNTDOWN_BR));
        Log.i(TAG, "Registered broacast receiver");
        }

    private void updateGUI(Intent intent) {
        if (intent.getExtras() != null) {
            long millisUntilFinished = intent.getLongExtra("countdown", 0);
            //Log.i(TAG, "Countdown seconds remaining: " +  millisUntilFinished / 1000);

            String status = intent.getStringExtra("timer_status");

            if(status.equalsIgnoreCase("timer_not_finished")){

                    tvCountDown.setText("Countdown seconds remaining: " +  millisUntilFinished / 1000);

            }else if(status.equalsIgnoreCase("timer_finished")){

                setCountDownFinished();
            }
        }
    }//end of updateGUI

    public void setCountDownFinished(){

        tvCountDown.setText("0");
        unregisterReceiver(br);
        Log.i(TAG, "Unregistered broacast receiver");

        stopService(new Intent(this, CountDownBroadcastService.class));
        Log.e(TAG, "Stopped CountDownBroadcastService");

    }// end of setCountDownFinished()

}
</code>
Comment: @MuchOverflow ok thanks for that. I will use open source solutions if there is no way of acheiving the desired functionality in Android. I just find it hard to believe there is nothing in Android that works for what i want to do
Comment: Kindly help me to understand, is your activity is in pause state or destroyed when you try to broadcast
Comment: @AttiqurRehman It works fine when the Activity is in the foreground. It doesn't work when i click the back button and say navigate to another Activity. i don't override any of the Activity lifecycle methods, so i presumed the Activity would still be on the stack and maybe in a paused state.
Comment: can you tell us why the broadcastreceiver must live in an Activity instead of having a stand-alone-broadcastreceiver that does the "stop the service and unregister the receiver." If the activity is not visible then it-s gui must not be updated
Comment: @k3b it is just the way i have done it. Given what i want to acheive would the receiver make more sense in its own class?
Comment: @turtleboy, lemme know my explanation and answer works. Otherwise I have a shortcut technique to do so
Comment: Are you familiar with using EventBus?
Comment: @MuchOverflow no i'm not, what is it?
Comment: @tutleboy It is used as a backbone in Pub/Sub design pattern. Have a read at this and see if it can help you http://square.github.io/otto/
Answer:
When you register a broadcast receiver programmatically in an
  activity, it will not get broadcasts when the activity is paused. The
  BroadcastReceiver docs are not as clear as they could be on this
  point. They recommend unregistering on onPause solely to reduce system
  overhead.
       If you want to receive events even when your activity is not in the foreground, register the receiver in your manifest using the
  receiver element.
Comment: You can handle this thing via Service because you just want to close the counter not to again show the activity....
If you really wanna show your activity, then you start the activity -- i will suggest you to launch activity with launchMode= "SingleInstance"
Comment: If i register a receiver using the receiver element in the manifest, how do i then update the UI if the Activity is in the foreground and how do i send the "timer_finished" String to the Activity if the Activity is not in the foreground?


Warnings during WAIC computation: how to proceed?

Question: I am computing the WAIC (widely applicable or Watanabe-Akaike information criterion) using the waic() function from the 'loo' package in R. When I do so, I see a warning message as follows:
Warning messages:
1: 118 (5.1%) p_waic estimates greater than 0.4.
We recommend trying loo() instead.
What should I do about this? I have noticed that several online examples/tutorials ignore this warning (e.g. here--this is a reproducible example). Is 5.1% (in my case) or 3.3% (in the example's case) a dangerously high number?  How is this likely to impact my inference when comparing two models? What if the WAIC values are REALLY different in my comparison (like more than 40 WAIC units different); can I trust the inference that one model is to be preferred?
Using loo() instead (for leave-one-out cross-validation), I get a different warning:
Some Pareto k diagnostic values are too high. See help('pareto-k-diagnostic') for details.
My model uses Bernoulli error, so the error term cannot be misspecified. In my particular class of model, the linear predictor is also unlikely to be badly misspecified.
WARNING, GORY DETAILS FOLLOW
My model is a latent variable model (see here) to jointly model the distributions of fifteen bird species across ~100 sites. The model includes no covariates, and so can be thought of as a model-based ordination. The occurrence probability of species i at site j is modeled on the probit scale as a species-specific intercept plus the impact of several (1-3) latent factors that behave like covariates in a GLM. Each latent factor takes a particular value (estimated from data) at each site, and each species gets a species-specific factor loading that governs its abundance across sites.  The matrix of factor loadings times its transpose is an approximation to the full (15x15) variance-covariance matrix among species. I want to fit the model with two latent factors (because this produces ordinations that are easy to visualize in two dimensions).  However, changing the number of latent factors to one or three does not improve the percentage of p_waic estimates greater than 0.4; this leads me to believe that I can't ameliorate the issue by choosing a better specification for the linear predictor.
My reason for performing model selection is not to dredge through a large number of possible covariates, but rather to perform inference on exactly two alternative models that represent meaningfully different biological hypotheses/scenarios. I want to know if the evidence strongly favors one hypothesis over the other.
For those interested, the full model specification in JAGS, including the computation of the log-likelihood, is below:
##### Model specification #####
LV_C <- function() {
  ## Data Level ##
  for(i in 1:n) { # sites
    for(j in 1:p){ # species
      eta[i,j] <- inprod(lv.coefs[j,2:(num.lv+1)],lvs[i,]) # LV part of the linear predictor
      Z[i,j] ~ dnorm(lv.coefs[j,1] + eta[i,j], 1) # This line and the next one implement a probit link
      y[i,j] ~ dbern(step(Z[i,j]))
      loglikelihood[(i-1)*(p)+j] <- y[i,j]*log(phi(lv.coefs[j,1] + eta[i,j])) + (1 - y[i,j])*log(1 - phi(lv.coefs[j,1] + eta[i,j]))
    }
  }

  ## Latent variables ##
  for(i in 1:n) { for(k in 1:num.lv) { lvs[i,k] ~ dnorm(0,1) } } # Says what Latent Variable values are

  ## Process level and priors ##
  for(j in 1:p) { lv.coefs[j,1] ~ dnorm(0,0.01) } ## Separate species intercepts

  for(i in 1:(num.lv-1)) { for(j in (i+2):(num.lv+1)) { lv.coefs[i,j] <- 0 } } ## Constraints to 0 on upper diagonal
  for(i in 1:num.lv) { lv.coefs[i,i+1] ~ dunif(0,20) } ## Sign constraints on diagonal elements
  for(i in 2:num.lv) { for(j in 2:i) { lv.coefs[i,j] ~ dunif(-20,20) } } ## Free lower diagonals
  for(i in (num.lv+1):p) { for(j in 2:(num.lv+1)) { lv.coefs[i,j] ~ dunif(-20,20) } } ## All other elements
}

#  Set up for Run

jags.data = list(y=ssm2, n=dim(ssm2)[1], p=dim(ssm2)[2],
                 num.lv=2)

params = c('lvs', 'lv.coefs', 'loglikelihood')

p <- dim(ssm2)[2]
n <- dim(ssm2)[1]
inits <- function(jjj) {
  Tau <- rWishart(1,p+1,diag(p))[,,1]
  Sigma <- solve(Tau)
  Z <- abs(t(mvtnorm::rmvnorm(n,rep(0,p),Sigma)))
  Z <- ifelse(as.matrix(ssm2), Z, -1 * Z)

  list(Z=Z)
}

Answer: I'm happy that you care about these diagnostic messages. I'm responsible for that specific warning message. WAIC doesn't have a good way to diagnose the reliability and that 0.4 threshold is empirically chosen. Pareto k diagnostic in PSIS-LOO is much better. You did not mention the specific k values, but if they are larger than 1, then theory and experiments show that the error can be arbitrary large (see Aki Vehtari, Andrew Gelman and Jonah Gabry (2017). Pareto smoothed importance sampling. https://arxiv.org/abs/1507.02646). WAIC and PSIS-LOO are connected so that if PSIS-LOO fails then WAIC fails even more (Aki Vehtari, Andrew Gelman and Jonah Gabry (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. In Statistics and Computing, 27(5):1413–1432, https://arxiv.org/abs/1507.04544). Thus, if even one p_waic can have arbitrary large error, then the total WAIC can have arbitrary large error and should not be trusted for final results.
Since you have a large difference in WAIC, it's likely that the difference is similar with more accurate/robust approach (e.g. k-fold-CV), but you cannot be sure without computing that more accurate/robust result. In your case it is likely that WAIC and PSIS-LOO fail because you have a flexible model and some of the observation are highly influential, that is, the full data posterior and leave-one-out-posterior are so different that using full posterior as the proposal distribution in importance sampling LOO fails. WAIC uses instead Taylor series approximation, which also fails in case of highly influential observations (which explains why p_waic is used as the ad-hoc diagnostic).


How to insert beacon details to database when the app is being killed from the background?

Question: I'm working with altbeacon library how can I add the beacon details to database when the app is being killed from background.
Comment: when app killed, onDestroy method called, at that time add beacon entry into the database.
Comment: Thank you for the reply Hemant N. Karmur
Comment: I am following sample in https://altbeacon.github.io/android-beacon-library/samples.html to detect beacon in background. Inside didEnterRegion method i gave inserion to database.  I called this class inside  on destroy of main activity... Is this correct? Can anyone help?
Comment: where you want to save your beacons details?
Comment: In sqlite database.
Comment: Where to add call for application  class extending region bootstrap?
Answer: On Android, there is no guaranteed callback when your app is killed.  See a discussion of this here.
You might have success getting a callback with a shutdown hook:
<code>Runtime r=Runtime.getRuntime();
r.addShutdownHook(new MyThread());
</code>
But I suspect that if and when it fires, the Android Context will be invalid making it impossible to write to your database.
Comment: Thank you davidgyoung. But i need to get the beacon details when the app is being killed from the background. Where will i make a call to application class extending BootstrapNotifier?
Comment: I don't think that is possible with Android.   Alternative: store the beacon/time every time one is detected (e.g. every second or so), and then when the app starts up again, check the last stored beacon timestamp to see if it more than a few seconds in the past.  If it is, this indicates that your app was previously stopped: mark it in the database as needed. This would meet your requirements except perhaps that the storage in the database would not happen exactly when the app is killed, but it would do this on next app launch based on the info available at the time the app was last killed.
Comment: Thank you davidgyoung. But  i can't get beacon details when app is being killed.Could you help with that? how to use RegionBootstrap to scan beacon in background?  Where to add the call to application class  extending BootstrapNotifier in the application?
Comment: There are code samples on how to do that in the "Starting an app in the background" section here: https://altbeacon.github.io/android-beacon-library/samples.html


UnicodeDecodeError: 'ascii' codec cant decode byte 0xef in position 2141: ordinal not in range(128)

Question: This is a script that sends randomly generated sentences into a discord chat. But it occasionally runs into the error:  UnicodeDecodeError: 'ascii' codec cant decode byte 0xef in position 2141: ordinal not in range(128)
How would I solve this error?
Code:
import asyncio
import random
import discord.ext.commands
import markovify
import nltk
import re

with open("/root/sample.txt") as f:
 text = f.read()

class POSifiedText(markovify.Text):
    def word_split(self, sentence):
        words = re.split(self.word_split_pattern, sentence)
        words = [w for w in words if len(w) > 0]
        words = [" :: ".join(tag) for tag in nltk.pos_tag(words)]
        return words

    def word_join(self, words):
        sentence = "".join(word.split("::")[0] for word in words)
        return sentence

text_model = POSifiedText(text, state_size=1)

client = discord.Client()
async def background_loop():
    await client.wait_until_ready()
    while not client.is_closed:
        channel = client.get_channel('286342556600762369')
        messages = [(text_model.make_sentence(tries=33, max_overlap_total=10, default_max_overlap_ratio=0.5))]
        await client.send_message(channel, random.choice(messages))
        await asyncio.sleep(15)

client.loop.create_task(background_loop())
client.run("MjY2NjkwNDY4MjI4NzU5NTU4.C5jcdw.WFfBTUmAY7UcrwKTwYFJ9_bFHjI")

The error is occurring on line 9.
Comment: Your sample contains non-ascii characters. In the `open()` call, specify the correct encoding.
Comment: Duplicate of [UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to ](http://stackoverflow.com/questions/9233027/unicodedecodeerror-charmap-codec-cant-decode-byte-x-in-position-y-character)
Comment: But your question has nothing to do with the nltk, or with the chatbot you're building. Stop tagging everything `nltk`; narrow down your problem and it will be easy to google the solution.
Answer: I had a similar problem; turns out there was an ascii code that python wasn't able to turn into a standard symbol.
To get around this you have to tell python to encode the ascii code and ignore ones that it can't encode. then decode it back to utf-8.
    def word_split(self, sentence):
        words = re.split(self.word_split_pattern, sentence)
        words = [w for w in words if len(w) > 0]
        words = [" :: ".join(tag) for tag in nltk.pos_tag(words)]
        words = words.encode('ascii', 'ignore')
        words = words.decode("utf-8"))
        return words

I added to extra steps before your return statement.
Comment: That would be a **non-ascii** code. [Learn](http://stackoverflow.com/a/4546129/699305) about encoding/decoding so you'll understand what your code does. (Also, this won't solve the OP's problem).


Add "webforms like" values to profile.module select list

Question: Is there a module that can allow me to add custom values to select list items in the Profiles module in Drupal 6, like webforms does it. For example:
my_value_1 | my_text_1
my_value_2 | my_text_2

which will create a select list
<select>
<option value="my_value_1">my_text_1</option>
<option value="my_value_2">my_text_2</option>
</select>

Answer: Try Content Profile module. Using this module you can create user profile where you can add cck fields to the user profile content type.

This module builds user profiles as content (aka nodes), which opens
  the opportunity to use all the powerful modules for content for user
  profiles too, e.g. the Content Construction Kit (CCK). It's intended
  to be simple and useful, but extensible by further modules.
Comment: I just want to add key|value pairs. Why is everything so difficult in Drupal? With Content Profile I have to add 2 modules, change all my profile settings etc etc. Isn't there any other way? Programmatically? I can see the fields in the database table.


How to check whether gitlab agent is successfully installed?

Question: I want to check whether the gitlab agent is successfully installed for kubernetes connection.
How can I check that?
Thanks in advance!
Comment: check the GitLab Agent logs with ```kubectl logs gitlab-agent``` . If you see messages about successful connections to the Kubernetes cluster, the agent is running and connecting correctly.
Answer: Depending on the way you installed it, one way to check is to see if the pod is running correctly by verifying the READY status by doing a kubectl get pods --namespace gitlab or kubectl get pods --namespace gitlab-agent
You can find more information here: Installing the agent for Kubernetes


Interaction terms of the same variable with multiple variables

Question: I have a model
lm = a  ~ b
I would like to include c, d , e that represent interactions terms with b =>
lm = a  ~ b + b:c + b:d + b:e.
Is there a rapid way to obtain this result without taping each variable? I have more than 10 variables.
Thank you !
Comment: Okay, `b:(.)` it is then.
Comment: I'm not quite sure what your question is.  The way you show it should work just fine, `a ~ b + b:c + b:d + b:e`. You can use parentheses to save a tiny bit of typing, `a ~ b + b:(c + d + e)`.  You can use `.` as a stand-in for all non-response variables in the data, `a ~ b:(.)`. Is that what you're looking for?
Comment: I have many variables to add. I am looking for a way that does not imply a 30min typing ^^
Answer: In R formulas, . is a placeholder for all non-response variables present in the data.
coef(lm(mpg ~ wt:(.), data = mtcars))
 #  (Intercept)            wt        wt:cyl       wt:disp         wt:hp       wt:drat       wt:qsec
 # 41.044844014 -16.742131313   0.028771226   0.006485611  -0.005048411   0.447194218   0.423909109
 #        wt:vs         wt:am       wt:gear       wt:carb
 # -0.087023686   0.402891966  -0.142805986   0.156345459

Comment: At some point if there are variable you want and variables you don't want, you'll have to let R know which  are which. There's probably a way to make it work using the names or even the column numbers of either set (those you want, or those you don't want). Or maybe you can specify a naming pattern (all variables starting with "year_"). If you want more help, ask another question that's more specific, perhaps giving an example of how you'd like to specify the variables you want (or don't want): name, naming pattern, column number, something else?
Comment: If I want to select specific columns and no all the responses variables ?


Setting the color of the home bar area of the mobile screen in Flutter

Question: I have tried options for setting the safearea by wrapping it in a container and several other background options but they do not extend further enough to allow the very last section of the screen to be adjusted.

How can this section of the screen be adjusted in Flutter so it blends in with the rest of the UI. Please note that the UI is a webview set to fill the safearea. My priority is for Android devices.
Comment: What is your expected result? Can you provide an image?
Answer: Wrap Scaffold with SafeArea widget. In the SafeArea widget, set bottom:false. And Wrap SafeAre widget with Container.
<code>class PostsPage extends StatelessWidget {
  const PostsPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.green,
      child: SafeArea(
        top: false,
        child: Scaffold(
          body: const Placeholder(),
        ),
      ),
    );
  }
}
</code>