text:
Q: mayavi: two surfaces obstruct each other, even though they are non-intersecting I am trying to plot two surfaces which touch at exactly two points but are otherwise well separated. Depending on the viewing angle, this renders either just fine (figure 1) or it makes some mess with the top surface s2 (plasma, red) obstructing the lower one s1 (figure 2). I suppose that is due to the order in which the surfaces are plotted, so mayavi just puts one in front even though mathematically it should be in the back. How can I solve this issue? Note that I would like to have different colormaps for both surfaces, as they represent different things. Thanks a lot!

figure 1, correct plot

figure 2, wrong plot
Here the code to produce the plot. Viewing angles were chosen in the interactive window, not sure how to get the numerical values.
import numpy as np
import mayavi.mlab

x,y = np.mgrid[-np.pi:np.pi:0.01, -np.pi:np.pi:0.01]

def surface1(x,y):
    return -np.sqrt((np.cos(x) + np.cos(y) - 1)**2 + np.sin(x)**2)

def surface2(x,y):
    return np.sqrt((np.cos(x) + np.cos(y) - 1)**2 + np.sin(x)**2)

s1 = mayavi.mlab.surf(x,y,surface1, colormap='viridis')
s2 = mayavi.mlab.surf(x,y,surface2, colormap='plasma')

mayavi.mlab.show()

EDIT:
Finally found the issue: Need to specify the correct backend for rendering. Using ipython3 --gui=qt solves the issue. Thus the issue only appears when using the default backend (whichever that is). I wish this would be documented more clearly somewhere, would have saved me a lot of work.


text:
Q: Laravel sort the result are grouped by weeks Having a hotel booking application.
i want to get the This Weeks reservation count an Last Weeks reservation count.
so i achieved this with the below query, that gives the date by its week number. i want to sort it.
The query:
$byweek = Reservation::all()->groupBy(function($date) {
                                    return Carbon::parse($date->check_in)->format('W');
                                });

The output is like this:

Here 16 and 17 are week numbers, how can i sort it to get 17 and 16?

A: $byweek = Reservation::all()->groupBy(function($date) {
                                    return Carbon::parse($date->check_in)->format('W');
                                });

$byweek = $byweek->reverse();

Done
Get the all records and then reverse the collection to get the reverse 17, 16, 15 etc.. order.

A: I think y try
$byweek = Reservation::all()
            ->groupBy(DB::raw('WEEK(created_at)'))
            ->orderBy(DB::raw('COUNT(id)','desc'));

A: There is methods in Laravel collections ->sortKeys() and ->sortKeysDesc().
https://laravel.com/docs/5.6/collections#method-sortkeys
PHP has ksort() function too.

A: Try using orderBy inside the query and it works perfectly like this:
$byweek = Reservation::orderBy('check_in')->get()->groupBy(function($date) {
                                return Carbon::parse($date->check_in)->format('W');
                            });

don't forget that you have to use get() instead of all().
I tried this methods because I wanted the objects inside each week to be ordered and it works perfectly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error: Could not create the Java Virtual Machine on linux system I am trying to use bbmap (pileup.sh in= my.fa out=new.txt) to check the sequencing depth of assembly scaffolds derived from illumina reads.
Using Linux, I installed java jdk as you see:
$ java -version
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

Also, I installed bbmap module.
When I tried to run the pipeline : pileup.sh in= my.fa out=new.txt, I got this error :
Error occurred during initialization of VM
Unable to allocate 207104KB bitmaps for parallel garbage collection for the requested 6627328KB heap.
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

How can I fix this error?


text:
Q: Failed to execute 'postMessage' on 'DOMWindow': target/origin mismatch http vs https I apologize up front as I'm very confused by my problem. I'm really in a bind because this is causing a problem on my production site.
I have a javascript player on my site which plays through song lists which can be hosted on youtube, soundcloud or vimeo. Yesterday I noticed this error which generally arises anytime you try to load a new song through "skipping" with the player buttons. This error just started in the last day or two. I am not seeing anything new in the youtube api release notes and this error occurs using Chrome, Firefox and Safari, so it is most likely not related to a change in the browser. Something that I am using has changed though, as I have not pushed new code in 18 days.
An example playlist is here: http://www.muusical.com/playlists/programming-music
I think I have isolated the way to reproduce the error, here are the steps:

*

*Play a youtube hosted song.

*Skip to any other song in the list (whether by pressing the skip buttons or directly pressing the play button on the song's row item).

*Note, that if the first song in the playlist is a youtube song, simply skipping to another song even without playing the initially loaded youtube song will produce the error.
Essentially, the error seems to occur once you have loaded and/or played a youtube song and attempt to skip to another song.
Let me know if you find an exception to this behavior.
I see this error in the console:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.muusical.com') does not match the recipient window's origin ('http://www.muusical.com').

I load the player with using the youtube javascript api:
new YT.Player('playlist-player', {
      playerVars: { 'autoplay': 1, 'fs': 0 },
      videoId: "gJ6APKIjFQY",
      events: {
        'onReady': @initPlayerControls,
        'onStateChange': @onPlayerStateChange
      }
    })

Which produces this iframe:

After hitting skip from the above youtube song, this is what I see loaded in the iframe:

I support youtube, soundcloud and vimeo songs. It seems like once a youtube song is loaded the "origin" changes from http to https. I don't think it is necessary to include the embedding methods for the other hosts as this error occurs even if the entire playlist is only youtube and it does not occur in a playlist which consists of only songs from soundcloud and vimeo.
Also, this is how I am loading the youtube javascript:
// Load the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

Please let me know if you need me to clarify anything and thanks in advance for taking a look.

A: I have read a bit about this, some SO posts here and there and this link too : https://code.google.com/p/gdata-issues/issues/detail?id=5788
I was about to add a comment to your question, saying I was getting crazy over this ... but when I started to describe my setup, I found a way to avoid the issue ^^.
I start with an empty div element, and use the Youtube Iframe API to turn it into an iframe with all the necessary options.
I have multiple divs like this one, and usually use the same JS variable to store all those players, but one at a time (one replaces the other, and so on ... - it could be better, I know).
To fix the issue, I had the idea to destroy the player with youtubePlayer.destroy(); before building a new one from another element. No more JS errors bleeding in my Chrome console :).
Hope it helps, all the litterature I could read about http and https did not apply to my case, because I am not setting the iframe URL myself, and my website happens to be not https ...
I did restore an async call instead of a static script tag in my HTML but I do not think this was necessary.
EDIT : this error message is quite misleading in fact, it only vaguely means : you are not using the youtube API the proper way :)

A: @sodawillow's answer is partially correct but I'd like to give the details to the solution and what caused my code to stop calling the .destroy() method to remove the youtube player.
My site has a player which swaps out songs from various sites, one of them being Youtube. There can be different methods for removing a player depending on the type it is. My code checks for the existence of a youtube player and if passes the check then it uses the .destroy() method which only the youtube player has. The problem is that YouTube changed the names of some of the static variables on their player object. For example, if I created a player via:
var player = new YT.Player('playlist-player', {
      playerVars: { 'autoplay': 1, 'fs': 0 },
      videoId: "gJ6APKIjFQY",
      events: {
      }
    })

then there would be a variable player.L which held the string "player". So to check if the current player was a YouTube player and remove it I did this:
if (player.L == "player") {
  player.destroy();
} else {
//handle the removal of the Soundcloud or Vimeo player.
}

Sometime recently Youtube changed the location of the string "player" to now reside at player.M. I could change the above code to check player.M instead of player.L and that would work but to try to avoid this issue in the future I instead have implemented:
if (player.destroy) {
  player.destroy();
} else {
//handle the removal of the Soundcloud or Vimeo player.
}

As long as Youtube does not remove the .destroy() method unannounced this will not cause any issues.
So in summary, the issue was as @sodawillow guessed, I was not using the .destroy() method to remove the Youtube player. The reason was because Youtube made some unannounced changes to their api, changing the location of some of the static variables.

A: This error belongs to the Google Youtube API.
Inside "https://www.youtube.com/iframe_api":
if (!window['YT']) {
    var YT = {loading: 0, loaded: 0};
}
if (!window['YTConfig']) {
    var YTConfig = {'host': 'http://www.youtube.com'};
}

