text:
Q: Confusion about the generating function for a regular expression Given a regex A = (a*b)*, I want to compute the Generating Function that enumerate this regex.
The formula for the GF of that regex is 1/(1-z/(1-z)) = (1-z)/(1-2z). Then I can compute the sequence that this GF represents is a(n) = 2^n - 2^(n-1). Based on that, I can compute that the number of 3-character strings that match regex A is a(3) = 4. However, I can only list 2 of them which are aab, bbb. I tried with 4 and 5-character strings and that does not feel right as well.
So my question is, am I misunderstanding anything here? If yes, I would be happy if you point it out.
Thank you,

A: Hint:

*

*Let $A = (a^*b)^*$ and $A' = \Sigma^* \setminus A$ (i.e. the complement of $A$).

*Observe that any word $w$ that ends with the letter $b$ belongs to $A$.

*Observe that $A' = \Sigma^*a$.

I hope this helps $\ddot\smile$


text:
Q: Javascript Second for loop never executes I have a script that hides or shows an element after a number of seconds have elapsed. The elements are all give the class .show-after-x-seconds or .hide-after-x-seconds and an attribute called data_seconds with the number of seconds.
The first loop iterates through all the elements with that class but the second loop seems to be ignored. I tried switching their order and only the first loop executes.

var show_these = $('.show-after-x-seconds');
for(var show in show_these) {
    show_this(show_these[show], parseInt(show_these[show].attributes.data_seconds.value));
}
var hide_these = $('.hide-after-x-seconds');
for(var hide in hide_these) {
    hide_this(hide_these[hide], parseInt(hide_these[hide].attributes.data_seconds.value));
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
function hide_this(element_to_hide, x){
    sleep(x *1000).then(() => {
        element_to_hide.style.display = 'none';
    })
}
function show_this(element_to_show, x){
    sleep(x *1000).then(() => {
        element_to_show.style.display = 'block';
    })
}

A: This will tell you what you're doing wrong:
var hide_these = $('.hide-after-x-seconds');
for(var hide in hide_these) {
    console.log(hide_these[hide]);
}

You want to do
$('.hide-after-x-seconds').each(function() {
   hide_this(this,this.getAttribute('data-seconds'));
});

Also, change your attribute data_seconds to data-seconds. It'll still work, but data_seconds is a non-standard attribute. You'll want to use HTML5 data- attributes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to replace a line with a certain pattern in vi? I am trying to replace lines that contain the pattern "s#_decoded_block[" with "s#_decoded_block_". The command I am using to do that is
%s/s\d\+_decoded_block\[/s\d\+_decoded_block_/g

I expect to get "s#_decoded_block_" as substitutions but instead I am getting "sd+_decoded_block_". Please let me know what I am doing wrong.

A: You seem to expect a decimal number for "#" in the question.  You can do this using a backreference:
%s/s\(\d\+\)_decoded_block\[/s\1_decoded_block_/g

where \(\d\+\) matches one or more decimal digits and is replaced using the marker \1.
You could improve the backreference by moving more of the text inside it:
%s/s\(\d\+_decoded_block\)\[/s\1_/g

because \1 will be replaced by whatever was matched in the group.

A: Not sure if it perfectly fits your use case, but it looks like you may as well just use:
:g/s\d\+_decoded_block\[/ s/\[/_/

...unless there are potentially other [ characters in the matching lines preceding the one you want to change.
Simpler is better, if it fits your requirements.


text:
Q: Долго выгружаются данные в из HTML в PDF Есть необходимость реализовать конвертор из HTML в PDF продукции. Все настроено все реализовано, но есть проблема, 25 страниц конвертируется за 75 секунд, что очень долго. Начал капать и вот что накопал,
Все фотографии продукт лежат в одной папке, их 16 000 фотографий. Если я беру одну фотографии и вывожу ее в html и сразу в Pdf то режим ожидания сокращается до 20 секунд что норм. Но если я в цикле вывожу каждую фотку то опять долго ждать приходиться. Думал может проблема в размере фотки, сжал их до минимума но все также. в чем может быть причина? неужели причина в том что он долго ищет нужную фотку из 16 000 файлов?

A: Конкретно в вашем случае сложно сказать причину, но в зависимости от реализации скрипта и используемой файловой системы да, задержка из за большого количества файлов в папке возможна.
Именно чтобы избежать таких задержек и делают фрагментацию списка файлов по папкам. Как пример реализации, часто используемый, это класть файл в папку названную по первым двум буквам имени файла. В случае если имя файла представляет собой шестнадцатиричную строку и генерируется случайно, то будет создано ~256 папок, по которым файлы будут равномерно распределены. Как следствие "нагрузка" на отдельно взятую папку упадет в 256 раз. И поиск файла будет происходить быстрее.


text:
Q: How to update variables defined in controller as syntax? The following is the code I am trying:

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

var appCtrl = app.controller('AppCtrl', AppCtrl);

function AppCtrl(){
  var appCtrl = this;
  appCtrl.variable = "search";
}

     {{ctrl1.variable}}

    <input type="search" ng-model = "ctrl2.variable"/>
     {{ctrl2.variable}}

When I update ctrl2.variable, but ctrl1.variable is not updated.
How can I update that without using $scope?

A: The easiest solution that I can find without using $scope.$watch is with a shared state, like below.
Basically both controllers have the same reference to the object and any change to the value is observed.

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

app.factory('SharedState', SharedState);

function SharedState(){
  var shared = this;
  state = {variable: "search"};

  shared.getState = function() {
    return state;
  }

  return shared;
}

app.controller('AppCtrl', AppCtrl);

function AppCtrl(SharedState){
  var appCtrl = this;
  appCtrl.sharedState = SharedState.getState();

}

     {{ctrl1.sharedState.variable}}

    <input type="search" ng-model = "ctrl2.sharedState.variable"/>
     {{ctrl2.sharedState.variable}}

A: Adricadar's answer is perfectly fine.
But I just wanted to post the one that I wrote:

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

var appCtrl = app.controller('AppCtrl', AppCtrl);

appCtrl.$inject = ['ShareDataService'];

function AppCtrl(ShareDataService){
  var appCtrl = this;
  appCtrl.variable = "search";

   appCtrl.setSearchQuery = function () {
       ShareDataService.setSearchQuery(appCtrl.variable);
    }

 appCtrl.getSearchQuery = function () {
        return ShareDataService.getSearchQuery();
    }

}

var sharedDataService = app.service('ShareDataService',ShareData);

function ShareData(){
  var shareDataService = this;

  shareDataService.searchQuery = "";

  shareDataService.getSearchQuery = function(){
 return shareDataService.searchQuery;
  }

  shareDataService.setSearchQuery = function(searchQuery){
 shareDataService.searchQuery = searchQuery;
  }
}

     {{ctrl1.getSearchQuery()}}

    <input type="search" ng-model = "ctrl2.variable" ng-change="ctrl2.setSearchQuery()"/>
     {{ctrl2.variable}}

The logic is:

*

*Service is a Singleton Object. Only one instance is created.

*Added a setter and a getter method.


text:
Q: Device /dev/spidev* not found I have a Banana Pi M1 and wanted to flash libreboot on a ThinkPad T400. I followed Raspberry Pi (ThinkPad X200), as RPi's GPIO pins are almost the same as BPi's and T400's chip is the same as X200. The only problem is that when it comes to flash the device, it doesn't appear
$ flashrom -p linux_spi:dev=/dev/spidev0.0,spispeed=512 --chip MX25L6405D -r romread1.rom
flashrom v0.9.9-r1955 on Linux 4.10.9-gnu-1 (armv7l)
flashrom is free software, get the source code at https://flashrom.org

Calibrating delay loop... OK.
linux_spi_init: failed to open /dev/spidev0.0: No such file or directory
Error: Programmer initialization failed.

Of course, if the devices /dev/spidev* do not exist!!
$ ls /dev/spidev*
ls: cannot access '/dev/spidev*': No such file or directory
$ lsmod|grep spi
spidev                  7364  0
spi_sun4i               4955  0

I've tried everything: loading spidev, spi-gpio, spi_sun4i kernels modules, different pinouts, etc. Maybe I've not got the right pinout? /dev/spidev* devices show up if there's nothing connected to the GPIO pins? how can I test them with sth. easier?
In almost all of the problems, people solve it by editing /boot/config.txt but that's only for RPi afaik. Anyways, the kernel I've installed in it does not have that file.

SoC: Allwinner A20
RAM: 1GB
OS:  Parabola GNU/Linux-libre (Arch Linux and ALARM based, without proprietary software packages)
BPi's GPIO pins: https://bananapi.gitbooks.io/bpi-m1/content/en/Banana-Pi-GIPO.png
More specs: https://bananapi.gitbooks.io/bpi-m1/en/

EDIT: There are some devices in /dev which look like sth. near to /dev/spidev* devices:
/dev/gpiochip0
/dev/gpiochip1
/dev/hidraw0
/dev/hidraw1
/dev/iio:device0
/dev/iio:device1

I say "near" because flashrom says:
# flashrom -p linux_spi:dev=/dev/gpiochip0
flashrom v0.9.9-r1955 on Linux 4.13.5-gnu-1 (armv7l)
flashrom is free software, get the source code at https://flashrom.org

Calibrating delay loop... OK.
linux_spi_init: failed to set SPI mode to 0x00: Invalid argument
Error: Programmer initialization failed.

For all those devices it says Invalid argument with whatever I put in "spispeed" (better than Inappropriate ioctl for device). I suspect that /dev/gpiochip0 might be the chip? However, if it is, IDK how to solve the problem of "Invalid argument"

A: Try the following:

*

*Type vi /boot/config.txt

*Press i to enter 'insert' mode.

*Delete the # in front of dtparam=spi=on to un-comment the line

*Press Esc then :wq

*Press Enter to save.


text:
Q: To reply or not to reply I was asked by a potential employer what time I would be available for a phone interview and they gave me the times available for them. I replied with a suitable time for me.  They responded with an email that read:

Please allow this email to confirm a telephone interview with John and Jane
  at 9am the 12th of...

Are they saying I don't need to reply?  Or should I reply to confirm the time?

A: You do not need to reply. The email is just their way of saying "we will arrange this time to call you". However, it shouldn't be a problem if you replied with something like "Thanks again for arranging this". Or, "I look forward to the interview, thanks again."


text:
Q: "Alt" bindings not working in tkinter text widget When I bind my text widget to the Alt key, the function assigned to that binding does not get called.
Here's my code:
from tkinter import *

root = Tk()

def func(event):
    print("Hello world")
    return 'break'

text = Text(root , width = 65 , height = 20 , font = "consolas 14")
text.pack()

text.bind("<Control-Alt-d>" , func)

mainloop()

Here, when I use the Ctrl+Alt+d combination on my keyboard, the function "func" does not get called.
This problem does not seem to occur when I don't bind the Ctrl and Alt keys together - ie "<Alt-d>". This really confuses me.
Is there any way to fix this problem?
It would be great if anyone could help me out.

A: Although it worked for me but if its not working for you then change text.bind("<Control-Alt-d>" , func) to text.bind("<Control-Alt-KeyPress-d>" , func) or maybe you should try again in different directory


text:
Q: javascript - dynamically created textbox doesnt work as datepicker i created textbox dynamically by createElement and appendChild and i gave it a classname;
a fixed textbox in my code works as datepicker with it's classname property but the dynamically created textbox is not work as datepicker.


text:
Q: Revit: Set type parameter in linked models Our Revit Add-In lets the user browse and set type parameters, including those in linked models. It worked fine in Revit 2011 and earlier, but in Revit 2012 and 2013 we can no longer set these. When constructing the transaction on the linked document I get: "Autodesk.Revit.Exceptions.ArguementException: Document is a linked file. Transactions can only be used in primary documents (projects or families.)"
OK, so we can't use transactions on linked models. So I tried setting the parameter without a transaction, but then I got an exception saying we cannot modify the model outside of a transaction.
Can't create a transaction on linked models and can't modify a model outside of a transaction--so how does one modify a linked model in Revit 2012/2013? It worked fine in 2011 with the same code. Did a fair amount of searching online including The Building Coder blog, but found no mention of this breaking change or how to work around it.  Can anyone lend a hand?
Our code is straightforward--we get a parameter in the model, start a transaction and attempt to set a parameter value.  Again the same code works without error in Revit 2011.
// elementType is an ElementType in document doc
// for which we want to set a type parameter.
Parameter typeParameter = elementType.get_Parameter(pararmeterName);
Transaction transaction = new Transaction(doc, "Update Revit Type"); // Exception thrown here if doc is a linked model
transaction.Start();

typeParameter.Set("FooValue");

transaction.Commit();

A: Since Revit 2014, you can unload the linked files. So just unload your files before starting the transaction, then reload them after the transaction has ended.
// Unload all links
var loadedExternalFilesRef = new List<RevitLinkType>();
var collector = new FilteredElementCollector(document);
foreach (Element element in collector.OfClass(typeof(RevitLinkType)))
{
    ExternalFileReference extFileRef = element.GetExternalFileReference();
    if (null == extFileRef || extFileRef.GetLinkedFileStatus() != LinkedFileStatus.Loaded)
        continue;
    var revitLinkType = (RevitLinkType)element;
    loadedExternalFilesRef.Add(revitLinkType);
    revitLinkType.Unload(null);
}

// Do your stuff in a transaction

// Reload links
foreach (RevitLinkType revitLinkType in loadedExternalFilesRef)
    revitLinkType.Load();

A: I started work with Revit 2012 and didn't know the behavior with the transactions in linked files. But I also needed set parameter to the linked files and didn't find the way how to do it properly.
And the RevitAPI help tells Transactions can only be used in primary documents (projects or families.)
I can guess that setting parameters in the linked file in the Revit 2011 was a bug, not a feature, because it is potentially unsafe.

A: 2 years later...I think you'll have to open the document in question, make it the activedocument and then try applying the code you want in there. if you need a code example, let me know and i'll try and whip something up


text:
Q: How to get the architectural size with assembly? On 32 bit machine ,it should be 4 bytes.
On 64 bit,it should be 8 bytes.
How to get it with assembly?

A: Read data from memory. The number of bytes read is what you're looking for. Don't ask how to do it because you didn't specify any particular CPU.
Anyway, if you code for 32 bit machines it will run on 64 bit too, while the opposite isn't true.
And, since you're programming in asm, you should have different coding for 32 and 64 bit machines to take advantage of the CPU's power. Think about the strlen() function, the 64 bit version is as twice as fast as the 32 bit version; they're both based on the same algo, but are coded slightly different.


text:
Q: number of rotations for a box in the Box Stacking (DP) algorithm is 3 or 6? I understand the dynamic programming solution to the Box Stacking problem, which tries to find the maximum possible length of a stack that can be formed by a given set of boxes, that can be rotated in any direction, such that the lower box is always lesser in width and length as compared to a box that is higher in the stack.
However, I haven't been able to understand why only 3 orientations are required for every box. According to me, the number of orientations should be 6. That is, for each of the three dimensions taken as height, you should have two combinations.
An online resource shows the following as the method to create the three orientations(2 rotations) of the original box.
/* Create an array of all rotations of given boxes
      For example, for a box {1, 2, 3}, we consider three
      instances{{1, 2, 3}, {2, 1, 3}, {3, 1, 2}} */
   Box rot[3*n];
   int index = 0;
   for (int i = 0; i < n; i++)
   {
      // Copy the original box
      rot[index] = arr[i];
      index++;

      // First rotation of box
      rot[index].h = arr[i].w;
      rot[index].d = max(arr[i].h, arr[i].d);
      rot[index].w = min(arr[i].h, arr[i].d);
      index++;

      // Second rotation of box
      rot[index].h = arr[i].d;
      rot[index].d = max(arr[i].h, arr[i].w);
      rot[index].w = min(arr[i].h, arr[i].w);
      index++;
   }

So, For example, for a box {1, 2, 3}, the three orientations would be
1 2 3
2 1 3
3 1 2

But according to me, the orientations should be
1 2 3
1 3 2

2 1 3
2 3 1

3 1 2
3 2 1

I understand that my extra three combinations are due to alternating length and width between them keeping the height same. So, whereas I conside 1 2 3 and 1 3 2 to be different, the original algorithm considers them to be the sam.
However, I feel that, in this problem h,l,w and h,w,l, should be treated as two separate orientations since a box say, l=3,w=4,h=5 could be stacked above a box say, l=4,w=5,h=6, but not above a box l=5,w=4,h=6

A: What you said is absolutely right we could take 6 orientations of the box, but the thing is we can make do with just 3 orientations of the box.
This is so because we impose the rule that given the height,width and length of a box, we shall treat the smaller of the two base dimensions as the width.
In other words, given a box with dimensions x > y > z, we'll consider orientations:

h=x, l=y, w=z
  h=y, l=x, w=z
  h=z, l=x, w=y

But not orientations such as:

h=x, l=z, w=y
  h=y, l=z, w=x
  h=z, l=y, w=x

This is merely to simplify the representation of the boxes.
Even in the link you have specified they have written,
for simplicity of solution, always keep w<=d:
struct Box
{
  // h –> height, w –> width, d –> depth
  int h, w, d;  // for simplicity of solution, always keep w <= d
};

Now that we have imposed this constraint on the data we can see that your original problem has been resolved i.e.

However, I feel that, in this problem h,l,w and h,w,l, should be treated as two separate orientations since a box say, l=3,w=4,h=5 could be stacked above a box say, l=4,w=5,h=6, but not above a box l=5,w=4,h=6

For example, if there were two boxes

h1,w1,l1 (Box1)
  and
  h2,w2,l2 (Box2)

we know w1<l1(because we have imposed that restriction) so if by chance w1>w2 we know automatically l1> w2,and thus the other box configuration(where you said w and l should be swapped and considered as a separate configuration) is not required.
Just think about it, i am sure you'll understand why we use just 3 configurations.


text:
Q: Power of $ 2 $ congruent to 1 mod n Fix some odd $ n $. For which values of $ m $, $ 1\leq m \leq n $, is $ 2^m $ congruent to $ 1 $ mod $ n $?
For $ n=3 $ the solutions are $ 2^2=4 \equiv 1 $
For $ n=5 $ the solutions are $ 2^4=16 \equiv 1 $
For $ n=7 $ the solutions are $ 2^3=8 \equiv 1 $ and $ 2^6=64 \equiv 1 $
EDIT: I figured number theory part of MSE was especially brutal but even I didn't expect this many downvotes lol. Here is my motivation in an attempt to stave off the closing of this question: There is an action of the symmetric group $ S_n $ on the space $ 2^n $ of bit strings of length $ n $. For any subgroup $ G $ of $ S_n $ which contains an $ n $ cycle then the orbits of the action of $ G $ on $ 2^n $ should mostly have size a multiple of $ n $, except for the orbits of the all 0 bit string and the all 1 bit string. I am interesting in subspaces of $ \mathbb{F}_2^n $ which are invariant under the action of $ G $. I am interested in the possible dimension of such subspaces. For some reasons, I am not interested in subspaces that contain the all 1 bit string. Thus I am interested in a vector subspace of $ \mathbb{F}_2^n $ that is the union of the all 0 bit string with a bunch of orbits of the $ G $ action, all of which have size divisible by $ n $ since  I am assuming $ G $ contains an $ n $ cycle. So the dimensions for such a nontrivial invariant subspace are the $ k $ such that $ 1 \leq k \leq n $ and $ 2^k $ is congruent to $ 1 $ mod $ n $.

A: Ok so just summarizing what everyone else said, the solutions are exactly the multiples of $ o_n(2) $. So the number of solutions less than $ n $ is the floor function of $ n /o_2(n) $. When 2 is primitive mod $ n $ then this value is 1 and there is a unique solution. A list of primes for which $ 2 $ is primitive is linked above
https://oeis.org/A001122
Another link
2 is a primitive root mod $3^h$ for any positive integer $h$
shows that $ 2 $
is primitive for $ n $
any power of 3
so for $ n= 3, 9, \dots $
there is also a unique solution. For general small $ n $
the problem is not hard and, again, just boils to down to knowing the order of 2 mod $ n $. One thing to keep in mind is that $ \phi(n) $ is the order of the group of units of $ \mathbb{Z}/n\mathbb{Z} $ so $ o_2(n) $ must divide $ \phi(n) $ and $ o_2(n)=\phi(n) $ exactly when $ 2 $ is primitive mod $ n $.


text:
Q: How do I backup all Gnome Tweaks configuration? I am about to upgrate from 17.10 to 18.04 but I'm afraid to lose all my Gnome desktop preferences in the process (always been using Unity until 17.10).
I made many changes through "Gnome Tweak tool" and I would like to backup all the current config so I can restore it in my new installation (the same question applies for a fresh
At the same time, I'd like to know if there's a similar way to backup all other configuration for Gnome in general (Nautilus, etc.)
Any info would really help, thank you in advance...

A: *

*From the terminal, execute the following to save your gnome settings:
cd ~
dconf dump / > saved_settings.dconf

Keep the saved_settings.dconf file in a safe place so you can use it after you upgrade.

*From the terminal, execute the following to restore your gnome settings:
cd ~
dconf load / < saved_settings.dconf

(I suggest doing a test to make sure this works for you:
Save the settings as shown above in step 1. Then make a few test changes using Gnome Tweaks. Finally restore the settings, as shown above in step 2. If everything restores to the way you had it before, you can use the saved file to restore settings after you upgrade.)
Note: There may be some settings that have changed between Ubuntu versions, and you will need to fix those manually. However, per vanadium's comment below, most settings will transfer over just fine.


text:
Q: Including Puppetlabs repo when provisioning Ubuntu client with Foreman Due to my manifests requiring the latest version of factor, all provisioned machines has to undergo a manual in-between step after OS installation of adding the puppetlabs repo and upgrading facter.
Even specifying that all subclasses require the installation, it aborts the entire manifest. All 100% after installing latest facter though.
Any way to have the puppetlabs repo being part of the provisioning process?
I though uncommenting this line:
<% if puppet_enabled && @host.params['enable-puppetlabs-repo'] &&     @host.params['enable-puppetlabs-repo'] == 'true' -%>
would do the trick, but no.
Also, the variables in the provisioning template (like hte enable-puppetlabs-repo above), where are they set?

A: This gets applied in foreman's host groups.  add it as a parameter to your hostgroup config in the UI and should work.


text:
Q: Is it possible to track all outgoing WCF call? Our application calls external services like
//in client factory
FooServiceClient client = new FooServiceClient(binding, endpointAddress);

//in application code
client.BarMethod(); //or other methods

Is it possible to track all of these calls (e.g by events or something like that) so that the application can collect the statistics like number of call, response time, etc? Note that my application itself needs to access the values, not only to write to a log file.
What I can think is to create a subclass of VisualStudio-generated FooServiceClient and then add codes like this
override void BarMethod()
{
    RaiseStart("BarMethod");
    base.BarMethod();
    RaiseEnd("BarMethod);
}

and the RaiseStart and RaiseEnd method will raise events that will be listened by my code.
But this seems tedious (because there are a lot of methods to override) and there is a lot of repeated codes, my code needs to change everytime the service contract changes, etc. Is there a simpler way to achieve this, for example by using reflection to create the subclass or by tapping into a built-in method in WCF, if any?

A: The first thing I would look at is to see if the counters available in your server's Performance Monitor can provide you with the kind of feedback you need. There's built in counters for a variety of metrics for ServiceModel Endpoints, Operations and Services. Here is some more info http://msdn.microsoft.com/en-us/library/ms735098.aspx

A: You could try building an implementation of IClientMessageInspector, which has a method to be called before the request is sent and when the reply is received. You can inspect the message, make logs etc in these methods.
You provide an implementation of IEndpointBehavior which applies your message inspector, and then add the endpoint behavior to your proxy client instance.
client.Endpoint.Behaviors.Add(new MyEndpointBehavior())

Check out the docs for MessageInspectors and EndpointBehaviors, there are many different ways of applying them (attributes, code, endpoint xml config), I can't remember of the top of my head which apply to which, as there also IServiceBehavior and IContractBehavior. I do know for sure that the endpoint behaviors can be added to the client proxy collection though.

A: I found a simple way to do it by using dynamic proxy, for example Castle's Dynamic Proxy.
Firstly, use a factory method to generate your client object
IFooClient GetClient()
{
    FooClient client = new FooClient(); //or new FooClient(binding, endpointAddress); if you want
    ProxyGenerator pg = new ProxyGenerator();
    return pg.CreateInterfaceProxyWithTarget<IFoo>(client, new WcfCallInterceptor());
}

And define the interceptor
internal class WcfCallInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        try
        {
            RaiseStart(invocation.Method.Name);
            invocation.Proceed();
        }
        finally
        {
            RaiseEnd(invocation.Method.Name);
        }
    }

    //you can define your implementation for RaiseStart and RaiseEnd

 }

I can also change the intercept method as I wish, for example I can add a catch block to call a different handler in case the method throw exception, etc.


text:
Q: stix2, overline and superscripts Consider the following MWE without stix2 loaded (looks nice with and without overline):

And with stix2 loaded (looks nice without but horrible with overline):

The overline is placed a bit high, but my main issue is that the superscript is placed far too high for some reason. A very similar problem was reported and fixed in this question, but it uses XeLaTeX (I'm using pdflatex) and the proposed solution using \wideoverbar does not appear to be available for use with pdflatex?
Is this a bug? Can I fix it somehow?
MWE code:
\documentclass{article}

%\usepackage{stix2}
\usepackage{amsmath}

\newcommand*{\tran}{^{\mkern-1.5mu\mathsf{T}}}

\begin{document}

\begin{equation*}
    h \tran s \qquad h^2 s
\end{equation*}

\begin{equation*}
    \overline{h}\tran \overline{s} \qquad \overline{h}^2 \overline{s}
\end{equation*}

\end{document}


text:
Q: Removing Duplicates from a query So I have the following query
SELECT r.userId, r.programmeId, u.email, u.firstName, u.lastName, u.profileId, tblProgrammes.name, u.storeId, r.dateEnded AS lastPass, r.dateExpired
FROM tblUserRepeatHistory AS r INNER JOIN
tblUsers AS u ON r.userId = u.id INNER JOIN
tblProgrammes ON r.programmeId = tblProgrammes.id
WHERE (r.dateExpired IS NOT NULL) AND (u.storeId = @storeId)
GROUP BY r.userId, r.programmeId, u.email, u.firstName, u.lastName, u.profileId, tblProgrammes.name, u.storeId, r.dateEnded, r.dateExpired, r.id
HAVING (DATEDIFF(D, MAX(r.dateExpired), GETDATE() + 31) >= 0)

Which returns the following data
11 22 asdf@asdf.com store-mgr jamie2 1 Deli Food Service 1 5 04/02/2011 09:36:11 10/05/2011 09:36:11

11 22 asdf@asdf.com store-mgr jamie2 1 Deli Food Service 1 5 04/02/2011 09:36:11 10/05/2011 09:36:11

11 22 asdf@asdf.com store-mgr jamie2 1 Deli Food Service 1 5 11/05/2011 09:44:36 10/07/2011 09:44:36

11 23 asdf@asdf.com store-mgr jamie2 1 Deli Food Service 2 5 11/05/2011 10:12:50 16/06/2011 10:12:50

I basically only 1 record returned for each user and programme, where the most recently added one should be returned so i guess by MAX(dateExpired). So i.e this query should only return two records
11 22 asdf@asdf.com store-mgr jamie2 1 Deli Food Service 1 5 11/05/2011 09:44:36 10/07/2011 09:44:36
11 23 asdf@asdf.com store-mgr jamie2 1 Deli Food Service 2 5 11/05/2011 10:12:50 16/06/2011 10:12:50

A: SELECT DISTINCT are the SQL keywords you'll need. DISTINCT causes the query to only return the columns that are different

A: Remove r.dateExpired from GROUP BY clause and replace it with "MAX(r.dateExpired) as dateExpired" in select list.

A: you can use cross apply
SELECT * FROM tblUsers as u CROSS JOIN tblProgrammes p
CROSS APPLY
(SELECT TOP 1 dateExpired FROM tblUserRepeatHistory
WHERE userId = u.id and programmeId = p.id
ORDER BY dateExpired desc
) as rr

in the co-related sub query you get the maximum dateExpired in tblUserRepeatHistory where meet the programme and the user,
cross apply is something like inner join, for nested queries and table-valued functions


text:
Q: Buttons in Container Repeats itself - ExtJS I'm using two buttons inside an container in ExtJS and container I'm showing on radio buttons checked. But on pressing Cancel button again when I open the form, buttons get repeats itself. Here is the xds:
{
    "id": "MyContainer39",
    "cid": "container",
    "jsClass": "MyContainer39",
    "snapToGrid": 10,
    "userConfig": {
        "flex": "-ext-undefined-",
        "autoRef": "SelectContainer",
        "id": "SelectContainer"
    },
    "cn": [{
        "id": "MyButton20",
        "cid": "button",
        "jsClass": "MyButton20",
        "snapToGrid": 10,
        "userConfig": {
            "text": "MCW.lr.s_btn_selectAll",
            "style": "float:left; display:inline-block; margin-left:10px;",
            "flex": "-ext-undefined-",
            "autoRef": "SelectAll"
        }
    }, {
        "id": "MyButton21",
        "cid": "button",
        "jsClass": "MyButton21",
        "snapToGrid": 10,
        "userConfig": {
            "text": "MCW.lr.s_btn_deselectAll",
            "iconAlign": "right",
            "style": "float:left; display:inline-block; margin-left:15px;",
            "flex": "-ext-undefined-",
            "autoRef": "DeSelectAll"
        }
    }]
}

Radio Button checked condition:
if (card.internalServerDowloadLocation.checked == true) {
    Ext.getCmp('SelectContainer').show();
} else {
    Ext.getCmp('SelectContainer').hide();
}

Is there any way, so on cancel I can remove buttons from container and on load again add it to containers.

A: I resolved it myself. Main issue was that in container both autoref and id's were same:
"userConfig": {
        "flex": "-ext-undefined-",
        "autoRef": "SelectContainer",
        "id": "SelectContainer"
    }

So I removed the autoref and its' working fine now.


text:
Q: Insert into from select query error in SQL Server I am using the below query to insert data from one table to another:
DECLARE @MATNO NVARCHAR(10), @GLOBALREV INT, @LOCALREP INT

SET @MATNO = '7AGME'
SET @GLOBALREV = 11
SET @LOCALREP = 1

INSERT INTO CIGARETTE_HEADER
VALUES
    (SELECT *
     FROM CIGARETTE_HEADER_BK1
     WHERE MATERIAL_NUMBER = @MATNO
       AND GLOBAL_REVISION = @GLOBALREV
       AND LOCAL_REVISION = @LOCALREP)

The column in both the tables are same, but I am getting the following error:

Msg 156, Level 15, State 1, Line 7
  Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 7
  Incorrect syntax near ')'.

Can you please let me know the mistake here?

A: You don't need VALUES keyword:
INSERT INTO CIGARETTE_HEADER
SELECT * FROM CIGARETTE_HEADER_BK1
WHERE MATERIAL_NUMBER = @MATNO AND
      GLOBAL_REVISION = @GLOBALREV AND
      LOCAL_REVISION = @LOCALREP

It is also preferable to explicitly cite every field name of both tables participating in the INSERT statement.

A: You don't need to use the VALUES () notation. You only use this when you want to insert static values, and only one register.
Example:
INSERT INTO Table
VALUES('value1',12, newid());
Also i recommend writing the name of the columns you plan to insert into, like this:
INSERT INTO Table
(String1, Number1, id)
VALUES('value1',12, newid());

In your case, do the same but only with the select:
DECLARE @MATNO NVARCHAR(10), @GLOBALREV INT, @LOCALREP INT;

SET @MATNO = '7AGME';
SET @GLOBALREV = 11;
SET @LOCALREP = 1;

INSERT INTO CIGARETTE_HEADER
(ColumnName1, ColumnName2)
SELECT ColumnNameInTable1, ColumnNameInTable2
FROM CIGARETTE_HEADER_BK1
WHERE MATERIAL_NUMBER = @MATNO
AND GLOBAL_REVISION = @GLOBALREV
AND LOCAL_REVISION = @LOCALREP);

A: To expand a bit on the issue.
VALUES() is actually a table constructor.
When inserting rows into a table you can either use SELECT to fetch rows or VALUE constructor.
Even though INSERT INTO... VALUES is often used in examples to insert a row, you can use it to insert multiple rows, separating them with commas.
Eg.
INSERT INTO table(col1, col2)
VALUES (1, 2)
    ,  (3, 4)
    ,  (5, 6)
Would insert a set of 3 rows into your table.
VALUES can also be used to make derived tables, allowing some advanced data manipulation.
https://msdn.microsoft.com/en-us/library/dd776382.aspx


text:
Q: Vertex Array for Star OpenGL I want to draw a star using Open GL on iPhone. Can anyone share me the Vertex Array and Indices Array

A: You can determine the x,y locations of the five points by taking the sin and cos of the five angles. The five angles are 360 degrees divided by the five points.
If you provide your code attempt I suspect there will be helpful answers.


text:
Q: Does supporting Diana Allers mean that you can no longer kick her off the Normandy? The first few times I've visited Diana Allers in her cabin, I've had the option to kick her off the Normandy:

Recently, she argued with a crew member about whether or not to run a story and I took her side.  Afterwards, I found that the dialogue option to kick her off the ship was no longer available.
Does supporting Diana mean that she becomes a permanent part of the crew?

A: You will eventually reach a point where, upon talking to Diana, she will simply say, "Shepard." As soon as that happens, choose to talk to her again.
You'll be met with two options upon doing so:
That will be all. or Get off my ship.
Simply choose the latter and Allers will leave. And take her horrible voice acting with her!


text:
Q: How to set the Toolbar collapseIcon color programmatically I want to change the color of the back button in the toolbar when a search is displayed (the circled white arrow).

I managed to change the color of all other elements and I am stuck with the back arrow color.
I can set the collapseIcon (back arrow drawable) from xml:
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:layout_scrollFlags="enterAlways"
    app:popupTheme="@style/AppTheme.PopupOverlay"
    app:collapseIcon=I_WANT_TO_SET_THIS_PROGRAMMATICALLY>

I set app:collapseIcon to whatever drawable I want and that works, however, I need to set it dynamically.
None of the suggestions I found here work for me.
not this:
final Drawable upArrow = ContextCompat.getDrawable(this, R.drawable. abc_ic_ab_back_material);
upArrow.setColorFilter(myColor, PorterDuff.Mode.SRC_ATOP);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(upArrow);

or this:
appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        Drawable d = ContextCompat.getDrawable(MyActivity.this, R.drawable.ic_back_white);
        d.setColorFilter(myColor, PorterDuff.Mode.SRC_ATOP);
        toolbar.setNavigationIcon(d);

//        Drawable d = ContextCompat.getDrawable(MyActivity.this, R.drawable.ic_back_white);
//        d.setColorFilter(myColor, PorterDuff.Mode.SRC_ATOP);
//        getSupportActionBar().setHomeAsUpIndicator(d);
            }
        });

Neither anything else I found.
Can anyone please help?
Thank you

A: Finally got it...
This is what worked for me:
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
AppBarLayout appBar = (AppBarLayout) findViewById(R.id.appbar);
appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        for (int i = 0; i < toolbar.getChildCount(); i++) {
            View view = toolbar.getChildAt(i);
            if (view instanceof ImageButton) {
                ImageButton btn = (ImageButton) view;
                Drawable drawable = btn.getDrawable();
                drawable.setColorFilter(new_button_color, PorterDuff.Mode.SRC_ATOP);
                btn.setImageDrawable(drawable);
            }
        }
    }
});


text:
Q: Cert expired on InfoPath form and yields an error in MOSS I have a very particular case in SharePoint 2007 and InfoPath 2007. I am using InfoPath 2010 as the designer, deploying the InfoPath form to SharePoint 2007 with a signed certificate and some code behind. The certificate was signed for one year and has now expired. Re-signing the form with a new certificate and publishing does not fix the issue. I still get the same generic error message:

The form cannot be opened becuase either the signature is corrupt, or
  the certificate used to sign the form has expired or has been revoked.
  To fix this problem, contact the form designer.

pressing CTRL+SHIFT+I yields the following error number: 1202431. Here is what I have found:
Here is what I have tried:

*

*I found this article, that this is a bug in InfoPath form, but the workaround isn't very helpful; which I have tried many times with different certificates.

*Deleted the InfoPath form from the list by using SharePoint Designer and publishing again with a new signed cert

*Same as Step 2 above, except this time calling the template something different and updating the list with the new template name.

The only thing to PARTIALLY work was Step 2, which allowed me to create a new Infopath form without error, but existing InfoPath forms wouldn't open and would yield the same error.
Any ideas on how I can sign new and exiting InfoPath forms int he Document Library and have them open using a new certificate?

A:
but existing InfoPath forms wouldn't open and would yield the same
  error

because they are linked to a (bad) template with bad (expired) certificate
So, essentially your question is how to relink old documents to a new template


text:
Q: Unix time command implementation I want to know about the time command flow of execution.
I have a doubt in the time calculation for the command execution.

*

*Whether the real time is sum of (time taken to open the unix window + execute the command given infront of the "time" command + close the unix window)

*or Just the time taken for executing the same command in the same window.

If u have time command source code, mail me.
Please help Me in this regard.

A: GNU implementation of time, with source, is available Free Software Directory.


text:
Q: Как сделать чтобы через apscheduler выполнялось действие через 3 сек, единожды? Как сделать чтобы через apscheduler выполнялось действие через 3 сек, единожды?
Нужно чтобы таймер запускался, через 3 сек срабатывала определенная функция, и после этого срабатывания не шел отсчет опять с выполнением функции.
Если использовать триггер 'interval', то функция будет исполняться каждые 3 сек(а мне этого не надо).

A: Никак!
Нужно воспользоваться встроенным модулем asyncio, и использовать в коде следующую конструкцию:
#...код...
asyncio.sleep(3)
#...код который выполнится через 3 секунды


text:
Q: How to redirect Magento after some operation to an url passed in query string? Possible? This Wiki article: Adding a Product to the Cart via Querystring describes how one can put product with specific id to the cart directly from querystring. So for simple product it would be something like this:
/path/to/app/checkout/cart/add?product=[id]&qty=[qty]

But after it adds a product, Magento redirects browser to the home page and shows nice message that product has been added successfully. But we need to show a Shopping Cart directly, not a home page. So maybe it is possible to add another param to the querystring to achieve this?
I know I could write a module, but I just stumbled upon this possibility, so might be there is a way to easily redirect as well?

A: There a few things you could try before going the custom code route.
In the Admin UI you could make sure the redirect flag is correct.
URL: /admin/system_config/edit/section/checkout
Fieldset: Shopping Cart
Field: After Adding a Product Redirect to Shopping Cart

If that doesn't solve the problem, try this one.
/checkout/cart/add?product=[id]&qty=[qty]&in_cart=true


text:
Q: vis timeline - items.add breaks loop when called from async function I am adding multiple items to a vis timeline:
The first adding is called inside a callback and works fine.
The second time I am adding data which comes from an async ajax request and returns a promise.
getRocketChat().then(print);
The problem is now, that the loop is only executed once when I do the item adding. When I uncomment the item adding it works fine.
I also tried around with timeline.redraw(), items.update() etc, but with no success. I absolutely have no idea why this does not work.
function print(channelAndMessages) {

    for (let i = 0; i < channelAndMessages.length; i++) {
        console.log(channelAndMessages[i]);

        for (let j = 0; j < channelAndMessages[i].messages.length; j++) {
            console.log("ChannelName " + getChannelName(channelAndMessages[i].messages[j].rid));

            let singleMsg = channelAndMessages[i].messages[j];

            items.add({
                id: "Chat" + singleMsg.id,
                group: 'einsatzltr',
                content: singleMsg.msg,
                start: moment(singleMsg.ts)

            });
            console.log(singleMsg.msg); //excecuted only once
        }
    }
}

A: I found the problem. It has nothing to do with the loop, but just with the id.
I changed the item id to another function and now it works:
 id: "Chat" + i +" " + j,


text:
Q: AchartEngine annotations everywhere i look, the only information I can find says to add them via the following code
series.addAnnotation("Hello!!", 1, 1);

However, When I try it in my code (with the proper series name) I get an error message that says addAnnotation is not supported. Can someone please clear this up for me? thanks!

A: You must download a recent version of the library. For example, get the night build from here.
In your code, replace the last line (the one where you return the chart view) with:
XYMultipleSeriesDataset dataset = buildBarDataset(titles, values);
XYSeries series = dataset.getSeriesAt(0);
series.addAnnotation("Vacation", 6, 30);
return ChartFactory.getBarChartView(context, dataset, renderer, Type.STACKED);

A: Here's the code...
public View getView(Context context) {

    String[] titles = new String[] { "2008", "2007" };
    List<double[]> values = new ArrayList<double[]>();
    values.add(new double[] { 240, 210, 60, 40 });
    values.add(new double[] { htmlHelper.grec, htmlHelper.gwhite, htmlHelper.gim, htmlHelper.gfit });
    int[] colors = new int[] { Color.rgb(255, 255, 255),
            Color.rgb(25, 25, 112) };
    XYMultipleSeriesRenderer renderer = buildBarRenderer(colors);

    switch (context.getResources().getDisplayMetrics().densityDpi) {

    /* Done*/
    case DisplayMetrics.DENSITY_XHIGH:
        renderer.setAxisTitleTextSize(29);
        renderer.setChartTitleTextSize(60);
        renderer.setLabelsTextSize(29);
        renderer.setLegendTextSize(50);
        renderer.setChartValuesTextSize(40);
        break;

    /*done*/
    case DisplayMetrics.DENSITY_HIGH:
        renderer.setAxisTitleTextSize(15);
        renderer.setChartTitleTextSize(47);
        renderer.setLabelsTextSize(19);
        renderer.setLegendTextSize(1);
        renderer.setChartValuesTextSize(40);
        break;

    case DisplayMetrics.DENSITY_LOW:
        renderer.setAxisTitleTextSize(24);
        renderer.setChartTitleTextSize(25);
        renderer.setLabelsTextSize(9);
        renderer.setLegendTextSize(10);
        renderer.setChartValuesTextSize(20);
        break;

    default:
        renderer.setAxisTitleTextSize(39);
        renderer.setChartTitleTextSize(35);
        renderer.setLabelsTextSize(20);
        renderer.setLegendTextSize(2);
        renderer.setChartValuesTextSize(40);
        break;
    }

    setChartSettings(renderer, "Gym Attendance", "", "", 0.5, 12.5, 0,
            24000, Color.BLACK, Color.BLACK);
    renderer.getSeriesRendererAt(0).setDisplayChartValues(false);
    renderer.getSeriesRendererAt(1).setDisplayChartValues(true);
    renderer.setShowLegend(false);
    renderer.setMargins(new int[] { 80, 10, 60, 10 });
    renderer.addXTextLabel(1, "Rec. Hall" + "\n" + ce);
    renderer.addXTextLabel(2, "White" + "\n" + "Building" + "\n"
            + wh);
    renderer.addXTextLabel(3, "IM" + "\n" + "Building" + "\n" + imm);
    renderer.addXTextLabel(4, "Fitness Loft" + "\n" + fi);
    renderer.setXLabelsColor(Color.rgb(0, 0, 0));
    renderer.setYLabelsColor(0, Color.BLACK);
    renderer.setYLabels(10);
    renderer.setXLabels(0);
    renderer.setXAxisMin(0);
    renderer.setXAxisMax(5);
    renderer.setYAxisMin(0);
    renderer.setYAxisMax(250);
    renderer.setAxesColor(Color.BLACK);
    renderer.setXLabelsAlign(Align.CENTER);
    renderer.setYLabelsAlign(Align.LEFT);
    renderer.setPanEnabled(false, false);
    // renderer.setZoomEnabled(false);
    renderer.setZoomRate(1.1f);
    renderer.setBarSpacing(0.5f);
    renderer.setApplyBackgroundColor(true);
    renderer.getSeriesRendererAt(1).setGradientEnabled(true);
    renderer.getSeriesRendererAt(1).setGradientStart(0,
            Color.rgb(192, 192, 192));
    renderer.getSeriesRendererAt(1).setGradientStop(45,
            Color.rgb(25, 25, 112));
    renderer.setBackgroundColor(Color.rgb(220, 220, 220));
    renderer.setMarginsColor(Color.rgb(248, 248, 255));
    renderer.setOrientation(Orientation.HORIZONTAL);
    renderer.setZoomEnabled(false, false);

    return ChartFactory.getBarChartView(context,
            buildBarDataset(titles, values), renderer, Type.STACKED);

}

Thanks so much for taking a look! At first I had the graph in frame layout with textviews but that doesn't work once I started testing on different screen sizes and pixel densities.


text:
Q: How to determine states for Hidden Markov Model I am trying to learn about machine learning using Accord.Net.
I created a project that has a number of labeled states that represent screens a user visited in a sequence. I created some unit tests to submit a series of historical sequences and a new observed sequence and calculate the probability that new sequence fits.
My basic case unit tests work fine, but once I expand it to my test data it throws errors. Each historical sequence contains 50-60 items and the observations is a sequence of 26 items. My method calculates 30 distinct symbols (screens) included in the dataset.
However, my final assertion calculated with "actual = _engine.CheckConfidence(history, observed)" throws the error "Index out of Bounds" at the Learn() method and appears to be related to the symbols provided. I must be misunderstanding the usage here, but if there are 30 screens then I should have 30 symbols and 30 potential states correct?
My implementation...
    public int CheckConfidence(int[][] historical, int[] observations)
    {
        IEnumerable<int> symbols = observations.Distinct();
        foreach (int[] array in historical)
        {
            symbols = symbols.Union(array.Distinct()).Distinct();
        }

        double probabality = getLikelihood(historical, observations, symbols.Count(), symbols.Count());

        //caclulate confidence on percent scale
        return (int)(Math.Round(probabality, precision) * 100);
    }

    private double getLikelihood(int[][] historical, int[] observations, int states, int symbols)
    {
        HiddenMarkovModel hmm = new HiddenMarkovModel(states, symbols);
        BaumWelchLearning teacher = new BaumWelchLearning(hmm) { Tolerance = 0.001, };
        teacher.Learn(historical);
        return Math.Exp(hmm.LogLikelihood(observations));
    }

...and my unit tests.
 public void GetProbabilityTest()
    {
        try
        {
            //test perfect case
            int[][] history = new int[][]
            {
                new int[] { 0, 1, 0, 1 },
                new int[] { 0, 1, 0, 1 },
                new int[] { 0, 1, 0, 1 },
                new int[] { 0, 1, 0, 1 },
            };

            int[] observed = new int[] { 0, 1, 0, 1 };
            double actual = _engine.CheckConfidence(history, observed);
            Assert.AreEqual(100, actual); //100%

            //test prefectly WRONG case
            history = new int[][]
            {
                new int[] { 0, 1, 0, 1 },
                new int[] { 0, 1, 0, 1 },
                new int[] { 0, 1, 0, 1 },
                new int[] { 0, 1, 0, 1 },
            };

            observed = new int[] { 2, 2, 2, 2 };
            actual = _engine.CheckConfidence(history, observed);
            Assert.AreEqual(0, actual); //0%

            //do again with real numbers
            history = _engine.GetHistoricalData(_historicalData.ToList());
            observed = _engine.GetNewObservations(_newObservations.ToList());

            IEnumerable<int> symbols = observed.Distinct();
            foreach (int[] array in history)
            {
                symbols = symbols.Union(array.Distinct()).Distinct();
            }
            actual = _engine.CheckConfidence(history, observed);
            Assert.AreEqual(0, actual); //0%
        }
        catch (Exception ex)
        {
            Assert.Fail("Exception caught: " + ex.Message);
        }
    }

StackTrace...
   at Accord.Statistics.Distributions.Univariate.GeneralDiscreteDistribution.Fit(Int32[] observations, Double[] weights, GeneralDiscreteOptions options)
   at Accord.Statistics.Distributions.Univariate.GeneralDiscreteDistribution.Fit(Int32[] observations, Double[] weights)
   at Accord.Statistics.Models.Markov.Learning.BaseBaumWelchLearning`4.Fit(Int32 index, TObservation[] values, Double[] weights)
   at Accord.Statistics.Models.Markov.Learning.BaseBaumWelchLearning`4.UpdateEmissions()
   at Accord.Statistics.Models.Markov.Learning.BaseBaumWelchLearning`4.Learn(TObservation[][] x, Double[] weights)
   at AnomalyDetector.Engines.BehaviorEngine.getLikelihood(Int32[][] historical, Int32[] observations, Int32 states, Int32 symbols) in C:\Git\anomalydetector\AnomolyDetector.Core\Engines\BehaviorEngine.cs:line 134

EDIT: So I have figured out through unit testing that it begins to error out at 20 symbols. I haven't been able to get Accord.Net to build locally yet, but looking at the code I don't see why this would be constrained at 20.
EDIT: Still struggling to figure out if I'm providing the right input or this is an Accord bug.
for (int i = 0; i < observations.Length; i++)
    p[observations[i] - start] += weights[i] * observations.Length;

I got it building locally and the error is in Accord.Statistics\Distributions\Univariate\Discrete\GeneralDiscreteDistribution.Fit(int[] observations, double[] weights, GeneralDiscreteOptions options) observations is length 150 while p is length 29 so when the loop reaches index = 29 it blows up. I was under the impression symbols should be the unique (distinct) symbols in the set e.g. the alphabet. Setting the symbols to 150 actually avoids this error, but then my results are useless as I never seem to get a likelihood result that is positive even when passing in one of the historical arrays as the new observations.


text:
Q: Why SettingWithCopyWarning is raised using .loc? I have checked similar questions on SO with the SettingWithCopyWarning error raised using .loc but I still don't understand why I have the error in the following example.
It appears line 3, I succeed to make it disappear with .copy() but I would like to understand why .loc didn't work specifically here.
Does making a conditional slice creates a view even if it's .loc ?
df = pd.DataFrame( data=[0,1,2,3,4,5], columns=['A'])
df.loc[:,'B'] = df.loc[:,'A'].values
dfa = df.loc[df.loc[:,'A'] < 4,:] # here .copy() removes the error
dfa.loc[:,'C'] = [3,2,1,0]

Edit : pandas version is 1.2.4

A: dfa = df.loc[df.loc[:,'A'] < 4,:]<br>

dfa is a slice of the df dataframe, still referencing the dataframe, a view..copy creates a separate copy, not just a view of the first dataframe.
dfa.loc[:,'C'] = [3,2,1,0]

When it's a view not a copy, you are getting the warning : A value is trying to be set on a copy of a slice from a DataFrame.
.loc is locating the conditions you give it, but it's still a view that you're setting values to if you don't make it a copy of the dataframe.


text:
Q: meteor: facebook signin status How do I check and get the username from the facebook login?? I successful get the account-facebook to work but I don't know how to access to the username?
Meteor is cool but not much documentation. Or I am to new for must of the server side javascript. Thanks!

A: There is an object (services) where facebook info is stored on  Meteor users. You can get accessToken, id, username, etc.
You can use onCreateUser to modify the user document and add the username on creation.
# on server
# coffeescript
Accounts.onCreateUser (options, user) ->
  if user.services.facebook
    data = user.services.facebook
    user.username = data.username or "generateOne"
    return user

You can use user.profile to add other fields.


text:
Q: Linux Pthread argument This is my code. It's very simple.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *func(void *arg)
{
    printf("ID=%d\n", *(int*)arg);
    pthread_exit(NULL);
}

int main()
{
    pthread_t pt[4];
    int i;

    for (i = 0; i < 4; i++)
    {
        int temp = i;
        pthread_create(&pt[i], NULL, func, (void*)&temp);
    }
    sleep(1);
    return 0;
}

I compiled it:
gcc p_test.c -lpthread
I ran it. It printed 2 2 3 3. I ran it again. It printed 2 3 3 2.
My problem is:
Why was 2 or 3 printed twice?
Why didn't it print 1 3 2 0 or any other results?

A: The major problem here is that you're taking the address of the local variable temp, and then using that pointer outside the scope of the variable - as soon as you exit one iteration of the loop, your pointer to temp becomes invalid and you must not dereference it.

A: You're passing a pointer to a temporary variable into the thread creation function and this temporary goes out of scope at the end of the loop block.  It would seem to me that the temporary address is being reused by the compiler and so that when the threads are executing, they see the same address location.
If you do:
int *temp = malloc(sizeof(int));
*temp = i;
pthread_create(&pt[i], NULL, func, (void*)temp);

instead, you should see the results you expect.
In this case, the thread function needs to free the int after it is printed it to avoid a memory leak.
Also, it's better practice to pthread_join() the threads that you're waiting for rather than just sleep()ing.

A: because it prints temp, all threads shares the memory(why temp  is "shared" is explained by TheJuice), so all threads "share"  temp . Use a mutex or make temp a private variable.
Private Variables in Threads
Or you can use phtread_join like this:
int main()
{
    pthread_t pt[4];
    int i;

    for (i =0 ; i < 4; i++)
    {

      pthread_create(&pt[i], NULL, func, (void*)&i);
      pthread_join(pt[i],NULL);

    }

    //sleep(1);
    return 0;
}

A: #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *func(void* arg)
{
printf("ID=%d\n", (int)arg);
pthread_exit(NULL);
return 0;
}

int main()
{
pthread_t pt[4];
int i;

for (i =0 ; i < 4; i++)
{

    pthread_create(&pt[i], NULL, func, (void*)i);
    pthread_join(pt[i],NULL);
}

return 0;

}


text:
Q: How does a convolutional kernel transform images with 3 channels into multiple channels? What does the last argument mean? I trained the ResNet50V2 model and I was wondering how the tensors transform from 3 channels to n channels.
I have the model as:
model.summary()

Model: "model_9"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_9 (InputLayer)            (None, 164, 164, 3)  0
__________________________________________________________________________________________________
conv1_pad (ZeroPadding2D)       (None, 170, 170, 3)  0           input_9[0][0]
__________________________________________________________________________________________________
conv1_conv (Conv2D)             (None, 82, 82, 64)   9472        conv1_pad[0][0]
__________________________________________________________________________________________________
pool1_pad (ZeroPadding2D)       (None, 84, 84, 64)   0           conv1_conv[0][0]
__________________________________________________________________________________________________
...
...
...
...
...
...
post_relu (Activation)          (None, 6, 6, 2048)   0           post_bn[0][0]
__________________________________________________________________________________________________
flatten_9 (Flatten)             (None, 73728)        0           post_relu[0][0]
__________________________________________________________________________________________________
dense_9 (Dense)                 (None, 37)           2727973     flatten_9[0][0]
==================================================================================================
Total params: 26,292,773
Trainable params: 26,247,333
Non-trainable params: 45,440

The first convolution layer "conv1_conv" has a filter:
filters= layer.get_weights()[2]  #conv1_conv layer
print(layer.name, filters.shape)

Output:
conv1_conv (7, 7, 3, 64)

What I don't understand is the convolution operation that makes the (170,170,3) tensor convert to (82,82,64) tensor.
What does the 64 in the conv1_conv indicate?

A: You can imagine the convolution as a sliding window of size 7 × 7 sliding over the image. Each filter takes a window of the image, here 7 × 7 × 3 numbers a makes a linear projection into a single number. You need 7*7*3 parameters for linear projection for each filter and you have 64 of them, therefore the shape of the convolution 7 × 7 × 3 × 64.
The other important property of the convolution is stride: this is a step by which the window moves. You have window size 7 and the image has width and height 170, i.e., the sliding window needs to pass 170-7=163 pixels. If you do it with stride 2, it means 163/2=81.5 windows, rounded to 82. Each of the windows gets projected with 64 filters, therefore the shape 82 × 82 × 64.


text:
Q: jQuery append Not Working in Double HTML I have a code with a two steps. The following statement:
Step 1: If the  no text, then id='parent' will be removed with this code $("#parent").Remove();
Step 2: If the id="container" no text, then id="container" will automatically generate text NO DATA with this code $("#container").append("NO DATA");
At Atep 1 work well. But at this Step 2 not working.
I also had to replace of append() into html() and has not been able to work.
What's the solution?
My Codes:

Age:

A: There's whitespaces left in your container so html() is not empty you need to use $.trim() to remove left whitespaces. Here's jsFIddle for you.

if($("#test").html()==""){
$("#parent").remove();
}
if($.trim($("#container").html())==""){
$("#container").append("NO DATA");
}

Age:


text:
Q: Protocol 'Numeric' can only be used as a generic constraint because it has Self or associated type requirements I have the following swift code that was written by a colleague.
I don't know swift.
I've been running 'Product' -> 'Archive' in xcode so that I can release to the App Store.
The following code has been in place for a long time and I haven't changed it, but I'm now getting the error "Protocol 'Numeric' can only be used as a generic constraint because it has Self or associated type requirements".
Does anyone know what the issue is? ...and could you explain it?
Any help is greatly appreciated.
import Foundation

func MyCallback(_ id: String, _ with: Any?) -> String{
    return "My.callback('\(id)', \(with != nil ? with is Numeric ? with! : "'\(with!)'" : "void 0"));"
}

A: IMO at a glance this code looks really bad. This is not how you unwrap optionals in Swift. Anyway if with is a Numeric type or a String you can simply try to cast it as a String instead of checking if it is Numeric.
func MyCallback(_ id: String, _ with: Any?) -> String {
    if let string = with as? String {
        return "My.callback('\(id)', '\(string)');"
    } else if let with = with {
        return "My.callback('\(id)', \(with));"
    }
    return "My.callback('\(id)', void 0);"
}

Note that it is Swift naming convention to name your methods starting with a lowercase letter func myCallback.


text:
Q: How do I store the OAuth v1 consumer key and secret for an open source desktop Twitter client without revealing it to the user? I want to make a thick-client, desktop, open source twitter client. I happen to be using .NET as my language and Twitterizer as my OAuth/Twitter wrapper, and my app will likely be released as open source.
To get an OAuth token, four pieces of information are required:

*

*Access Token (twitter user name)

*Access Secret (twitter password)

*Consumer Key

*Consumer Secret

The second two pieces of information are not to be shared, like a PGP private key. However, due to the way the OAuth authorization flow is designed, these need to be on the native app. Even if the application was not open source, and the consumer key/secret were encrypted, a reasonably skilled user could gain access to the consumer key/secret pair.
So my question is, how do I get around this problem? What is the proper strategy for a desktop Twitter client to protect its consumer key and secret?

A: I found an answer that mirrors the path I was considering going down on hueniverse. The article, Beyond the OAuth Web Redirection Flow, offers some suggestsions, one of them being a web url that proxies the token exchange process. I have to work out a way to properly authenticate that my app is what is requesting the authentication to this proxy page. However, that is possible.

A: Section 4.6 of RFC 5849, which defines OAuth 1, states that the consumer secret was never intended for use by desktop consumers, despite Twitter's use thereof in practice. As Nelson Elhage pointed out in "Dear Twitter", Twitter can and does terminate consumer keys of desktop clients, provided that the client isn't too big to fail. But there are two workarounds to allow use of OAuth 1 in a desktop or mobile application.
One way is to proxy the entire Twitter protocol through a server that you operate. This way, the consumer secret stays on your server. This is the workaround recommended by Dick Hardt, editor of the OAuth 1 spec. This workaround does not address the cost of operating this server.
The other way, as suggested in a post by Raffi Krikorian to the Twitter development talk Google group and a post by Chris Steipp to a Wikipedia mailing list, is to "have each user register their copy of your desktop application as its own consumer." Then the user would copy and paste the newly registered consumer key and consumer secret into your application. The manual for your application would then need to include detailed instructions on how to register a new application on Twitter's developer site. This official limitation has a few practical problems:

*

*Your client will face a usability disadvantage compared to well-known proprietary clients.

*The form to create a new app doesn't appear to offer a way to pre-populate the required fields. This means you will have to update the registration walkthrough in your manual whenever Twitter changes the procedure for registering an app.

*The developer agreement requires users to be of legal age to enter a binding contract. This means a user of your application aged 13 to 17 must have a parent accept the agreement on the user's behalf.

*Twitter's Developer Policy prohibits mass-registering applications and "name squatting", which it defines as "submitting multiple applications with the same function under different names." I am unaware of any precedent as to whether Twitter has treated unrelated users who have registered separate copies of one application as "name squatters".

A: I may be wrong, but if you bundle keys with the desktop or mobile app, open source or not, it is possible to access them. If services like Twitter and Tumblr force us into using OAuth-only API, we have two options:

*

*setup an auth proxy service for every app

*bundle keys with the app

The former is more difficult and costly, not necessarily maintainable for small and open source apps. The latter means that the app may and will be blocked, once the spammers steal the keys. As Twitter and Tumblr don't give a better option yet, and screw all desktop clients, Open Source clients inclusive, there is a proposal to distribute "Big Fish" keys, and use them as a fallback.
Finally, there is an option to force every user into obtaining API keys.

A: The consumer key and secret are application bound and not user bound. With this in formation the OAuth provider knows with what application it is dealing. The rest, Access token and secret will be obtained after the first steps are done.
See this blog post for more information as it shows how the protocol works.

A: I'm going to answer but be warned I have not dealt with this myself, I am going off of best practices and existing relevant experience;
I wouldn't worry about it too much. If your client is open source then they are going to have access to the source anyway, and  trying to control what they do with your program goes against the nature of open source anyway (though importantly, what you are trying to do does not).
If someone has enough knowledge to debug your program and extract your key, they likely know how to do more than that and you could very well be wasting your time trying to lockdown further.
As a precaution I would change keys every so often (if possible), but if all they can do is pretend to be your program than that doesn't sound too serious to me.
Full disclosure, I am not familiar with Twitters API, twitterizer's API, oauth requirements, or anything else I said that sounds questionable ;)


text:
Q: What is the difference between Java and C# when it comes to connect to Sql Server Database? I am writing an application requires to connect to sql server. I prefer to write the App in Java. but When I try to connect to the server I got the connection refused error. I am using JTDS JDBC driver. I think it is due to the port 1433 or 1434 are not open. The server is in my work place and I can not change the ports. But funny enough, I use c# writing the same thing, it connects successfully. is it because SqlConnection class in C# library works better with ms sql server? or am I doing something wrong here? FYI, the server we are using in work is MS SERVER 2003.
Sorry I did not provide any code earlier. One tricky part is that the server we have is called "SERVER" on the local network.
C#:
SqlConnection objConnection = new SqlConnection("Data Source= SERVER\\SQLEXPRESS;Initial Catalog=SSS;Persist Security Info=True;User ID=user;Password=pass");
SqlCommand objcommand = new SqlCommand();
string strSQL;
objcommand.Connection = objConnection;
strSQL = "select * from company where companyid = @companyID ";
try
{
 objConnection.Open();
 SqlDataReader Query = objcommand.ExecuteReader();
            while (Query.Read())
            {
                MessageBox.Show(Convert.ToString(Query["clientRef"]));

            }
            objConnection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error Retreiving info: " + ex.ToString(), "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            objConnection.Close();
        }

As I am not really familiar with C#. I have got the code above from one of the colleges. and it returns the info correctly.
Java:
try{
Connection connection;
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:jtds:sqlserver://network.local/SERVER\\SQLEXPRESS:1433/SSS","user","pass");
System.out.println("Connection succeed!");
}
catch (Exception e) {
e.printStackTrace();
}

The java code above got Network error IOException: Connection refused error.
FYI: I can ping server.network.local successfully. But when I telnet server.network.local 1433/1434, I got  telnet: Unable to connect to remote host: Connection refused.

A: Check how your .NET app is connecting. It may be as simple as it using named pipes, which JTDS supports as well.

A: It might be that the defaults are different, are you setting the port when you initialise your driver
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]

Something like this jdbc:jtds:sqlserver://nameofyourdatabaseserver.or.ipaddress:port/yourdatabasename
Try using the full dns name for your server or the IP address

A: At the following link you will find a useful tutorial which describes in detail how to connect to MS SQLServer database, both from Java and C#. It also describes how to query the database, pass and retrieve data and much more. Hope you find it useful: http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html


text:
Q: Web Scraping Using Multiple Variables in Link I am trying to efficiently scrape weekly tournament data from pgatour.com, and place the results in one encompassing table. Below, is an example link that I will use:
https://www.pgatour.com/stats/stat.02568.y2019.eon.t041.html
In the example link - 02568 is one of many stat_id's and t041 is one of many tournament_id's. I want the scrape to get every combo of stat_id and tournament_id in the following manner:

Currently, my lapply is cycling through both id's at the same time and I am only getting 3 of the possible 9 combinations. Is there a way to change my lapply call to cycle through both id's in the desired manner?
library(rvest)
library(dplyr)
library(stringr)

tournament_id <- c("t041", "t054", "t464")
stat_id <- c("02568", "02567", "02564")
url_g <- c(paste('https://www.pgatour.com/stats/stat.', stat_id, '.y2019.eon.', tournament_id,'.html', sep =""))

test_table_pga4 <- lapply(url_g, function(i){
  page2 <- read_html(i)
  test_table_pga5 <- page2 %>% html_nodes("#statsTable") %>% html_table() %>% .[[1]] %>%
    mutate(tournament = i)
})

test_golf7 <- as_tibble(rbind.fill(test_table_pga4))

A: Use expand.grid() to create unique combinations of stat_id and tournament_id and then mutate a new column with those links.
library(tidyverse)
library(janitor)
library(rvest)

df <- expand.grid(
  tournament_id = c("t041", "t054", "t464"),
  stat_id = c("02568", "02567", "02564")
) %>%
  mutate(
    links = paste0(
      'https://www.pgatour.com/stats/stat.',
      stat_id,
      '.y2019.eon.',
      tournament_id,
      '.html'
    )
  ) %>%
  as_tibble()

# Function to get the table
get_info <- function(link, tournament) {
  link %>%
    read_html() %>%
    html_table() %>%
    .[[2]] %>%
    clean_names() %>%
    select(-rank_last_week ) %>%
    mutate(rank_this_week = rank_this_week %>%
             as.character,
           tournament = tournament) %>%
    relocate(tournament)
}

# Retrieve the tables and bind them
df %$%
  map2_dfr(links, tournament_id, get_info)

# A tibble: 648 × 9
   tournament rank_this_week player_name       rounds average total_sg_app
   <fct>      <chr>          <chr>              <int>   <dbl>        <dbl>
 1 t041       1              Corey Conners          4    2.89        11.6
 2 t041       2              Matt Kuchar            4    2.16         8.62
 3 t041       3              Byeong Hun An          4    1.90         7.60
 4 t041       4              Charley Hoffman        4    1.72         6.88
 5 t041       5              Ryan Moore             4    1.43         5.73
 6 t041       6              Brian Stuard           4    1.42         5.69
 7 t041       7              Danny Lee              4    1.30         5.18
 8 t041       8              Cameron Tringale       4    1.22         4.88
 9 t041       9              Si Woo Kim             4    1.22         4.87
10 t041       10             Scottie Scheffler      4    1.16         4.62
# … with 638 more rows, and 3 more variables: measured_rounds <int>,
#   total_sg_ott <dbl>, total_sg_putting <dbl>


text:
Q: Why would I extend java.lang.RuntimeException I was recently asked a question, apparently in an Interview, about extending the java.lang.RuntimeException.
I was asked to cite an example where there would be a need to extend the java.lang.RuntimeException.
I always thought that we would not need to extend the RuntimeException, can anybody enlighten me?
Thanks,
SB

A: One layer's runtime exception is another layer's checked (and acted upon) exception.
I can see containers e.g. servlet container; REPLs and/or anything top-level interpreter loop; etc. legitimately selecting and catching RuntimeExceptions as they are not supposed to crash simply because something goes boom deeper in the stack.
Similar to the container case, crossing adjacency boundaries e.g. crossing layers or tiers typically calls for a more articulated exception semantics.
If the 'cause' and/or message properties prove semantically insufficient to express anything beyond "hey, it broke", and the client/higher layer can act selectively, then it is arguably legitimate to sub-class RuntimeException.

A: You want to extend RuntimeException when you create an Exception that doesn't have to be explicitly caught (unchecked exception). This is the case of exceptions that signal a problem that normally can not be recovered (eg. a dead database).
You should take a look at the difference between checked and unchecked exceptions in Java.

A:
RuntimeException is the superclass of
  those exceptions that can be thrown
  during the normal operation of the
  Java Virtual Machine.
A method is not required to declare in
  its throws clause any subclasses of
  RuntimeException that might be thrown
  during the execution of the method but
  not caught.

See RuntimeException

A: RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.
If you add new feature to the jdk or if you modify the jvm implementation you should extend the RuntimeException in order to add new RuntimeException.

A: You should stay with the these that this exception should not be extended, because it should be used usually in places where no more action can be executed and operation should be interrupt.
But if You rally need to find out a application for that case, you can say that by creating different type of RuntimeException we can have more control in out exception handler to display the messages of exception etc. but IMHO this is only a play talk.

A: when the client cannot reasonably recover from program,i would throw Runtime Exceptions,
these are typically Unchecked Exceptions, mostly bugs in code, where the client is not expect to recover at runtime
examples: dead link to data source, JNDI binding failure, pre condition failed for certain operations(division where the denominator is zero) are scenarios for this RuntimeException subclassing


text:
Q: Finding first non-zero value in an image I'm pretty new to Python and I would like to locate the extremes of a binary image. There's a white shape in the middle of a black background and I would like to locate the top, bottom, left and right enclosing rectangle.
My way of doing this is by finding the first non-zero pixels in all directions.
My function is goes as this, but it only works on the Y axis. How can I manage to pass through the X axis?
def first_non_zero(img):
    width = img.shape[1]
    height = img.shape[0]

    idx = 0
    result = 0

    for j in range(0, height):
        idx = np.argmax(img[j])

        if idx > 0:
            result = j
            break

    return result

A: I'd simply use numpy.nonzero and then find minimum and maximum for each axis.
Script:
import cv2
import numpy as np

img = cv2.imread('blob_in_the_middle.png', cv2.IMREAD_GRAYSCALE)
positions = np.nonzero(img)

top = positions[0].min()
bottom = positions[0].max()
left = positions[1].min()
right = positions[1].max()

output = cv2.rectangle(cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    , (left, top), (right, bottom), (0,255,0), 1)

cv2.imwrite('blob_with_bounds.png', output)

Sample input:

Sample output:


text:
Q: Let $g \in N_G(H)$ an element of order $5$. Compute the order of $H \langle g \rangle$. Let $G = A_5$ and $H=\langle(1,2,3,4,5)\rangle$.
Let $g \in N_G(H)$ an element of order $5$. Compute the order of $H \langle g \rangle$.
I think I can use the second isomorphism theorem to solve this problem. I find that $|HK| = \frac {|H||\langle g \rangle|}{|H \cap \langle g \rangle|}$, but I don't know how to find $H \cap \langle g \rangle$.
Is anyone is able to give me a hint?

A: Both of the subgroups $H$ and $<g>$ are of order 5 which is prime, so either they are equal, or their intersection is trivial.
EDIT: full solution
Since $g$ has order 5 and it is in $A_n$ it must be a 5-cycle. If $g\notin H$, then $H\cap <g>=\{e\}$ since they are both subgroups of prime order, and then you get that $<H,g>$ is a group of order 25 (because $<H,g>\cong H\rtimes <g>$ using the normality of $H$ in $<H,g>$). This is not possible, since $|A_5|=5!/2=60$ is not divisible by 25. It therefore follows that $g$ must be in $H$.


text:
Q: Customize the PrettyPrint options in Jackson? I'm aware of the writerWithDefaultPrettyPrinter option in Jackson, but is there any way to customize it?  See examples below.
If this isn't possible in Jackson, if you can't change pretty print options, then is there another popular JSON library that would do it?
Summary of options to change:

*

*Don't open multiple containers on the same line

*Don't close and open containers on the same line

*Use 4 spaces as indents instead of 2

*(another option, though I wouldn't use it) Open containers on a new line so that they line up vertically with their closing marker

Example of what it outputs now:
[ {
  "id" : "12",
  "payload" : [ {
    "name" : "url",
    "value" : [ {
      "name" : "url",
      "value" : "http://foobar.com"
    } ]
  }, {
    "name" : "tags",
    "value" : [ {
      "name" : "tags",
      "value" : "red"
    }, {
      "name" : "tags",
      "value" : "green"
    }, {
      "name" : "tags",
      "value" : "blue"
    }, {
      ...

Example of what I'd like to get:
[
    {
        "id" : "12",
        "payload" : [
            {
                "name" : "url",
                "value" : [
                    {
                        "name" : "url",
                        "value" : "http://foobar.com"
                    }
                ]
            },
            {
                "name" : "tags",
                "value" : [
                    {
                        "name" : "tags",
                        "value" : "red"
                    },
                    {
                        "name" : "tags",
                        "value" : "green"
                    },
                    {
                        "name" : "tags",
                        "value" : "blue"
                    },
                    {
                        ...


text:
Q: JWT Authentication, Encoding a LocationToken I'm working an external API in which there is a locationToken.
With this, I use it to create encoded data which I will use within my Bearer.
I am creating the data as such:
var data = {
  "locationToken": postman.getEnvironmentVariable("LocationToken"),
  "timestamp": Math.floor(new Date().getTime() / 1000)
};

data = addIAT(data);

With this data, i'm then encoding it using stringify then Cyrpto:
var stringifiedData = CryptoJS.enc.Utf8.parse(JSON.stringify(data));
var encodedData = base64url(stringifiedData);

postman.setEnvironmentVariable("locationTokenData", encodedData);

Strangely, within this it will always come out as, please note the NhdGlvblRva
eyJsb2NhdGlvblRva2VuIjoiZXlKMGVYQWlPaUpLV ----- etc

However, if I run it through their automatic documentation sample it comes with:
eyJpYXQiOjE2NjE2OTQyNzksInRpbWVzdGFtcCI ------ etc

I can confirm it is linked to the same account, same area, same details etc, however there appears to be an issue with how i'm passing this data. Can anyone let me know what's incorrect? Why is this string always occuring: NhdGlvblRva


text:
Q: Charts in django Web Applications I want to Embed a chart in a Web Application developed using django.
I have come across Google charts API, ReportLab, PyChart, MatPlotLib and ChartDirector
I want to do it in the server side rather than send the AJAX request to Google chart APIs, as I also want to embed the chart into the PDF.
Which is the best option to use, and what are the relative merits and demerits of one over the other.

A: Another choice is CairoPlot.
We picked matplotlib over the others for some serious graphing inside one of our django apps, primarily because it was the only one that gave us exactly the kind of control we needed.
Performance generating PNG's was fine for us but... it was a highly specialized app with less than 10 logins a day.

A: Well, I'm involved in an open source project, Djime, that uses OpenFlashChart 2.
As you can see from our code, generating the JSON-data that OFC uses is a bit complex, but the output is very nice and user friendly, since you can add tooltips, etc. to the different elements.

A: Open Flash Chart 2
http://teethgrinder.co.uk/open-flash-chart-2/
python library http://btbytes.github.com/pyofc2/
kybi

A: One package I've wanted to try is graphite. It's a graphing server / platform built with Django. It's specialized for "numeric time-series data" though, like stock prices or bandwidth utilization. If that fits your need I would check it out. Here are some screenshots:
http://graphite.wikidot.com/screen-shots

A: I like client side charts because you can get full page plotting.
A good options seems to be Jquery Flot : http://code.google.com/p/flot/ which can load JSON data.
However, you won't get pdf support.

A: Perhaps you might want to have a look here: Django Plotting app.
The HowTo describes how to embed matplotlib plots into the admin interface and create a PDF view.

A: I have used FusionCharts Free  with Django.
Its flash based, open source, multi-licensed and it's well documented. It's ActionScript 1, but AS version wasn't really a criteria for me, though it could be for others.


text:
Q: Change color of data series in excel xyscatter chart I'm trying to change the color of the data points in an excel chart but everything im trying unsuccessful.
This is one method I tried, yet the points still appear blue:
With Chrt
.ChartType = xlXYScatter
Do Until .SeriesCollection.Count = 0
.SeriesCollection(1).Delete
Loop
    .SeriesCollection.NewSeries

                .SeriesCollection(1).Name = "=""Top Platen"""
                .SeriesCollection(1).Values = yaxis
                .SeriesCollection(1).XValues = xaxis

                ActiveChart.SeriesCollection(1).Select
                 With Selection.Format.Fill
                    .Visible = msoTrue
                    .ForeColor.RGB = RGB(255, 0, 0)
                    .Transparency = 0
                    .Solid
                End With

Here's another method I tried and still the data points appear blue:
With Chrt
.ChartType = xlXYScatter
Do Until .SeriesCollection.Count = 0
.SeriesCollection(1).Delete
Loop
    .SeriesCollection.NewSeries

                .SeriesCollection(1).Name = "=""Top Platen"""
                .SeriesCollection(1).Values = yaxis
                .SeriesCollection(1).XValues = xaxis
                .SeriesCollection(1).Interior.Color = RGB(255,0,0)

This is only one segment of my code, I can supply additional areas if necessary. Any help would be greatly appreciated.

A: I believe the problem is with the nested With blocks getting confused.  Here is one way to solve it and still use nested With block:
With Chrt
    .ChartType = xlXYScatter

    Do Until .SeriesCollection.Count = 0
        .SeriesCollection(1).Delete
    Loop

    .SeriesCollection.NewSeries

    With .SeriesCollection(1)
        .Name = "=""Top Platen"""
        .Values = yaxis
        .XValues = xaxis
        .Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
    End With
End With

Here is Microsoft's documentation link that talks about fully qualified nested With blocks.


text:
Q: Como executar o loop for de 2 em 2? Minha solução:
function passandoPelosPares() {
for (var i=0; i <=6; i++)
  console.log ('aqui eu tenho o valor de' + i)
}

Resposta 'insuficiente':

Imprimir passandoPelosPares() deve imprimir:
aqui eu tenho o valor de 0
aqui eu tenho o valor de 2
aqui eu tenho o valor de 4
aqui eu tenho o valor de 6

O que eu tô fazendo de errado?

A: Provavelmente faltava um espaço na impressão, o corretor automático do site quer algo exato, não pode errar nem o espaço. Mas eu aproveitei e simplifiquei e dei mais performance para o código tirando o if, não faz sentido ter esse código se pode fazer sem ele.

function passandoPelosPares() {
    for (var i = 0; i <= 6; i += 2) console.log('aqui eu tenho o valor de ' + i);
}
passandoPelosPares();

Coloquei no GitHub para referência futura.
Coloquei a chamada da função só para executar aqui, lá nesse site ele deve chamar por conta própria e não precisa desta linha.

A: No seu código no loop for você está adicionando sempre mais 1 na variável i a cada iteração do loop for o que não vai te dar o resultado em 2 e 2 e sim em 1 em 1, então altere de i ++ para i += 2, adicione um espaço no final da String para não ficar junto o texto e o número e é só chamar a função passandoPelosPares();.
Exemplo 1

function passandoPelosPares() {
for (var i = 0; i <= 6; i += 2)
  console.log ('aqui eu tenho o valor de ' + i)
}

passandoPelosPares();

Caso você queira que uma sequência em 2, 4, 6 e não 0, 2, 4, 6 é só iniciar a variável i com 2 e não com 0.
Exemplo 2

function passandoPelosPares() {
for (var i = 2; i <= 6; i += 2)
  console.log ('aqui eu tenho o valor de ' + i)
}

passandoPelosPares();

A: Executei o seu código e o resultado obtido foi:
aqui eu tenho o valor de0
aqui eu tenho o valor de2
aqui eu tenho o valor de4
aqui eu tenho o valor de6

O que me leva a crer que o problema é o espaço entre o "de" e o "par".
Neste caso, simplesmente substitua o "+" por "," no seu console.log.
Você também não precisa do if se o passo do seu for for de 2 em 2, trocando i++ por i+=2.
Além disso, pode ser que falte executar a função, e você pode fazer isso envolvendo a função com () e colocando os parêntesis no final, desta maneira:

(function passandoPelosPares() {
    for (var i=0; i <=6; i+=2)
        console.log ('aqui eu tenho o valor de', i)
})()


text:
Q: How to compute $P(Z_2 \le Z_3 \le Z_4| Z_2=Z_1 )$? where we have an i.i.d. sequence of standard normal $Z_1,Z_2,Z_3,Z_4$. Suppose that we have an i.i.d. sequence of standard normal $Z_1,Z_2,Z_3,Z_4$. How to compute
\begin{align}
P(Z_2 \le Z_3 \le Z_4| Z_2=Z_1 )
\end{align}
My idea
\begin{align}
P(Z_2 \le Z_3 \le Z_4| Z_2=Z_1 ) =P( Z_1 \le Z_3 \le Z_4 ) =\frac{1}{3!}
\end{align}
The last step follow because there are $3!$ ways that arrange $Z_1,Z_3,Z_4$ and normal is symmetric.
However, I am not sure if the second step is fine and we can drop the conditioning?

A: Partial answer that is too long for a comment:

Consider the joint distribution of $(Z_1-Z_2, Z_2)$. This is a bivariate normal distribution with means $0$ and $0$, variances $2$ and $1$, and correlation $-\frac{1}{\sqrt{2}}$. Thus it has the same distribution as $(2U, -\frac{1}{\sqrt{2}} U +\frac{1}{\sqrt{2}} V)$ where $U$ and $V$ are i.i.d. standard normal. (You can verify this by checking that the means, variances, and correlation are the same.)
So, the conditional distribution of $Z_2$ given $Z_1=Z_2$ is the same as the conditional distribution of $-\frac{1}{\sqrt{2}} U + \frac{1}{\sqrt{2}} V$ given $2U=0$. By plugging in $U=0$, we immediately see that the conditional distribution is $N(0, 1/2)$, as Brian Tung mentioned in the comments.

Thus you can rewrite your original probability as
$$P(\frac{1}{\sqrt{2}}V \le Z_3 \le Z_4)$$
where $V, Z_3, Z_4$ are i.i.d. standard normal. Some sort of volume/symmetry argument might allow you to compute this, but I'm not sure.

A: Here's a more direct approach. Let $E=\{Z_1=Z_2\}$ and $h(x)=\frac{1}{\sqrt{2\pi}}e^{-x^2/2}$. Notice $(Z_1,Z_2,Z_3,Z_4)\sim f$ where $$f(x,y,z,w)=h(x)h(y)h(z)h(w)$$ The conditional distribution of $(Z_1,Z_2,Z_3,Z_4)$ given $E$, denoted by $f_{E}$, equals $$f_{E}(z_2,z_3,z_4)=\frac{f(z_2,z_2,z_3,z_4)\sqrt{2}}{\iiint_{\mathbb{R}^3}f(z_2,z_2,z_3,z_4)\sqrt{2}dz_4dz_3dz_2}$$ The probability you're trying to compute is $$P(Z_2 \leq Z_3 \leq Z_4|Z_1=Z_2)=\int_{-\infty}^{\infty} \int_{z_2}^{\infty} \int_{z_3}^{\infty} f_{E}(z_2,z_3,z_4)dz_4dz_3dz_2$$ This is approximately 15.2%
Remark: The $\sqrt{2}$ represents the "surface area component" for the parametric surface $\vec{r}(u,v,w)=(u,u,v,w)$ whose trace is $$\Big\{(z_1,z_2,z_3,z_4)\in \mathbb{R}^4\Big|z_1=z_2\Big\}$$


text:
Q: Transfer function : Determination I have the below circuit, here, I have Is and Va are measurable quantities. Rc1..Rc4 and Rbd are unknown variables for which I intend to derive transfer function. I have flexibility of adding additional resistances or switches in the circuit to get the equations. I am not sure how to go about it.

I am thinking of adding the switches S1,S2 and Sx, and resistance R1 to generate 5 equations for switch combinations S1,S2,Sx[000,100,010,101,011]

A: Your effort to compensate the skin contact resistances is useless. The current source pushes the certain AC current through the tissue, no matter is the contact resistance =0 or more. The resistance between the driver probes must only be smaller than some specified maximum. The current spreads like tissues allow and you get some current density vector field and scalar potential field. Your BIP-BIN probes sample that potential field at two points. What they get doesn't at all depend on contact resistances of BIP-BIN probes as long as those resistances are below megaohms. That's because the BIP-BIN inputs have Zin=gigaohms.
The system uses the typical four wire measurement principle. Normally it's used to prevent the measuring wire resistance to affect the result, but contact resistance is taken into the account as well. Using AC doesn't change the idea. Read this: https://www.allaboutcircuits.com/textbook/experiments/chpt-3/4-wire-resistance-measurement/
Your system should use 4 different contact probes (needles?) on the skin to be sure the voltage is measured from tissue, not from the current feeding probe. The probe placement geometry must be always the same for consistent results (=same geometric formation, same distances).
I guess that the interface IC can tell that there's overload i.e. too high resistance connected to the drive outputs. Too low contact resistance-that's non-existent. Zero ohms is optimal.
If it happens that you are trying to find the contact resistance to extract some extra information - like is the test object nervous - is a different thing. For example lie detection uses that idea.


text:
Q: Does it harm if I use TensorFlow without an isolated python environment? I have installed TensorFlow using Anaconda Installation.
During the installation, after sourcing into the 'tensorflow' environment (create by conda), I used pip in my anaconda(i.e. $HOME/anaconda/bin/pip3) instead of pip or pip3 in the tensorflow environment(i.e. $HOME/anaconda/envs/tensorflow/bin/pip) to install TensorFlow.
When I test my installation, I find that I can still import tensorflow even if I am not in the 'tensorflow' environment(after source deactivate). So I think I am actually using tensorflow without an isolated python environment. Does it harm?

A: If it works well for you, that's good, but in general this isn't an approach we test extensively or support, so your mileage may vary!


text:
Q: Всплывающие окна поисковика на Node JS Сделал всплывающие окна поисковика, но работает с проблемами. А именно: по какой-то причине при отжатии клавиши код срабатывает дважды (возможно баг JQuery), и в целом он может бесконечно добавлять строки, а должен высвечивать только нужные результаты.
HTML+JS:

$(document).ready(function() {
  $("#search").keyup(function() {
    var name = $('#search').val();
    if (name === "") {
      $("#display").html("");
    } else {
      $.ajax({
        type: "POST",
        url: "/handler",
        data: {
          search: name
        },
        success: function(response) {
          for (i = 0; i < response.length; i++) {
            $("#display").append(`<li onclick="fill('${response[i].name}')"><a>${response[i].name}</a></li>`);
          }
        }
      });
    }
  });
});

function fill(Value) {
  $('#search').val(Value);
  $('#display').hide();
}

  <form class="example" method="POST">
    <input type="text" autocomplete="off" name="search" id="search" placeholder="Search..">
    <button type="submit"></button>
  </form>

Код серверной части Node JS:
app.post("/handler", (req, res) => {
  item.find({
    name: {
      $regex: req.body.search,
      $options: 'i'
    }
  }).limit(5).then((name) => {
    res.send(name);
  });
});


text:
Q: completion of functions annoted with @Async I am calling an async function from a spring-mvc controller.
@Async
public void doSomething()
{
    ....
}

I am simply calling this function from a controller method
@RequestMapping(/person)
@ResponseBody Person returnPerson()
{
    service.doSomething();
}

The function returnPerson returns as expected. However I would like to return  DeferredResult to denote the completion of returnPerson.
@RequestMapping(/person)
@ResponseBody DeferredResult<Person> returnPerson()
{
    service.doSomething();
}

I think for that to happen I should know when deSomething has finished its execution so that I can return the response to the caller. I am not getting how do I know when doSomething has finished its execution and then how do I return DeferredResult based in that?

A: The @Async annotation method can return a Future object. When you call get on the Future it will block until the @Async method it was returned from finishes.