They use http instead of https.
We need to override the 'host' option and 'widget_referrer' same as 'origin'.
player = new YT.Player('player', {
          host: 'https://www.youtube.com',
          height: '390',
          width: '640',
          videoId: 'M7lc1UVf-VE'
...
          origin: "https://www.enziin.com",
          widget_referrer: "https://www.enziin.com"
}

Goodluck.

A: My solution is to write all the Youtube player logic in a separate page (as blank as posible) , and that page be referenced in an IFRAME tag.
" height="400px" width="100%" frameborder="0" border="0" scrolling="no">

Then, your youtube_frame.html will be something like this:
<!DOCTYPE html>

(As a marginal note: my context is that Prototype.js interferes with the event 'OnStateChange', and we cannot remove this dependency.
Using a jsfiddle would not be useful to reproduce the issue, as it has few dependencies.
My app here is built in Rails, and using this plugin for showing a Video playlist: https://github.com/Giorgio003/Youtube-TV/)


text:
Q: Is there any android phone allowing to use both the rear and front camera at the same time? I am doing a project on android phone and I hope to use the two camera at the same time. According to Is there any API to fetch both rear and front camera view at the same time?     , it may be possible to realize it. However, when I tried it on HTC One S, it cannot work -- the second camera cannot be open. So is there anyone who used to do it seccessfully? If so, please tell me which phone you worked on. Thank you in advance.

A: While it is possible in theory, in practice Android does not allow it at a firmware level. I'm not sure exactly what happens, but my guess is that one camera blocks some part of the API from the second one, thereby stopping two from working at once.
So for any device to do this, the manufacturer would have to change it at an OS level, and I don't think this has ever been done.

A: There are currently two phones that do the trick: Samsung Galaxy S4 and LG Optimus G Pro. Neither defines an API to 3rd parties to use this feature in their apps.


text:
Q: error while changing directory using crontab This is my script I am trying to rename the files in folder.
rename1.sh
----------
#!/bin/bash
cd /home/lanein1/WestonIN7pm/"$(date +%Y-%m-%d)" && rename s/WestonIN/WestonIN7pm/ *.jpg
cd /home/lanein1/WestonOUT7pm/"$(date +%Y-%m-%d)" && rename s/WestonOUT/WestonOUT7pm/ *.jpg

This is the error I get :
can't cd to /home/lanein1/scripts/rename1.sh

I don't understand why am  I getting this error
CRON ENTRY :
29 12 * * * cd /home/lanein1/scripts/rename1.sh >> /home/lanein1/scripts/rename2.log 2>&1

A: You're asking to change directory to the script:

cd /home/lanein1/scripts/rename1.sh >> /home/lanein1/scripts/rename2.log 2>&1

Perhaps you meant to run it:
/home/lanein1/scripts/rename1.sh >> /home/lanein1/scripts/rename2.log 2>&1


text:
Q: Command line program don't work correct on windows Command line program don't work correct.
I write test.py and setup.py, and do "python setup.py install".
I run "test.py", it results editer open test.py.
test.py don't print "test".
My enviroment is Python 2.7.6 on windows.
Please advise.
setup.py
# coding: UTF-8

from distutils.core import setup

setup(
    name = "test",
    version = "0.1",
    scripts = ['test.py']
)

test.py
# coding: UTF-8
print u"test"

A: your test.py has to start with #!python so the setup tool can use it.
from the documentation:

Scripts are files containing Python source code, intended to be
  started from the command line. Scripts don't require Distutils to do
  anything very complicated. The only clever feature is that if the
  first line of the script starts with #! and contains the word
  "python", the Distutils will adjust the first line to refer to the
  current interpreter location.

A: I solved this problem.
I delete editer, and it appear "select which program starts" window when I run test.py.
I select python.exe on this window.


text:
Q: type of recognition of convolution neural network I was trying to create a convolution neural network for the recognition of animals, vehicles, buildings, trees, plants from a large data-set having the combination of these objects.
At the time of training I got a doubt about the way in which the network should be trained. My doubt is that whether I could train the network with the data-set of whole animals as a single attribute or train each animals separately?
Means, one group for lions, one for tigers, one for elephants etc and at the time of testing I can code it to output the result as animal if any one of its subcategory is satisfied.
I got this doubt since I have read that there should be a correct pattern in the data-set for the efficient detection and there should be a pattern only if we are training with the subcategory of objects than the vast data-set.
I have attached a figure showing the sample dataset(only logically correct). I want to know whether there should be separate data-set or single data-set.

A: Training on a separate data-set or a single data-set will depend on a variety of factors. If you want to classify the images in your test dataset using the Convolution Neural Network into just animals and not further subdivide them, then training on a single-data should be done. However, if you plan to further sub classify the images into tigers and lions, then the training needs to be done on separate datasets of tigers and lions.
The type of the dataset that you use for training will highly depend on your requirements of classification on the test dataset.
Moreover, you have to make sure that you normalize the images before you use it for training.


text:
Q: How to solve keyboard crashes? I realized a program under codenameone and it worked very well; but since this morning I observe a bizzare behavior of my program that I newly compiled for android. Indeed on the identification's form for example, when I put the focus on the Login field and that I return on the PASSWORD field, the keyboard crashes and the text typed is confused with the text in Hint
Is this a compilation error? what is it, how to correct it.
Thanks


text:
Q: Escaping single and double quotes in a string in ruby? How can I escape single and double quotes in a string?
I want to escape single and double quotes together. I know how to pass them separately but don't know how to pass both of them.
e.g: str = "ruby 'on rails" " = ruby 'on rails"

A: My preferred way is to not worry about escaping and instead use %q, which behaves like a single-quote string (no interpolation or character escaping), or %Q for double quoted string behavior:
str = %q[ruby 'on rails" ] # like single-quoting
str2 = %Q[quoting with #{str}] # like double-quoting: will insert variable

See https://docs.ruby-lang.org/en/trunk/syntax/literals_rdoc.html#label-Strings and search for % strings.

A: >> str = "ruby 'on rails\" \" = ruby 'on rails"
=> "ruby 'on rails" " = ruby 'on rails"

A: I would go with a heredoc if I'm starting to have to worry about escaping. It will take care of it for you:
string = <<MARKER
I don't have to "worry" about escaping!!'"!!
MARKER

MARKER delineates the start/end of the string. start string on the next line after opening the heredoc, then end the string by using the delineator again on it's own line.
This does all the escaping needed and converts to a double quoted string:
string
=> "I don't have to \"worry\" about escaping!!'\"!!\n"

A: I would use just:

str = %(ruby 'on rails ")

Because just % stands for double quotes(or %Q) and allows interpolation of variables on the string.

A: Use backslash to escape characters
str = "ruby \'on rails\" "

A: Here is a complete list:

From http://learnrubythehardway.org/book/ex10.html

A: You can use Q strings which allow you to use any delimiter you like:
str = %Q|ruby 'on rails" " = ruby 'on rails|

A: Here is an example of how to use %Q[] in a more complex scenario:
  %Q[
    <meta property="og:title" content="#{@title}" />
    <meta property="og:description" content="#{@fullname}'s profile. #{@fullname}'s location, ranking, outcomes, and more." />
  ].html_safe

A: One caveat:
Using %Q[] and %q[] for string comparisons is not intuitively safe.
For example, if you load something meant to signify something empty, like "" or '', you need to use the actual escape sequences. For example, let's say qvar equals "" instead of any empty string.
This will evaluate to false
if qvar == "%Q[]"
As will this,
if qvar == %Q[]
While this will evaluate to true
if qvar == "\"\""
I ran into this issue when sending command-line vars from a different stack to my ruby script. Only Gabriel Augusto's answer worked for me.


text:
Q: What's the best short cut for this in MATLAB? padColor = [bgColor bgColor bgColor];
padColor = reshape(padColor,1,1,3);

How to do the above in a more compact way(less code/replication)?

A: ones(1,1,3)*bgColor

A: Alternatively, using repmat:
padColor = repmat(bgColor,[1,1,3])

A: Another one is:
padColor(:,:,1:3) = bgColor


text:
Q: SQL Server Cannot Create Transactional replication Error 14013 I am trying to create transactional replication but encountered the following error:
Please help,
[

A: You can follow these steps before setting up a Publication.
Tutorial: Prepare SQL Server for replication (publisher, distributor, subscriber)

*

*Create Windows accounts for replication.

*Prepare the snapshot folder.

*Configure distribution.
I believe you skipped this. If not, please edit you question with the steps you already followed successfully.


text:
Q: py3k: mapping dictionary (string->number) into list (of strings) Assume we have dictionary that translates strings into numbers.
How to reverse it into list ?
Let assume, we can fill not mapped numbers with empty string ''.
Here example how it works:
>>> dic_into_list({'x':0, 'z':2, 'w':3})
['x', '', 'z', 'w']

A: d = {'x':0, 'z':2, 'w':3}
lst = [""] * (max(d.values()) + 1)
for k, v in d.items():
    lst[v] = k
print(lst)

prints
['x', '', 'z', 'w']

A: The simplest way is to flip the dict and then iterate up to the maximum value (now key) in the dict:
original = {'x':0, 'z':2, 'w':3}
d = dict((v, k) for k, v in original.iteritems())
print [d.get(i, '') for i in range(max(d) + 1)]

A: I share my current solution: (I look for shorter and cleared implementation in other posts):
def dic_into_list(dic):
    maxindex = max([v for i,v in dic.items()])
    dicrev = {num:name for name,num in dic.items()}
    l=[]
    for i in range(0,maxindex+1):
        if i in dicrev:
            l.append(dicrev[i])
        else:
            l.append('')
    return l


text:
Q: Saving file data in an SQL Server database through PHP I have a problem in saving file data and retrieving content in original form using SQL Server.
To save content, I have used this code
$size = filesize($file);
$fp = fopen($file, 'rb');
$content = fread($fp, $size);
$content = addslashes($content);
fclose($fp);

and database to store its content is of type image.

A: Never do addslashes to binary files.addslashes should only be done on text data.
Image files,audio video files and executable all are binary files.
Try removing addslashes and try again.If it still doesn't get inserted into your database then you should check if the datatype of the column in your database is set to blob.Only blob datatype can hold binary data.
If still you have problems inserting to database then try inserting smaller images of size smaller than 1mb. php has  a default post and file upload limit of 2mb.


text:
Q: Theorem on Giuga number Giuga number : $n$ is a Giuga number  $\iff$ For every prime factor $p$ of $n$ , $p | (\frac{n}{p}-1)$
How to prove the following theorem on Giuga numbers
$n$ is a giuga number $\iff$ $\sum_{i=1}^{n-1} i^{\phi(n)} \equiv -1 \mod {n} $

A: The $\Rightarrow$ part.
For first, a giuga number must be squarefree, since, by assuming $p^2\mid n$, we have that $p$ divides two consecutive numbers, $\frac{n}{p}$ and $\frac{n}{p}-1$, that is clearly impossible. So we have:
$$ n = \prod_{i=1}^{k} p_i $$
that implies:
$$ \phi(n) = \prod_{i=1}^{k} (p_i-1).$$ By considering the sum
$$\sum_{i=0}^{n-1}i^{\phi(n)}$$
$\pmod{p_i}$ we have that all the terms contribute with a $1$, except the multiples of $p_i$ that contribute with a zero. This gives:
$$\sum_{i=0}^{n-1}i^{\phi(n)}\equiv n-\frac{n}{p_i}\equiv (n-1)\pmod{p_i}\tag{1}$$
that holds for any $i\in[1,k]$. The chinese theorem now give:
$$\sum_{i=0}^{n-1}i^{\phi(n)}\equiv n-1\pmod{\prod_{i=1}^{k}p_i}$$
that is just:
$$\sum_{i=0}^{n-1}i^{\phi(n)}\equiv -1\pmod{n}$$
as claimed. For the $\Leftarrow$ part, we have that the congruence $\!\!\!\pmod{n}$ implies the congruence $\!\!\!\pmod{p_i}$, hence $(1)$ must hold, so we must have:
$$\frac{n}{p_i}\equiv 1\pmod{p_i}$$
that is equivalent to $p_i\mid\left(\frac{n}{p_i}-1\right).$


text:
Q: What is the channel uri when registering a device via Microsoft's Azure Create a Registration call Following what's outlined here I've been able to so far read all registered devices, delete a device registration by id, and get a specific device registration by tag. What I want to do is register a device with a specific tag.
I found the page that specifies using this POST endpoint:
https://{namespace}.servicebus.windows.net/{NotificationHub}/registrations/?api-version=2015-01

I've applied the correct headers - Content Type, Authorization, and x-ms-version.
My question comes in the XML body that is getting sent. Where do I find the correct ChannelUri or is there something else in Azure / Firebase that I should be using in place of the channel uri?
<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom">
<content type="application/xml">
    <WindowsRegistrationDescription xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
        <Tags>myTag, myOtherTag</Tags>
        <ChannelUri>{ChannelUri}</ChannelUri>
    </WindowsRegistrationDescription>
</content>

Also, am I correct in thinking that the above api call will successfully register a device with the azure notification hub or am I missing a step somewhere?

A: The ChannelUri is a value that will be provided to you via UWP that allows you to target the particular Windows machine your application is running on (e.g.the example that you've provided above is WNS specific payload.)
Each Push Notification Service (PNS) has its own mechanism for uniquely identifying a device that should receive notifications. Other examples are included on the reference page you found, for instance you'll notice that Apple devices require a DeviceToken instead.


text:
Q: Pointer addition check I have a few questions about pointers.
I have the following struct
struct buffer {
    char *ptr;
    char data[DATA_SIZE];
};

and I have the following code
printk("ptrs and what not:  buf=%p, b-ptr=%p,   b-data=%p,    INIT_LOC=%lu\n", buf, buf->ptr, buf->data, INIT_LOC);

if (buf)
    buf->ptr = buf->data + INIT_LOC;

printk("ptrs and what not:  buf=%p, b-ptr=%p,   b-data=%p,    INIT_LOC=%lu\n", buf, buf->ptr, buf->data, INIT_LOC);

The output is the following:
ptrs and what not:  buf=ffff880091ae2000, b-ptr=          (null),   b-data=ffff880091ae2008,    INIT_LOC=10
ptrs and what not:  buf=ffff880091ae2000, b-ptr=ffff880091ae2012,   b-data=ffff880091ae2008,    INIT_LOC=10

questions
1) when adding a number, lets say 2  to a ptr with an address lets say 10001
is the value 10003, or 10001 + 2 * sizeof(X), where x is the type of the ptr.
2) if ptr=10001 is an array of chars in memory, the first character in that array is at location 10001, is the second character at location 10002 or 10009? or what would it be?
3) going to the printout shown above the buf->data has address 2008, i am not sure how adding 10 to it makes it point to 2012.
Thanks in advance.

A: *

*10001 + 2 * sizeof(X)

*10002

*It's in hex, 0x2012-0x2008 equals 10 in decimal.

A:
1) when adding a number, lets say 2 to a ptr with an address lets say 10001 is the value 10003, or 10001 + 2 * sizeof(X), where x is the type of the ptr.

Addition and subtraction moves the pointer X elements forth or back. This prevents you from having a mis-aligned pointer that points to the middle of a multi-byte object. (Unless you're doing invalid casts between pointer types).

2) if ptr=10001 is an array of chars in memory, the first character in that array is at location 10001, is the second character at location 10002 or 10009? or what would it be?

10002, since sizeof(char) is 1.

3) going to the printout shown above the buf->data has address 2008, i am not sure how adding 10 to it makes it point to 2012

Notice the hexadecimal notation.

A: 1) Both are wrong. X is the type of the pointee.
2) Unless your architecture can adress something smaller than a char, it should be 10002.
3) 0x2008 + 10 = 0x2012


text:
Q: Set location of PHP error message on page I am creating a log on and registration system. When validating the forms an error message is sent to the relevant page via this code -
echo '

';
    foreach ($error as $key => $values) {

     echo '
'.$values.'
';

The div it creates always appears at the top of the page above all my content. I've set my CSS to absolute and I can control the box. However, I don't want it absolute.
I'd like to tell the error message exactly which div to fill on the page. I've tried creating a div with the class .errormsgbox but it ignores it and creates it's own.
Any ideas?

A: Solved.
The message was appearing whereever my PHP include was for the posted file. Moved it and now all good. Hooray.


text:
Q: Passing data to Datagrid textbox in another form I open a datagrid when I double-click the textbox in my form1. I need to give two clicks on a cell of datagrid in form2 and when I click it already bring value to the textbox in form1. I've tried many ways no longer works, which he already ran automatically adds the value in the textbox before I click the cell, can anyone help?
I tried this:
in form1
         Ncm Ncm formNcm = new ();
         formNcm.Show ();
         ncmcb.Text formNcm.getNCM = ();
         ncmcb.Focus ();

the form2
public string getNCM ()
         {
             = dataGridView1.CurrentCell.Value.ToString value2 string ();
             return value2;
         }
Only this way it selects already own the value of the datagrid and I can not change, if I change it does not take the value for the textbox in form1

A: Design wise, one form should never know that other form has a textbox or drop down or some other control. Ideally the two forms should interact via public properties or custom events.
Assigning Value from Form2 to Form1

*

*Define a custom event in Form 2.

*Make the Form1 register with that event, so that when Form 2 fires it, Form1 can catch it.

*Capture the grid cell click event in Form2 and fire the custom event. You will be using EventArgs to pass the value.

*In Form1, event handler should get in action and there you can assign the value you sent from Form 2.
Here's an article doing exactly that : http://www.codeproject.com/Articles/17371/Passing-Data-between-Windows-Forms
if you want to assign a value from Form2 to Form1,
In Form 2 , define a property eg.
publis string MyTextBoxValue //Choose a better name :)
{
     set {myTextBox.Text = value;}
}

And when you open the form, you make the call in following manner,
     Ncm Ncm formNcm = new ();
     formNcm.MyTextBoxValue = "Grid Cell Value"; //Whatever your value is
     formNcm.Show ();
     ncmcb.Text formNcm.getNCM = ();
     ncmcb.Focus ();


text:
Q: How to fix cabal installation error I'm getting the following error when trying to install the contravariant library (which is needed for lens) with Cabal:
``src/Data/Functor/Contravariant.hs:96:1:
    StateVar-1.1.0.0:Data.StateVar can't be safely imported! The module itself isn't safe.''
I've not had any success googling solutions, and tried a few fixes (such as getting rid of all my Haskell packages (with ``rm -r ~/.ghc'') and starting again), but I'm not really clear on what's causing this error to occur. I'm using ghc 7.4.1 - could that be the problem?
Thanks,
Reuben

A: Posting the correct answer from comments as community-wiki:

Looks like you're being hit by interactions between an old GHC and the
  lack of Safe Haskell annotations (in the library) that are redundant
  with newer GHC versions. Cf. http://github.com/ekmett/ersatz/issues/13


text:
Q: Scipy.optimize and callback not working when using workers I'm using scipy.optimize (differential evolution) for optimisation. Overall works great. I've started to use the worker feature (which allows you to tell the optimisation to spin off individuals in the population into other processes, effectively parallelizing the optimisation process very easily).
I see that if I specify workers=-1, all my cores are being put to work, as they should.
The simulation is managed in a structure:
""" Sandbox stuff """
from scipy.optimize import *

class Simulation:
    def __init__(self):
        self.data = None

    def optim_manager(self):
        optimized_results = differential_evolution(self.optim_loop,
        bounds=self.bounds, callback=self.optim_callback, workers=-1)

    def optim_loop(self, parameters):
        self.data = run_model(parameters)
        optim_value = self.calc_optim_value(self.data)

        # at this point self.data exist & is not None
        return optim_value

    def optim_callback(self,*args):
        # *args contains the parameters value for that optimal run
        optim_value = self.calc_optim_value(self.data)              # error
        write_optimisation_run_to_dictionnary(args, optim_value)

However, when I try to calculate the optim_value in the callback, I get:
Traceback (most recent call last):
  File "lancer_modele.py", line 512, in <module>
    mp.launch()
  File "lancer_modele.py", line 234, in launch
    self.do_optim_ghosts()
  File "lancer_modele.py", line 296, in do_optim_ghosts
    opt.opti_manager_ghosts(**merged_kwargs)
  File "/home/atari/PycharmProjects/RT/managers/optimisation.py", line 41, in opti_manager_ghosts
    simul_params = simul.fctopti_ghosts(nbrite=1, free_params_ordereddict=free_init_params[-1], **kwargs)   # it returns other stuff we don't need, a,b,c
  File "/home/atari/PycharmProjects/RT/managers/Simulation.py", line 225, in fctopti_ghosts
    popsize=5, callback=self.optim_callback, workers=2)
  File "/home/atari/.local/lib/python3.6/site-packages/scipy/optimize/_differentialevolution.py", line 272, in differential_evolution
    ret = solver.solve()
  File "/home/atari/.local/lib/python3.6/site-packages/scipy/optimize/_differentialevolution.py", line 701, in solve
    convergence=self.tol / convergence) is True):
  File "/home/atari/PycharmProjects/RT/managers/Simulation.py", line 433, in optim_callback
    optim_value = self.calc_ghost_optimized_value()
  File "/home/atari/PycharmProjects/RT/managers/Simulation.py", line 509, in calc_ghost_optimized_value
    optim_value = np.sum(cubedata[:,:,self.gstart_tick:self.gstop_tick])
TypeError: 'NoneType' object is not subscriptable

Because self.data is None in the context of the optim_callback. This works fine however if I use only 1 core. I am guess that when using multiple cores, the class is serialized and passed around and attributes updated in each process that runs. Then it returns to the main process, where Simulation is still as it was because worker spin-off were called (therefore it still has self.data = None). Meaning I can't easily calculate the optim value, and it seems that although scipy's callback gives me the parameters values all right, it doesn't passes the value I told it those were worth in my model.
Any idea? I guess I could separately re-create a complete model in the optim_callback, update it with the parameters provided, run it again to get the optimization value. However running a model is moderately long and I'd rather not slow down the optimization each and every time I get an (intermediate) optimal value.

A: Actually, there seems to be no reason why DifferentialEvolution doesn't return the optimization value. Therefore, it's possible to subclasss
from scipy.optimize._differentialevolution import DifferentialEvolutionSolver

And one only needs to edit a few lines in DifferentialEvolutionSolver.solve() at line 697:
     if (self.callback and
             self.callback(self._scale_parameters(self.population[0]),
                           convergence=self.tol / convergence) is True):

Becomes:
    if (self.callback and
            self.callback(self._scale_parameters(self.population[0]),
                          convergence=self.tol / convergence, optim_value=self.population_energies[0]) is True):

As self.population_energies contains the optimizations values thus far, with [0] being the best value at this point.
Therefore in the callback method:
def optim_callback(self,*args, **kwargs):
    # *args contains the parameters value for that optimal run
    optim_value = kwargs['optim_value']
    write_optimisation_run_to_dictionnary(args, optim_value)

Will provide the optimization value without the need to re-launch the model.


text:
Q: Is there a term for preloading video? When playing videos with slow connectivity from YouTube, I often pause the video to allow the loaded video portion to grow.  I was wondering if any of the technophiles could weigh in on a possible term for this practice. It seems to me that  preloading could work, but I figured I could ask about a better term.

A: Depends on whom you're addressing. You're probably asking the wrong people. Videophiles may well have a specific term for this.
You could make one up or adapt a general term like caching or buffering as suggested in the comments if you want to. But in a language where we still talk about dialing a telephone anything can happen.

A: The word you are looking for is buffer. Since the playback speed of a video is typically faster than the download speed, the video can't be played immediately. As it is downloaded, it is buffered until there is enough data stored to be able to play the video at its proper speed while the rest of the data is downloaded.


text:
Q: AH00127: Cannot map HEAD... and Blank Page I've a Magento 1.7 store in a dedicated Apache 2.4/Ubuntu host.
My site is breaking down for some hours since last week.
Site is not offline but showing blank pages.
When I see the problem I restart Apache, and site is up.
But site goes down in the next day, in high traffic hours (high traffic for me is 10 orders/hour).
Looking for log files I can see this AH00127 many times.
I think it happens when reloading the blank page.
[core:error] [pid 19744] (36)File name too long: [client mas.ked.xx.xxx:60403] AH00127: Cannot map GET /tag/index/save/product/2087/uenc/aHR0cDovL3d3dy50b2NhZG92ZXJkZS5jb20uYnIvcHJhdG8tdmlvbGV0YS1jZXJhbWljYS5odGLa/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1fwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1YwWVMxalpYSmhiV2xqWVM1b2RHMXMv/ HTTP/1.1 to file, referer: http://www.mysite.com.br/product_name.html/

PHP Error Log says only this error, many occurences:
PHP Fatal error:  Call to a member function isRequired() on a non-object in /var/www/includes/src/Mage_Captcha_Model_Observer.php on line 167

Anyone know what is happening here?
At a first glance I disabled Mage_Captcha in backend. But the errors keep same.
My Apache settings:
<VirtualHost *:80>
    ServerAdmin webmaster@mysite.com
    ServerName mysite.com
    ServerAlias www.mysite.com
    DocumentRoot /var/www
    DeflateCompressionLevel 2
    <Directory /var/www/>
        #Options Indexes FollowSymLinks
        DirectoryIndex index.php
        AllowOverride none
        Require all granted
        AddDefaultCharset Off
        RewriteEngine on
        RewriteCond %{HTTP_HOST} !^www\.mysite\.com\.br
        RewriteRule ^(.*)$ http://www\.mysite\.com\.br/$1 [R=301,L]
        RewriteCond %{HTTP_REFERER} badass_cover_all_mycontent\.com [NC]
        RewriteRule .* - [F]
        <IfModule mod_php5.c>
            php_value memory_limit 256M
            php_value max_execution_time 120
            php_flag magic_quotes_gpc off
            php_flag session.auto_start off
            #php_flag zlib.output_compression on
            php_flag suhosin.session.cryptua off
            php_flag zend.ze1_compatibility_mode Off
        </IfModule>
        <IfModule mod_security.c>
            SecFilterEngine Off
            SecFilterScanPOST Off
        </IfModule>
        <IfModule mod_deflate.c>
            <IfModule mod_filter.c>
                SetOutputFilter DEFLATE
                AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
                BrowserMatch ^Mozilla/4 gzip-only-text/html
                BrowserMatch ^Mozilla/4\.0[678] no-gzip
                BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
                SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
                Header append Vary User-Agent env=!dont-vary
            </IfModule>
        </IfModule>
        <IfModule mod_headers.c>
            Header set Access-Control-Allow-Origin '*'
        </IfModule>
        <IfModule mod_ssl.c>
            SSLOptions StdEnvVars
        </IfModule>
        <IfModule mod_rewrite.c>
            #Options +FollowSymLinks
            RewriteEngine on
            RewriteBase /
            RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
            RewriteRule ^(index.php/)?minify/([^/]+)(/.*.(js|css))$ lib/minify/m.php?f=$3&d=$2
            RewriteCond %{REQUEST_URI} !^/(media|skin|js)/
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteCond %{REQUEST_FILENAME} !-l
            RewriteCond %{REQUEST_URI} !=/server-status
            RewriteRule .* index.php [L]
        </IfModule>
        ExpiresActive On
        ExpiresDefault "access plus 1 year"
    </Directory>
    <Directory /var/www/app/>
        Require all denied
    </Directory>
    <Directory /var/www/app/errors/>
        <FilesMatch "\.(xml|phtml)$">
            Require all denied
        </FilesMatch>
    </Directory>
    <Directory /var/www/pkginfo/>
        Require all denied
    </Directory>
    <Directory /var/www/lib/>
        #Require all denied
    </Directory>
    <Directory /var/www/var/>
        Require all denied
    </Directory>
    <Directory /var/www/includes/>
        Require all denied
    </Directory>
    <Directory /var/www/media/>
        Options All -Indexes
        #<IfModule mod_php5.c>
        #   php_flag engine 0
        #</IfModule>
    </Directory>
    <Directory /var/www/downloader/>
        <Files ~ "\.(cfg|ini|xml)$">
            Require all denied
        </Files>
    </Directory>
</VirtualHost>

A: Most likely the cause is a bad mod_rewrite rule in your .htaccess possibly?

*

*https://serverfault.com/questions/388858/how-to-fix-file-name-too-long-error-in-apache2
Also, if you note the redundant GET URL in the log which may be caused by a misconfiguration on the server for the HTTP referer:

/tag/index/save/product/2087/uenc/aHR0cDovL3d3dy50b2NhZG92ZXJkZS5jb20uYnIvcHJhdG8tdmlvbGV0YS1jZXJhbWljYS5odGLa/index.php/customer/account/login/referer/aW5kZXgucGhwL3RhZy9pbmRleC9zYXZlL3Byb2R1Y3QvMjA4Ny91ZW5jL2FIUjBjRG92TDNkM2R5NTBiMk5oWkc5MlpYSmtaUzVqYjIwdVluSXZjSEpoZEc4dGRtbHZiR1fwWVMxalpYSmhiV2xqWVM1b2RHMXMv
  /index.php/customer/account/login/referer/aW5k ...

But this in regards to the /product_name.html file which is not default Magento.
And you may want to consider disabling compilation and using an OPCode cache instead to remove the possibly headaches caused by it, it may also be the source of your issues.

*

*is it safe to run magento compiler?
Also make sure you have the Log cleaning enabled in Magento's admin configured as it will help to clean out the generated captcha images. You can do this manually by simply removing all files under /media/captcha.


text:
Q: Model-based partitioning with "two-layer interaction" (segmented models) I am trying to build a model-based tree with a type of "two-layer interaction" where the models in the nodes of the tree are segmented again.
I am using the mob() function to this aim but I could not manage to make the argument for the fit function work with the lmtree() function.
In the following example a is function of b and the relationship between a and b depends on d and on b | d.
library("partykit")
set.seed(321)

b <- runif(200)
d <- sample(1:2, 200, replace = TRUE)
a <- jitter(ifelse(d == 1, 2 * b - 1, 4 * b - 1.2), amount = .1)
a[b < .5 & d == 1] <- jitter(rep(0, length(a[b < .5 & d == 1])))
a[b < .3 & d == 2] <- jitter(rep(0, length(a[b < .3 & d == 2])))

fit <- function(y, x, start = NULL, weights = NULL, offset = NULL, ..., estfun = FALSE, object = FALSE)
{
  x <- x[, 2]
  l <- lmtree(y ~ x | b)
  return(l)
}

m <- mob(a ~ b | d, fit = fit) # not working

Of course with this simple example I could use lmtree(a ~ b | d + b) to find every interaction but is there a way to use as fit function of mob() a lmtree()?

A: No but yes ;-)
No, lmtree() cannot be used easily as a fitter for a mob().

*

*The dimension of the inner tree (lmtree()) is not fixed, i.e., you may get a tree without any partition or with many subgroups, and this would be confusing for the outer tree (mob()).

*Even if one worked around the dimension issue or fixed it by always forcing one break, one would need more work to set up the right coefficient vector, matrix of estimating functions, etc. This is also not straightforward because the convergence rate (and hence the inference) is different if breakpoints are given (e.g., for a binary factor) or have to be estimated (such as for your numeric variables b).

*The way you set up your fit() function, the inner lmtree() does not know where to find b. All it has is a numeric vector y and a numeric matrix x but not the original data.
But yes, I think that all of these issues can be addressed if changing the view from fitting a "two-layer" tree to fitting a "segmented" model inside a tree. My impression is that you want to fit a model y ~ x (or a ~ b in your example) where a piecewise linear function is used with an additional breakpoint in x. If the piecewise linear function is supposed to be continuous in x, then the segmented package can be easily used. If not, then strucchange could be leveraged. Assuming you want the former (as you have simulated your data like this), I include a worked segmented example below (and also slightly modified your question to reflect this).
Changing the names and code a little bit, your data d has a segmented piecewise linear relationship of y ~ x with coefficients depending on a group variable g.
set.seed(321)
d <- data.frame(
  x = runif(200),
  g = factor(sample(1:2, 200, replace = TRUE))
)
d$y <- jitter(ifelse(d$g == "1",
  pmax(0, 2 * d$x - 1),
  pmax(0, 4 * d$x - 1.2)
), amount = 0.1)

Within every node of a tree I can then fit a model segmented(lm(y ~ x)) which comes with suitable extractors for coef(), logLik(), estfun() etc. Thus, the mobster function is simply:
segfit <- function(y, x, start = NULL, weights = NULL, offset = NULL, ...)
{
  x <- as.numeric(x[, 2])
  segmented::segmented(lm(y ~ x))
}

(Note: I haven't tried whether segmented() would also support lm() objects with weights and offset.)
With this we can obtain the full tree which simply splits in g in this basic example:
library("partykit")
segtree <- mob(y ~ x | g, data = d, fit = segfit)
plot(segtree, terminal_panel = node_bivplot, tnex = 2)

A hands-on introduction to segmented is available in: Muggeo VMR (2008). "segmented: An R Package to Fit Regression Models with Broken-Line Relationships." R News, 8(1), 20-25.  https://CRAN.R-project.org/doc/Rnews/
For the underlying methodological background see: Muggeo VMR (2003). "Estimating Regression Models with Unknown Break-Points." Statistics in Medicine, 22(19), 3055-3071. doi:10.1002/sim.1545


text: Q: How to stub getting user ip? My site needs to know user location. Using browser's geolocation API is not enough. So it takes user ip and uses geoip database to find out user location. But when I run tests, there's no such thing as client ip. Can I stub it somehow? Laravel's documentation says that one shouldn't stub (or to be precise, mock) Request facade. What do I do then?


text:
Q: Send rest requests to amazon web services with visual foxpro (posible signature error) I'm trying to send instructions in order to create a new SimpleDB domain using VFP9.
The .fll library come thanks to sweet potato software, and the hour difference was solved using an additional variable. I've seen other samples with java and php here. Also, I'been checking the aws developer page for examples on this:
http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/index.html?REST_RESTAuth.html
http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API_CreateDomain.html
but still, no luck. I've made a .prg file for test my connection, and receive a:
<?xml version="1.0"?>
<Response><Errors><Error>SignatureDoesNotMatch<Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.</Message></Error></Errors><RequestID>2e4718de-4ba2-2f76-0aad-a7f3a4c86ab5</RequestID></Response>

Here's the code for my .prg:
*   http://www.sweetpotatosoftware.com/SPSBlog/2009/08/09/MajorVFPEncryptionUpdate.aspx

SET LIBRARY TO ('vfpencryption71.fll')

PUBLIC cURL_AWS_SDBService

PUBLIC cAWSAccessKeyId
PUBLIC cAWSSecretAccessKey
PUBLIC cAWS_Action
PUBLIC cAWS_SignatureMethod
PUBLIC cAWS_SignatureVersion
PUBLIC cAWS_Version
PUBLIC cAWS_TimeStamp
PUBLIC cAWS_Signature
PUBLIC nAWS_UTCDifference

nAWS_UTCDifference = 5

cURL_AWS_SDBService = 'https://sdb.amazonaws.com'
cAWS_Action = 'CreateDomain'
cAWSAccessKeyId = (MY_ACCESS_ID)
cAWSSecretAccessKey = (MY_SECRET_ACCESS_KEY)
cAWS_TimeStamp = STRTRAN(STRCONV(TTOC(DATETIME() + (60 * 60 * nAWS_UTCDifference),3),9),':','%3A') + '-00%3A00'
cAWS_SignatureVersion = '2'
cAWS_SignatureMethod = 'HmacSHA256'
cAWS_Version = '2009-04-15'

LOCAL cFirma
SET TEXTMERGE on
TEXT TO cFirma noshow
GET\n<<cURL_AWS_SDBService>>\n/\nAWSAccessKeyId=<<cAWSAccessKeyId>>&Action=<<cAWS_Action>>&DomainName=Atoq_SDB&SignatureMethod=<<cAWS_SignatureMethod>>&SignatureVersion=<<cAWS_SignatureVersion>>&Timestamp=<<cAWS_TimeStamp>>&Version=<<cAWS_Version>>
ENDTEXT
SET TEXTMERGE off
clear
?cFirma

cAWS_Signature = HMAC(cFirma,cAWSSecretAccessKey ,2)
cAWS_Signature = STRCONV(cAWS_Signature,15)
?
?cAWS_Signature
?
SET TEXTMERGE on
TEXT TO cCadena noshow
<<cURL_AWS_SDBService>>/?Action=<<cAWS_Action>>&AWSAccessKeyId=<<cAWSAccessKeyId>>&DomainName=New_Database&SignatureVersion=<<cAWS_SignatureVersion>>&SignatureMethod=<<cAWS_SignatureMethod>>&Timestamp=<<cAWS_TimeStamp>>&Version=<<cAWS_Version>>&Signature=<<cAWS_Signature>>
ENDTEXT

SET TEXTMERGE off
?cCadena
?
objSrvHTTP = CreateObject ("Msxml2.ServerXMLHTTP.3.0")
objSrvHTTP.open('GET',cCadena, .F.)
objSrvHTTP.send()

?objSrvHTTP.responseText

What i'm doing wrong here?
TIA

A: Dumb question but, are you using STRCONV(cAWS_Signature,15) instead of STRCONV(cAWS_Signature,13) on purpose?  The Amazon docs makes a reference to Base64Encode(Signature) which is what the 13 seems to mean in VFP9's help file for strconv()


text:
Q: check and find database record with no data in rails I am working on a rails app. I have a listings form which creates the listings. There are no validations while creating the listings form other than on some basic fields. But I wont let the users publish the listings if any of the fields are not filled up. In their dashboard I am showing all their listings.
But how can I find the listings with unfilled database fields??..so that I can show it in a different uncompleted listings tab for them to fill out later..The listing model has_many relation with a photos table.
Update as per Rich Peck's answer
For the enum I added a status field to my listing table with default value 0 and its showing published and draft listings as expected on my existing listings. But I cant create new records now..
Getting below error now while updating records

undefined method `draft?' for "draft":String

I think this validation is causing the error
validates :bed_room, :bath_room, :listing_name, :summary, :building_name, presence: true, unless: "status.draft?"

A: If you wanted to keep your current flow, you'll have to pick through any records in the database which might be nil (difficult):
#Controller
@listings = current_user.listings.unfinished

#app/models/listing.rb
class Listing < ActiveRecord::Base
   def self.unfinished
    execute(";WITH XMLNAMESPACES('http://www.w3.org/2001/XMLSchema-  instance' as ns) SELECT * FROM Listings WHERE  (SELECT Listings.*
    FOR xml path('row'), elements xsinil, type
    ).value('count(//*[local-name() != "colToIgnore"]/@ns:nil)', 'int') > 0")
   end
end

I have absolutely no idea if the above will work. It uses execute in ActiveRecord to use a pure SQL query.

wont let the users publish the listings

This sounds like you want to make draft functionality.
I would strongly recommend putting validations into your model so that you don't have to pick through a database that might have null values dotted around.
I know you said you have this already; I would make the validations conditional on whether the status of the listing is to be "published" or not (with an enum)...
#app/models/listing.rb
class Listing < ActiveRecord::Base
   enum status: [:draft, :published] #-> defaults to draft
   belongs_to :user
   has_many   :photos

   scope :draft,     -> { where status: :draft     }
   scope :published, -> { where status: :published }

   ####

   validates :name, :user, :photos, :etc, :etc, presence: true, unless: "status.draft?"

   ####

   def publish!
      self.update status: :published
   end
end

This would work similarly to the Wordpress "draft" functionality (IE publishing and saving are two completely different things):
#config/routes.rb
resources :listings do
    post :publish, on: :member #-> url.com/listings/:id/publish
end

#app/controllers/listings_controller.rb
class ListingsController < ApplicationController
    def new
       @listing = current_user.listings.new
    end

    def create
       @listing = current_user.listings.new listing_params
       @listing.save #-> will be "draft" by default so no validations
    end

    def publish
       @listing = current_user.listings.find params[:id]
       redirect_to @listing if @listing.publish!
    end
end

In your front-end, you'll be able to then list the @listings by whether they're published or draft:
#app/views/listings/index.html.erb
<% @listings.published do |published| %>
    ...
<% end %>

<% @listings.draft do |draft| %>
   ...
<% end %>

Update
According to the OP, the answer was to use the following in his model:
#app/models/listing.rb
class Listing < ActiveRecord::Base
   enum status: [:draft, :published] #-> defaults to draft
   belongs_to :user
   has_many   :photos

   ####

   validates :name, :user, :photos, :etc, :etc, presence: true, unless: "draft?"

   ####

   def publish!
      self.update status: :published
   end
end

A: Assuming Listing is your model name and required_field is a unfilled field name,

Listing.where(required_field: nil).where(user: current_user)

will give the listings of the current user with unfilled fields.

listings.includes(:photos).where(photos: { id: nil })


text:
Q: debugging a method for finding running average of frames from video for motion detection using OpenCV in C++ So to practice C++ I'm writing a motion detection program that uploads photos to dropbox using the OpenCV library, a project that I did last summer in pyton following this tutorial:  https://www.pyimagesearch.com/2015/05/25/basic-motion-detection-and-tracking-with-python-and-opencv/
This section of code is running once, and then throwing an error on the second loop.
This is the code:
Mat set_delta(Mat &average, Mat gray_frame)
{
    Mat delta_frame;
    if (average.empty()==1)
    {
        cout<<"gray frame depth: "<<gray_frame.depth();

        gray_frame.convertTo(average, CV_32FC(gray_frame.channels()));
        //Mat Acc(gray_frame.rows,    gray_frame.cols,CV_32FC(gray_frame.channels()));
    }
    //cout<<"gray_frame average: "<< get_average(gray_frame)<<
    //      "\naverage_frame average: "<<get_average(average);
    Mat Acc(average.rows, average.cols,CV_32FC(average.channels()));

    cout<<"average depth: "<<average.depth()<<"\nAcc depth: "<<Acc.depth();

    accumulateWeighted(gray_frame, average, .5);
    convertScaleAbs(average, average);
    absdiff(gray_frame,average,delta_frame);
    return delta_frame;
}

I'm getting this error:
OpenCV Error: Assertion failed (func != 0) in accumulateWeighted, file /build/opencv/src/opencv-3.3.1/modules/imgproc/src/accum.cpp, line 635
terminate called after throwing an instance of 'cv::Exception'
what():  /build/opencv/src/opencv-3.3.1/modules/imgproc/src/accum.cpp:635: error: (-215) func != 0 in function accumulateWeighted

the error is being generated by the accumulate Weighted function, which I tried to fix by creating a local array Acc after reading these pages:
http://answers.opencv.org/question/63781/accumulateweighted-problems/
Assertion failed with accumulateWeighted in OpenCV
I need to find out why this is terminating on the second loop. I think this is a symantic error. the code runs as written, but my instructions aren't actually what I intend/need it to do.
some possibly useful information:
Acc was originally based off gray_frame but I realized the design of this method depended on the global value average, causing the delta frame to have an outline of the original frame in all proceeding frames. So I'm trying to redesign it to stick to using global average.
The channels for all 3 (gray_frame, average, and Acc) is one.
The depth of gray frame stays at 0.
The depth for average at first is 5(after the if statement), then 0, whereas the depth of Acc stays at 5. It seems as is the main loop executes once and then quits.
a single average value of average before the accumulate weighted of the second loop is the same as the average of the first. around 97.89
The entire C++ program (work in progress) can be found here: https://github.com/skewballfox/SauronsEye/blob/master/SauronsEye.cpp
My work from last summer that I'm somewhat using as a guide (this was mainly for me to practice and never really was intended to be viewed so it's kinda messy):
https://github.com/skewballfox/opencv-practice/blob/master/pi_surveillance.py

A: The issue is when scaling average in convertScaleAbs() this changes the type of average to 0 or CV_8U. this was fixed by creating an empty Mat() and storing the results in there, as opposed to scaling average itself:
Mat set_delta(Mat &average, Mat gray_frame)
{
    Mat delta_frame, scaled_average;
    //delta_frame is the storage for the difference between the accumulated average
    //and the current gray frame. scaled average is for storing the output of convertScaleAbs()
    //otherwise the depth of global average is 0 and causes an error on the second loop
    if (average.empty()==1)
    {
        gray_frame.convertTo(average, CV_32FC(gray_frame.channels()));
    }

    accumulateWeighted(gray_frame, average, .5);
    convertScaleAbs(average, scaled_average);
    absdiff(gray_frame,scaled_average,delta_frame);

    return delta_frame;
}


text:
Q: Compiling with python on CentOS 8 returns errors I have installed the latest node, npm and python versions but get the following error when I try to install leveldown (using npm):
> leveldown@2.1.1 install /root/apps/authentication/node_modules/leveldown
> prebuild-install || node-gyp rebuild

prebuild-install WARN install No prebuilt binaries found (target=10.16.3 runtime=node arch=x64 platform=linux)
gyp ERR! configure error
gyp ERR! stack Error: Command failed: /bin/python -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                                ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:294:12)
gyp ERR! stack     at ChildProcess.emit (events.js:198:13)
gyp ERR! stack     at maybeClose (internal/child_process.js:982:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
gyp ERR! System Linux 4.18.0-80.11.2.el8_0.x86_64
gyp ERR! command "/usr/bin/node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /root/apps/authentication/node_modules/leveldown
gyp ERR! node -v v10.16.3
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
npm WARN auth@1.0.0 No description
npm WARN auth@1.0.0 No repository field.
npm WARN auth@1.0.0 No license field.

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! leveldown@2.1.1 install: `prebuild-install || node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the leveldown@2.1.1 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2020-01-08T21_40_49_710Z-debug.log

It seems that python doesn't compile on CentOS 8... any help is welcome
FYI I'm not using directly leveldown but it's a dependency of PouchDB

A: You have installed Python 3 but you are running code that expects Python 2. You can install the python2 package and then you may be able to instruct your npm install process to use /usr/bin/python2 instead of /usr/bin/python.
If that's not possible, you should be able to symlink /usr/bin/python to /usr/bin/python2. By default, CentOS 8 doesn't have a /usr/bin/python (it has only python2 or python3 commands), so this should be harmless.

Note that Python 2 has just reached end of life. Any software that still expects Python 2 at this point may not have seen updates in a while.


text:
Q: How long can he be the Hulk before he has to turn back into a puny human? It used to be: "The madder Hulk gets, the stronger Hulk gets!" and then he'd revert back when he calmed down. I always assumed it was to recharge. Now it appears Bruce Banner can change into the Hulk at will. What is the longest amount of time (either Dr. David or Bruce) Banner maintained his Hulk alter-ego before he had to turn back into a puny human?

A: I don't know if anyone is keeping track, so I doubt there's an official record of the longest amount of time that Banner has stayed the Hulk.  There have been several periods that stretched on for months where he stayed in his green Hulk form though.  This happened once during the Merged Hulk/Professor incarnation, which was basically the mind of Bruce Banner in control of the Hulk's physical form, and more recently during the events of Planet Hulk through the end of World War Hulk.

A: This answer is actually a simple one.
Bruce Banner, essentially, represents the calm feelings in the Banner/Hulk creature. He is the weakness in the Hulk and this is why the Hulk has always despised him.
As shown several times, the Hulk can stay angry indefinitely, while awake and with Banner in him. When, in one comic, Bruce Banner reaches the end of his natural lifespan, the Hulk essentially makes himself immortal by staying angry forever. However, it is important to note that at this point, Banner is essentially dead and gone, affording the Hulk the ability.
With Banner in and against him he can stay the Hulk as long as he doesn't calm down or sleep. Without Banner or in accordance with Banner (as seen with several versions of the Hulk), he never needs to change back.

A: In Thor Ragnarok movie, Banner stayed as Hulk for 2 years and he would have remained that way if he hadn't seen and heard Black Widow's message.
So, the answer is "Lifetime".


text:
Q: Поменять значение глобальной переменной внутри функцию я хочу создать функцию в которой за аргумент будет приниматься глобальная переменная и внутри функции изменить значение этой переменной. Но изменений никаких не происходит
def tst(arg1,arg2):
    arg1 += 15
    arg2 = 17
    return arg1, arg2

abc = 15
zxc = 15
tst(abc,zxc)

print(abc, zxc) выводит: abc = 15, zxc = 15
В функции ниже я хочу повлиять на две переменные через аргументы. В переменную по аргументу arg_ret_index я хочу переназначить значение. Переменная по ключу arg_dict это словарь и я хочу добавить новое значение к существующему ключу в этот словаарь. Поидее манипуляция с добавлением нового значения в ключ не должна сработать. Потому что это словарь из глобальной переменной, но значение всё равно добавляется. Обьясните плз почему так происходит?)
def ZTE_HO_index(arg_dict, arg_key, arg_ret_index, start_i, finish_i):
    for i in range(start_i, finish_i):
        if i not in arg_dict[str(arg_key)]:
            arg_ret_index = i
            arg_dict[str(arg_key)] = arg_dict.get(str(arg_key), []) + [i]
            break
    return arg_ret_index

A: Вы должны присвоить значения глобальным переменным:
def tst(arg1,arg2):
    arg1 += 15
    arg2 = 17
    return arg1, arg2

abc = 15
zxc = 15
abc, zxc = tst(arg1=abc, arg2=zxc)
print(abc, zxc) # выведет (30, 17)

A: Всё, что вы делаете с аргументами функции, остаётся внутри функции. Потому что это копии значений внешних переменных, помещённые в переменные - аргументы функции. Какие бы вы вычисления и присваивания не делали - всё это пропадёт с окончанием функции, потому что это локальные переменные функции.
Есть несколько вариантов для функции что-то поменять вовне себя:

*

*В явном виде вернуть результаты наружу через return. Это самый правильный способ, потому что "явное лучше неявного".

*Получить доступ к глобальным переменным, объявив их внутри функции как global и присвоить им что нужно. Это плохой способ, так делать не рекомендуется. В идеале функция должна быть вещью в себе и знать о внешнем мире самый минимум в виде аргументов, которые она в явном виде получает на вход. Функция не должна ничего знать про какие-то ещё внешние переменные.

*Ещё один способ - это получить на вход не простые переменные, а коллекции (например - список, словарь). С коллекциями функция тоже может что-то делать, как-то менять их содержимое, но опять же это не самый хороший способ, даже при таком подходе лучше не менять исходную коллекцию, а сделать её копию, поменять в ней что нужно, и вернуть в явном виде новую коллекцию.

P.S. Ещё раз про коллекции. Саму переменную - ссылку на коллекцию - вы поменять не можете, всё, что вы присвоите переменной аргументу функции наружу по-прежнему не уйдёт. А вот содержимое коллекции вам вполне доступно, потому что в функцию передаётся ссылка на коллекцию и по этой ссылке вы можете что угодно делать с содержимым коллекции - добавлять элементы, удалять и т.д.

A: Можно так, но не рекомендуется.
# Глобальные переменные

a = 0

def change_the_sign_of_the_global_variable():
    global a
    a += 1

def main():
    change_the_sign_of_the_global_variable()
    print(a)

if __name__ == '__main__':
    main()


text:
Q: Spring jdbcTemplate Junit I have one application with DAO as follows. I want to junit this class. My Class looks like this.
    public class DaoImpl implements Dao{

    @Override
    public User getUserInfo(String userid) {
        return getTemplate().queryForObject(QUERY, new Object[] { userid },
                new BeanPropertyRowMapper<User>(User.class));
     }

   }

My junit class looks like this
@RunWith(SpringJUnit4ClassRunner.class)
public class DaoImplTests{

    @Autowired
    private Dao dao;

    @Mock
    JdbcTemplate jdbcTemplate;

    @Test
    public void testUsingMockito() {
        try {
            User mockedUserInfo = new User();
            //setters
            mockedUserInfo.setXXX;
            mockedUserInfo.setYYY;

            Mockito.when(((JdbcDaoSupport)dao.getTemplate())).thenReturn(jdbcTemplate);
            Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(Object[].class),
                    Mockito.any(RowMapper.class))).thenReturn(mockedUserInfo);
            User userInfo = dao.getUserInfo("");
            Assert.assertNotNull(userInfo);
            Assert.assertEquals(mockedUserInfo.getXXX(), userInfo.getXXX());
            //few more assertions
        } catch (Exception e) {
            Assert.fail(" : " + e.getMessage());
        }
    }

}

When I execute this test case I get following exception from mockito.
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.
3. the parent of the mocked class is not public.
   It is a limitation of the mock engine.

My Queries :

*

*How to junit my class

*This exception is coming because getJdbcTemplate is final JdbcDaoSupport class. Is there any alternative for this approach?

I wrote my junit using post Spring jdbcTemplate unit testing
But, looks like it doesn't work.

A: You problem is with this line:
Mockito.when(((JdbcDaoSupport)dao.getTemplate())).thenReturn(jdbcTemplate);

You have dao annotated with @Autowired so it is not a mocked object. What you want to probably do is use SpringTestReflectionUtils to set your jdbcTemplate in the dao to your mocked object.


text:
Q: Another identity involving sums of (alternating) binomial coefficients. I have derived two different solutions to the same problem involving computing the expected time to find $k$ swaps when collecting coupons. However to me the two sums, although apparently numerically identical, look completely unrelated. Is there some elementary way of showing the following identity?  $$\sum_{s=1}^n(s+m)  \binom{n}s \sum_{i=0}^s(-1)^i\binom{s}i \left(\frac{s-i}n\right)^{s+m-1}\frac{s}n=n  + m - \sum_{k=1}^{n} k^{k-1} \binom{n}{k} \frac{(n-k)^{n+m-k}}{n^{n+m-1}} $$
This is defined for integers $n,m \geq 1$.
This is related to a possibly simpler previous question I asked.


text:
Q: Wiener-Hopf factorization of matrices Given a $2\times2$ matrix, which entries are functions in the complex plane $$\hat{A}(z)=\left(\begin{array}{cc}a(z)&b(z)\\c(z)&d(z)\end{array}\right)$$Where $a(z),b(z),c(z)$ and $d(z)$ are functions in the complex plane. I would like to obtain two new matrices, denoted as $\hat{\phi}_+(z)$ and $\hat{\phi}_-(z)$, such $\hat{A}(z)=\hat{\phi}_+(z)\hat{\phi}_-(z)$. The meaning of the subindexes is related to the discrete Fourier transform. If we take $\hat{\phi}_+(z)$
$$\int dz e^{i k z}\hat{\phi}_+(z)=0,\;\;\forall\;k<0$$
Similar definitions can be given for $\hat{\phi}_-(z)$ with $k>0$. It means that the Fourier transform of the two functions is only non-zero in a half complex plane.
As far as I know, this is called Wiener-Hopf factorization.
My questions are about the conditions that ensure the  existence of such a factorization, and how this factorization can be determined (references or examples may help at this point).
Thank you for any help!
Note: Suppose that the entries of $A(z)$ are continium and smooth, and the matrix is invertible a.e. ($\mbox{det}[\hat{A}(z)]\neq0,\forall z\in \mathbb{C}$) By the moment I don't care about pathological cases

A: Pointers to the literature on matrix-Wiener-Hopf factorization can be found in A brief historical perspective of the Wiener-Hopf technique:

Matrix Wiener-Hopf kernels are fundamentally distinct from their
  scalar counterparts in that there is no algorithmic approach to
  determining the factorisation of the transformed kernel. Exact
  factorisation can be achieved for matrices with certain special
  features: those that are upper (or lower) triangular in form; those
  that are of Khrapkov-Daniele, i.e. commutative, form; those whose
  elements comprise meromorphic functions; kernels with special
  singularity structure that allows the Wiener-Hopf equation to be
  recast into uncoupled Riemann-Hilbert problems and $N \times N$
  matrices with special algebraic or group structure.

More specifically, for the $2\times 2$ case, see for example Matrix Wiener-Hopf factorization (and this related note):

A method is described for effecting the explicit Wiener-Hopf
  factorisation of a class of $2\times 2$ matrices. The class is
  determined such that the factorisation problem can be reduced to a
  matrix Hilbert problem which involves an upper or lower triangular
  matrix. Then the matrix Hilbert problem can be further reduced to
  three scalar Hilbert problems on a half-line, which are solvable in
  the standard manner.

This explicit method works if
$$b\left[a-d\pm\sqrt{(a-d)^2+4bc}\right]^{-1}$$
can be expressed as a ratio of polynomials in $z$. It seems a completely general explicit construction does not exist, not even for $2\times 2$ matrices.


text:
Q: Assigning values in VHDL I am stuck in a problem.
I have like this type of binary code. (actually I have data in 10 rows, but here I am showing 3 rows only).
1000011100101000001111
1110000111101010000111
1000000000011110000010
and now i want to assign each row to output 1, output 2, output 3 (let's say).
Basically, I am reading this type of data from a text file and I want to assign each row to array type variable.
how could we do that in VHDL. Any suggestion. Thanks.

A: entity e is
port( output1 : out std_logic_vector(22 downto 0));
end entity

architecture rtl of e is
begin
  output1 <= "1000011100101000001111";
end architecture;

is that what you mean?

A: What you need is a std_logic_textio package or something similar.
http://www.vhdl.org/rassp/vhdl/models/standards/std_logic_textio.vhd
A good example is shown here on how to do this:
http://www.stefanvhdl.com/vhdl/html/file_read.html


text:
Q: Neo4j / Cypher - Conditional set/create/etc statement based on count (or any previous query statement) How do you conditionally do a SET (or anything else) based on the result of a previous line? So for example the query below (which doesn't work atm), where I'm trying to update something based on if the count is 1 (and not do it otherwise). Query doesn't like statements after THEN so that's where the error is occurring. I've tried also using WHERE clauses but no luck as of yet.
Is there any other way to accomplish what I'm trying to do below in a single query?
MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (p:Thing)-[:HAS_CHILD]->(n)
OPTIONAL MATCH (c)<-[:HAS_CHILD]-(p:Thing)
WITH c, p, n,
CASE count(c)
WHEN 1
THEN SET p.btogstate = 'closed'
DETACH DELETE n

Update
Tried the following based on a similar post but still no luck:
MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (p:Thing)-[:HAS_CHILD]->(n)
OPTIONAL MATCH (c)<-[:HAS_CHILD]-(p:Thing)
WITH c, p, n,
CASE WHEN count(c) = 1 then [1] else [] end as countOne
FOREACH (x in countOne | SET p.btogstate = 'closed'
DETACH DELETE n

Update 2 (final)
While cybersam's solution worked in a particular situation, the following was the only thing that ended up working for my particular situation for reasons that I still don't understand, so here it is for anyone that might run into similar weirdness. The main difference is that instead of using count to see if there was more than one child for the parent node, I just did another match to see if there was anything else that was a child of the parent node that wasn't the originally matched child (i.e. where n<>y). If there was not (i.e. y is null) then update the property, if there was (i.e. y is not null) then don't do anything other than delete n:
MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (p:Thing)-[:HAS_CHILD]->(n)
with p, n
OPTIONAL MATCH (p)-[:HAS_CHILD]->(y)
WHERE n<>y
WITH n, y, p,
CASE WHEN y IS NULL then [1] else [] end as countOne
FOREACH (x in countOne | SET p.btogstate = 'closed')
DETACH DELETE n;

A: Try this:
MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (p:Thing)-[:HAS_CHILD]->(n)
OPTIONAL MATCH (c)<-[:HAS_CHILD]-(p:Thing)
WITH c, p, n
FOREACH(x IN (CASE WHEN c IS NULL THEN [] else [1] END) |
  DETACH DELETE n
)

Based on this Mark Needham post (Neo4j: LOAD CSV – Handling conditionals).

A: This should work:
MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (c)<-[:HAS_CHILD]-(p:Thing)-[:HAS_CHILD]->(n)
WITH p, n,
  CASE WHEN COUNT(c) = 1 then [1] else [] end as countOne
FOREACH (x in countOne | SET p.btogstate = 'closed')
DETACH DELETE n;

Notice that, unlike your original query, the WITH clause does not include c by itself, as that would prevent the aggregation function COUNT from working as expected (in that case, the count would always have a value of 1 if the optional match found any matches).


text:
Q: Magento2 slick slider issue on page load I am applying slick slider on the home page at widget but on page load, it is not loading properly but after page load, ends it works fine

and when the page loads completely it looks like this

here is my code
<script type="text/javascript">

    require(['jquery', 'slick'], function($){
    jQuery(document).ready(function ($) {

           jQuery('#blog-post-silder').not('.slick-
   initialized').slick({
      dots: false,
      infinite: false,
      speed: 300,
      slidesToShow: 3.1,
      settings: "unslick",
      slidesToScroll: 1,
      responsive: [
        {
          breakpoint: 1024,
          settings: {
            slidesToShow: 3.1,
            slidesToScroll: 1,
            infinite: false,
            dots: false
          }
        },
         {
          breakpoint:767,
          settings: {
            slidesToShow: 3.2,
            slidesToScroll: 1,
             dots: false
          }
        },
        {
          breakpoint: 600,
          settings: {
            slidesToShow: 3.1,
            slidesToScroll: 1,
             dots: false
          }
        },
           {
          breakpoint: 320,
          settings: {
            slidesToShow: 2.1,
            slidesToScroll: 1,
             dots: false
          }
        },
        {
          breakpoint: 480,
          settings: {
            slidesToShow: 2.1,
            slidesToScroll: 1,
             dots: false
          }
        }
        // You can unslick at a given breakpoint now by adding:
        // settings: "unslick"
        // instead of a settings object
      ]
       });
       });
       });
    </script>
      <ol id="blog-post-silder" class="product-items <?= /* @noEscape
    */ $type ?>"  >

thanks a lot


text:
Q: How to change the US default dateformat input fields in React-bootstrap-daterangepicker I'm new to React and Javascript and have the following problem: I need to change the default US dateformat in my React-bootstrap-daterangepicker. I found some info about changing the locale object from the momentjs site, but not sure how exactly to implement it... I also tried adding a dateFormat="DD/MM/YYYY" (and format="DD/MM/YYYY") attribute to my DatePicker but with no success.
My React version is 15.4.0
Thanks in advance!

import React from 'react';
import { ControlLabel, FormGroup, HelpBlock } from 'react-bootstrap';
import DatePicker from "react-bootstrap-daterangepicker";
import moment from 'moment';

class DateRangePicker extends React.Component {

    componentWillMount() {
        const value = new Date().toISOString().replace("T", " ").replace("Z", "");
        const date = value;

        this.setState({
            value: date,
            startDate: moment(),
            endDate: moment()

        });

    }

    handleChange(e, datepicker) {
        this.setState({

            startDate: datepicker.startDate,
            endDate: datepicker.endDate,
            value: datepicker.startDate + " to " + datepicker.endDate
        });
        const label = datepicker.startDate + " to " + datepicker.endDate;

        const {startDate, endDate} = datepicker;
        this.props.onSelect(startDate, endDate)
    }

    render() {
        let start = moment(this.state.startDate).format("DD/MM/YYYY");
        let end = moment(this.state.endDate).format("DD/MM/YYYY");
        let dateRange = start + ' to ' + end;
        return (
            <fieldset className="form-group form-group--small pull-left">
                <legend className="hidden">Choose a date range</legend>
                <FormGroup>
                    <ControlLabel className="hidden" htmlFor="dateRange">
                        Date range:</ControlLabel>
                    <DatePicker
                        readOnly="false"
                        startDate={this.start}
                        endDate={this.end}
                        onApply={this
                            .handleChange
                            .bind(this)}
                        onChange={this
                            .handleChange
                            .bind(this)}>

                            <input type="text" id="dateRange" className="form-control" value={dateRange} />

                    </DatePicker>
                    <HelpBlock className="hidden">Help</HelpBlock>
                </FormGroup>

            </fieldset>

        );
    }
}

export default DateRangePicker;

A: According to the documentation, which refers to the original project, which in turn points to the probably official site, it seems you could pass to setState, along with startDate and the like, a locale sub-object such as locale: {format: 'DD-MM-YYYY'}, as illustrated in one of the examples.
Hope this helps!

A: I managed to solve my issue by initializing the locale const in the componentWillMount() method in my compoent i.e
    componentWillMount() {
    const value = new Date().toISOString();
    const date = value;
    const locale = locale;

    this.setState({
        value: date,
        locale: {
            'format': 'DD/MM/YYYY'
        },
        startDate: moment(),
        endDate: moment()

    });
   }

and then setting a locale attribute for the DatePicker tag:
 <DatePicker  locale={this.state.locale}

...


text:
Q: Classic Fantasy with characters from the real world I read this book about 6-8 years ago, and it was already slightly old at that point. The key parts were that the characters were all from Earth (America, if I remember correctly - one character internally monologues about remembering exactly how many steps it takes to get to a specific beach from his house, and while I don't remember the beach name, I remember thinking it was American) and woke up in a fantasy world, scattered about, and not remembering where they come from for quite a while.
Each abductee is wearing a bracelet with (what I remember as) polyhedral dice, although they aren't named that I think I inferred it from the description, and at some point they start using them as a form of magic. They find out that they were all abducted by a wizard so they go to find him. I can't remember what happens next, other than that eventually they find him and in a later book in the series (that I only saw the blurb of) they go back to his castle.
I think the book might be called "______ Keep", and am fairly certain the later book in the series is called "Return to ______ Keep".
I'd really appreciate it if someone who knew the title could tell me - it's like an unscratched itch at the moment, and I'd love to read it again!

A: Sounds like Quag Keep by Andre Norton and Return to Quag Keep by Andre Norton and Jean Rabe. From the review of Quag Keep at www.curledup.com:

The book starts with a brief glimpse into a modern world where people are playing role-playing games with the aid of miniatures. The players belong to different gaming groups, and most of them do not know each other. Quickly, the players are transported into the very fantasy world that they we playing in, Greyhawk.

The main point-of-view character, a swordsman called Milo Jagon, and his rarely seen alter-ego, Martin Jefferson, wakes up in a tavern sitting alone at his table. He notices on his wrist a bracelet which has different kinds of die on it. It is also warm to the touch. He does not remember how he got there or much of anything about his life so far. A berserker called Naile Fangtooth comes to him and reveals that he has a similar bracelet. Neither of them knows where they got it, but both of them have vague memories of another world and place.
Soon a mysterious figure gives them a summons from a powerful wizard. They have nobody else to turn to, so they go to see the wizard. During the short journey, they meet an elven ranger, Ingrge, who also wears a similar bracelet. At the wizard's place, they meet four other adventures with similar memory loss and with bracelets: the bard Wymarc, the cleric Deav Dyne, the lizardman Gulth, and one token woman: the Amazon battlemaid Yevele.
The wizard Hystaspes explains to them that he has seen that a mysterious power from outside their world and time threatens their world of Greyhawk. He also knows that each of the adventures is bound to one person from another place. Now the group has to battle the mysterious menace in order to save their world and to find out what has happened to them. The only person who can help them is a great Gold Dragon, Lichis, who at least used to serve Law. The group sets out to find the dragon and defeat their enemies.


text:
Q: Vb.net Passing values to constructor of Type T I have this code to get the default constructor:
Public Function f(ByVal t As System.Type) As Object
    Return t.GetConstructor(New System.Type() {}).Invoke(New Object() {})
End Function

I need to pass values to the Constructor as
Public Function f(ByVal t As System.Type) As Object
    Return t.GetConstructor(New System.Type() {someInteger,someString,etc.etc}).Invoke(New Object() {})
End Function

Also I have 3 classes of Type T, with all having different parametric constructor. It's important for me to have it generic as the Classes of type T might increase in future with less or more parameters.

A: Yes, it is possible.
However, you are putting the values in the Type(). You need to specify the types of the constructor, so it knows which constructor you want to actually resolve, then pass the actual values you wish in Invoke:
Public Function f(ByVal t As System.Type) As Object
    Return t.GetConstructor(New System.Type() {GetType(Integer),GetType(String)}).Invoke(New Object() {someInteger, someString})
End Function


text:
Q: What functionality to expose in a database abstraction layer? I'm trying to design a simple way of abstracting away data persistence behind an interface, but I'm having a hard time figuring out how much fine grained control should be exposed to higher layers.
Limit, Filter, Order, etc.
Defining an interface for a dumb data repository is all fine and dandy for the basic CRUD operations, but what about all the other common database capabilities such as result filtering, limiting, map/reduce and other transformative or conditional operations? Do these types of operations violate the single responsibility principle in the sense that a persistence layer should just be a dumb retrieve/persist black box -and consequently, would this functionality be better implemented on the calling code side (i.e, in a service layer, or even client side)?
Client side transformations
Although it would greatly simplify the persistence layer, personally, I feel that it would be quite wasteful to perform these operations client side. For example, regardless of whether a user queries for a collection of 10 resources or 1000, the database would have to return the entire data set incurring bandwidth and caching costs, among other things. Also many of these queries are probably heavily optimized natively, and this would throw all of that out the window.
A smart database abstraction
On the other hand, if I were to expose this database functionality in the persistence layer, it would greatly increase the complexity of the interface and it would probably just end up looking like a 1:1 wrapper of the database driver (which is handy for mock testing purposes I suppose, but kind of defeats the purpose of writing the abstraction in the first place).
My question is: is there a general rule of thumb when designing a database abstraction layer for what functionality to expose and what to keep hidden?

A: Database systems can implement very different approaches.  Just compare SQL vs. NoSQL.  And for the latter compare key-value stores with graph databases. So you'll not find a silver bullet that will offer a single API with all the benefits of these databases.  So you'll have to narrow down your scope.
Considering the limits, filtering, ordering, many of those are related to the queries of the database. So I think that you definitively need to take care of this in your API. If you don't, you might suffer. Not because of extra calls between client and API,  but because if you force doing it on client side, you will force your app to solicit the database server much more than needed. It's one variant of the traditional issue of client vs. server side processing.
But unless you want to write your own general purpose API,  I'd strongly advise to design your persistence layer starting from your application architecture, and especially how your architecture will handle the mapping between your objects in memory and the data objects on the database (e.g. object-relational mapping).
The problem has some similarities with serializing/deserializing challenges: i.e. how to map relations between objects, composition of objects, containers of objects, etc...  Once you have the clear picture, you should design your database layer with the operation needed to support the primitives of your object mapping.
One good start would be to consider the proxy design pattern for the mapping in-memory proxies that control database objects.  The approach I propose you here is very different from developing a universal database wrapper.  But it has the advantage of allowing you to get the best from the underlying database architecture, i.e. take benefit of graph and document databases.


text:
Q: How to limit Gmail API and MSGraph email API to specific email subjects I've built a CRM webapp with Django for a specific lead heavy industry. It's working for both gmail and outlook users.  Through MsGraph and Google API, the user is able to give authorization via Oath2 to the app to access their inboxes. The app then grabs and parses emails from various sources.
Each lead source always sends the lead emails with same subject. This makes the lead emails easy to identify from the users inbox. Unfortunately, the subject of EVERY email that comes in has to be searched to find the desired lead emails. Unfortunately, Identifying by sender isn't an option, and wouldn't change the issue.  Each email would still have to be searched.
I have a couple of colleagues beta testing right now.
As I think about taking on new users that may be outside of my colleagues, I am starting to think the webapps unrestricted access to a user's inbox via the available scopes isn't the best approach for trying to attract new users.   I would be suspicious of any 3rd party program wanting to access all of my emails, even if just searching for specific emails.
I use Google's watch() and MsGraphs subscriptions to do this while the user is offline. It doesn't appear that Google or Microsoft allow for any kind of message change filter based on what's in the subject line.
Are there any methods that I have not been able to find in either Google API or MsGraph documentation that would limit access to only the emails that meet the subject search criteria?
Would this even pass either of their security checks to get 'Published Status.'

A: Reading through the Google docs, it looks like you can set authorization scopes that limit access to just labels and basic settings. This should allow you to filter messages by subject and apply labels to those filters.
Of course, the subject filtering doesn't have anything to do with authorization. But fine tuning the authorization is better than allowing write access to an entire mailbox.
I would say in general, the more open the permissions are, the less likely you are to get approved. Google wants you to only have access to what you need to achieve the product's purpose, nothing more.
https://developers.google.com/gmail/api/auth/scopes
There definitely isn't a way to set custom permissions based on subject. In fact, I don't know many APIs in general that allow you to define custom permissions that granularly.
That said, it doesn't seem like you even need read access to message headers, let alone message body content, to achieve what you want to do in Gmail.
I assume Microsoft has similar scoping, but I'm not sure.


text:
Q: String to Array in Ruby I need my string: "---\n- aaaadddhh ddddggg\n- bbbdddddf ff ddd\n- cccf\n" to convert to an array in Ruby
This is what I want it to be:
["aaaadddhh ddddggg", "bbbdddddf ff ddd", "cccf"]

A: That's YAML. Use YAML.load(str) to unmarshal it from a string into an object.
> require 'yaml'
 => true
> YAML.load "---\n- aaaadddhh ddddggg\n- bbbdddddf ff ddd\n- cccf\n"
 => ["aaaadddhh ddddggg", "bbbdddddf ff ddd", "cccf"]

Be aware that there are security risks in unmarshalling arbitrary YAML, so be sure that the source you are passing into it is trusted.


text:
Q: Obtaining a probability distribution after a change of variables. I have two random variables $x_1,x_2$ whose distributions are unknown. I define $y_1=g(x_1,x_2)$ and $y_2=f(x_1,x_2)$ where $f(\cdot)$ and $g(\cdot)$ are known and the probability distributions $p(y_1)$ and $p(y_2)$ are known. How could I obtain the joint probability?
One proposed:
$$
P(x_1,x_2)=\int\int P(y_2)P(y_1)\delta(y_2 -f(x_1,x_2))\;\delta(y_1 -g(x_1,x_2))dy_1dy_2
$$
However I am unable to derive the formula nor the reason behind it.
Thank you very much for your help! Any idea highly appreciated.


text:
Q: Grails: URL mapping changing the controller name This must be a simple config in URLMappings.groovy, but I keep getting a 404.
Basically, I want to change the name of a controller. For example, we have controller name Content_pdfs_data_etcController.groovy, awful as a URL, I tried
static mappings = {
    "/mdata/$action?"(controller: "content_pdfs_data_etc", action: 'index')

    "/$controller/$action?/$id?"{
        constraints {
            // apply constraints here
        }
    }
    "/"(view:"/index")
    "/"(controller:"home")
    "500"(view:'/error')
}

All actions in the controller should get redirected as well (example):
/mdata/show    ->   content_pdfs_data_etc/show
/mdata/update  ->   content_pdsf_data_etc/update
Thanks.

A: Try removing the hard-coded action, which should allow the $action variable to do its mapping magic:
"/mdata/$action?"(controller: "content_pdfs_data_etc")

A: Thanks for the answer Andrew. I actually figured out that swapping the order of the mapping with the default fixed the issue. I ended up with:
"/$controller/$action?/$id?"{
    constraints {
    // apply constraints here
    }
}
"/mdata/$action?/$id?" (controller: "content_pdfs_data_etc")


text:
Q: Bxslider not working properly with jQuery 2.1.1 I use bxSlider on my page and at first when I open a page it doesn't work, but then sometimes when I refresh it starts working. What could be the problem?
custom.js
$(document).ready(function(){
    $('.news').bxSlider(
        {
            mode: 'vertical',
            minSlides: 4,
            maxSlides: 10,
            ticker: true,
            speed: 40000
        }
    );
});

My Page

...

...

...

A: use latest file bxslider.min.js version v4.2.5
https://jsfiddle.net/8rxobr6j/2/


text:
Q: Problems with jest and Vuetify regarding aria-owns id in snapshot Im having problem with jest-test with vuetify. If Im running a testcase by it own I get one value for aria-owns. Example:

Im using webstorm so I just update the snapshot directly. BUT when Im running all testcases with npm run test. The testcase received this HTML instead:

As you see the id for the aria-owns has been changed. And I dont know how to fix this. I tried several clear and reset methods for jest, for example: jest.clearAllMocks() and jest.resetModules(), and so on but nothing works.
Please help.

A: Vuetify 2 uses this._uid which is internal to vue and can't be reset. It is incremented for each component instance which is why you get a different value if you run a different number of tests.
Vuetify 3 has a custom getUid function which also increments but can be imported and reset before each test:
import { getUid } from 'vuetify/lib/util'

beforeEach(() => {
  getUid.reset()
})