text:
Q: How to change this.variable in jquery function? How to change this.variable of class AuthDirective in jquery function?
maybe stupid question but, I need to use Jquery events and to change/to work with angular variables.

import { Component, Directive, OnInit } from '@angular/core';
import { AppGlobal                    } from '../../../app.global';
declare var $:any;

@Component({
  selector    : 'authorization',
  templateUrl : './auth.directive.html'
})
export class AuthDirective {
  isCaptcha : boolean = false;
  constructor(
    public  app : AppGlobal
  ) {
  }
  ngOnInit() {
    $('.sign-up-label').on('show.bs.modal', function (e) {
      this.isCaptcha = true; // NOT IN THIS CONTEXT, IN THAT CONTEXT
    })
  }
}

{{isCaptcha}} is always false

<div class="form-group ta-web-right mt-3" *ngIf="isCaptcha">
  <re-captcha (resolved)="resolved($event)"></re-captcha>
</div>

Help please.

A: You can preserve value of this from outer context by assigning it to variable:
ngOnInit() {
    var self = this;
    $('.sign-up-label').on('show.bs.modal', function (e) {
      self.isCaptcha = true;
    })

}

A: store the outer context like this let self = this; and then it doesn't conflict with the local context.
replace your function like this
ngOnChanges(changes: SimpleChange) {
    let self = this;
    $('.sign-up-label').on('show.bs.modal', function (e) {
      self.isCaptcha = true; // NOT IN THIS CONTEXT, IN THAT CONTEXT
    })
  }


text:
Q: Simple $G$-module where $G$ is commutative Suppose that $G$ is a commutative group with $|G|<\infty$. Show that any irreducible finite $G$-module over $\mathbb{C}$ must be one dimensional.

*

*A question first: Is it possible that this is not one dimensional? Simple example is really appreciated. Thanks.

*Attempt:
Let $V$ be the irreducible $G$-module. Hence, $V$ must be nonzero by definition, and $G$ acts on $V$ with linearity property. For every $g\in G$, consider the map $f_g:V\rightarrow V$ given by $f_g(v)=g.v$ (the action of $g$ on $v$). This map cannot be zero, otherwise for some nonzero $v\in V$, $g.v=0$ implies $v=(g^{-1}g).v=0$, a contradiction.
We show that $f_g$ is a $G$-module map (for using Schur's Lemma). Let $x\in G$. We have $f_g(x.v)=g.(x.v)=(gx).v=(xg).v$ by commutativity of $G$. Hence, $f_g(x.v)=x.(g.v)=x.f_g(v)$.
Therefore, by Schur's Lemma, $f_g=k_gI$ (Wait, do we show $f_g$ as a linear map too, or Schur's Lemma actually works for any auto $G$-module map?) for some $k_g\in\mathbb{C}$ and $I$ is the identity map on $V$. Recall that our $g$ is arbitrary.
Now, consider the subspace $H:=span(v)$ for some nonzero $v\in V$. We show that $V=H$ by showing that $H$ is a $G$-submodule of $V$ and use the irreducibility of $V$ to conclude.
To do that, let $g\in G$ and $mv\in H$, where $m\in\mathbb{C}$. We see that $g.mv=m(g.v)=mf_g(v)=m(k_g v)=(mk_g)v\in H$. Thus, $H=span(v)$ is a $G$-submodule of $V$.
Hopefully there is any correction or improvement (too much/too little).
Thank you very much.
EDIT: I should have said that I have searched and found answers in MSE before posting this, but I would like to try my own solution and would like to know whether mistakes exist as I haven't really understood other concepts well. Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I patch a specific subdocument in an array I have at collection of documents with this structure
{"_id":"mrc",
  "Name":"MRC Odense",
  "events":[
  {"date":"01/12/2020","title":"Løb","uuid":"4ee494ac-e73c-4945-ac19-25c9d6882707"},
  {,"date":"01/12/2020","title":"Løb","uuid":"925a99d3-8d77-425a-ad54-a893d5c14d72"}
  ]
}

I get at patch request with the uuid of an event. How can I update the specific event?
def patch(self,event_uuid=None):
    r = request.get_json(force=True)   # r={"title"="new title"}
    doc=self.col.find_one({"events.uuid":id})
    ....??

A: for key in r:
  self.col.update_one({"events.uuid":id }, {'$set' : {  "events.$."+key : r[key]}} )


text:
Q: Kubernetes version upgraded, but kubectl showing different versions I just upgraded kubernetes cluster, but kubectl is very inconsistent in showing me the version. How can I verify this. Any source of truth?
[iahmad@web-prod-ijaz001 k8s-test]$ kubectl  version
Client Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.3", GitCommit:"5e53fd6bc17c0dec8434817e69b04a25d8ae0ff0", GitTreeState:"clean", BuildDate:"2019-06-06T01:44:30Z", GoVersion:"go1.12.5", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"14", GitVersion:"v1.14.3", GitCommit:"5e53fd6bc17c0dec8434817e69b04a25d8ae0ff0", GitTreeState:"clean", BuildDate:"2019-06-06T01:36:19Z", GoVersion:"go1.12.5", Compiler:"gc", Platform:"linux/amd64"}

[iahmad@web-prod-ijaz001 k8s-test]$ kubectl  get nodes
NAME        STATUS   ROLES    AGE    VERSION
wp-np3-0b   Ready    worker   55d    v1.14.1
wp-np3-0f   Ready    worker   55d    v1.14.1
wp-np3-45   Ready    master   104d   v1.13.5
wp-np3-46   Ready    worker   104d   v1.13.5
wp-np3-47   Ready    worker   104d   v1.13.5
wp-np3-48   Ready    worker   43d    v1.14.1
wp-np3-49   Ready    worker   95d    v1.13.5
wp-np3-76   Ready    worker   55d    v1.14.1
[iahmad@web-prod-ijaz001 k8s-test]$

A: IIRC: kubectl version is telling you what version the APIServer is at (1.14.3). kubectl get nodes is telling you what version the kubelet is on those nodes.


text:
Q: Can i parse a binary XML file ( in res/xml ) with a SAX parser To clarify my question :-)
I want to have the best of both worlds.

*

*The speed of having a compressed xml
file

*The speed of the SAX parser (
over a XmlResourceParser that is
normally used with binary files )

Most important question is: Can this be done?
Closest i came to the solution is.

*

*OR open a raw resource ( not binary
formatted )

*OR parse a binary xml file with a XmlResourceParser

I hope someone can help me get a bit further in this situation.
Edit: link to reflect SAX-parser speed

A: SAX parser is not more efficient than XmlResourceParser for XML in raw resource.  Just use XmlResourceParser.

A: You can place your xml file assets folder and you can use Sax parser
InputStream xmlFileStram = getAssets().open(filePath); // this gives the file in your asset folder
XmlHandler xmlHandler = new XmlHandler(activity);
SAXParserFactory.newInstance().newSAXParser().parse(xmlFileStram, xmlHandler);


text:
Q: Android image quality dependent on network speed When connected to 4G ATT network and downloading an image from my server using InputStream or BufferedInputStream, image size and quality is downgraded. When downloading the same picture from a google server, image quality is flawless. When connected to Wifi, T-Mobile or Verizon networks image quality is fine for both scenarios.
Succesful scenario shows 137 buffered read cycles of 1.3kb each. (174kb image)
urlConnection.getContentLength() returns the appropriate file size and urlConnection.getInputStream().available() > 0.
Failed scenario shows 5 buffered reads varying from 1.3 to 4.1kb (13kb image) with urlConnection.getContentLength() returning -1 and urlConnection.getInputStream().available() returning 0. The connection header for this scenario shows Transfer-Encoding=[chunked]. Ive tried reading the input stream as chunked (https://stackoverflow.com/a/16646479/2333242) but loss of quality is still there.
At first I though the culprit was ATT which might be doing some throttling, but then I tethered this ATT connection to another identical phone and image quality is flawless. Using the Android image loader (http://developer.android.com/training/displaying-bitmaps/index.html) and hardcoding the urls of images located in my server shows the same loss of quality. I have played around with connection and read timeouts but the results are the same.
Any ideas what might be going on?

A: Wrong APN settings on AT&T phone was causing the data to be chunked. Always use default carrier settings.


text:
Q: KSH Split String Issues I have a string in a variable Var.
And the value looks like this:
Var="Key1:Val1~Key2:Val2~"
I just simply need this split by "~" and assigned to an array in KSH only
When I try Var2=$(echo $Var | sed $'s/~/\\n/g')
and check the size of Var2 array as follows:
ArrSize=${#Var2[@]}
I always get 1. I would have imagined that would be 2. Please Help

A: Assuming you want to use the x=( list of array items ) method of populating the array then you need to wrap the right side of the assignment in a pair of parens, eg:
$ Var2=( $( echo $Var | sed $'s/~/\\n/g' ) )

$ typeset -p Var2
typeset -a Var2=(Key1:Val1 Key2:Val2)

$ echo "${#Var2[@]}"
2

Other options that accomplish the same thing but reduce the overhead of subprocess calls:
here string:
$ Var2=( $(sed 's/~/ /g' <<< "${Var}") )

$ typeset -p Var2
typeset -a Var2=(Key1:Val1 Key2:Val2)

$ echo "${#Var2[@]}"
2

parameter substitution:
$ Var2=( ${Var//\~/ } )

$ typeset -p Var2
typeset -a Var2=(Key1:Val1 Key2:Val2)

$ echo "${#Var2[@]}"
2

NOTE: while ${var//~/ } works in ksh, other shells (eg, bash) require the ~ to be escaped (ie, \~); ksh appears to work with both - ~ and \~ = so I've updated the answer to include the escape


text:
Q: Передать определенные значения массива через ajax? Есть 2 кнопки по сабмиту на которые должны меняться статусы заявки по аяксу:
 <form>

<button onclick="send_N()" class="btn btn-primary btn__sign" >Отправить замечания</button>
<button onclick="send_Y()" class="btn btn-primary btn__sign--else" >Замечаний нет</button>
</form>

в обработчике :
require($_SERVER['DOCUMENT_ROOT'].'/bitrix/modules/main/include/prolog_before.php');
if ( $_POST['id'] > 0 ) {
    echo 'succes';
    CIBlockElement::SetPropertyValuesEx($arValues['EXTERNAL_ID'], false, array('STATUS' => 200)); // записываем в БД новый статус

}

< script type = "text/javascript" >
  function send_Y() {

    $.ajax({
      type: "POST",
      url: "/updstatus.php",
      //data: "name=John&location=Boston",

      success: function(data) {
        //alert("Изменение статуса 201 " + data);

      }

    });
    return false;
  }

как правильно передать конкретные значения массива ?
$arValues['EXTERNAL_ID']  // id текущей заявки
$arValues['STATUS']['ID'])  // Текущий статус (меняется)

Хватит ли этих данных чтобы обработчик сработал?
предыдущий мой вопрос на эту тему
Похожий вопрос

A: Ну, раз вы уже пишете вызов функции инлайново, то можете сделать что-то типо
<form>
   <input name="deal_id" type="hidden" value="<?=$arValues['EXTERNAL_ID']?>">
   <input name="status" type="hidden" value="<?=$arValues['STATUS']['ID']?>">
   <button onclick="send_Y(this); return false;" class="btn btn-primary btn__sign--else" >Замечаний нет</button>
</form>

js код
function send_Y(e) {
let data = $(e).parents('form').serialize();
$.ajax({
    type: "POST",
    url: "/updstatus.php",
    data,
    success: function(data) {
        if(data.result =='success'){
            console.log('lalal');
        }
    }
});
return false;
}

/updstatus.php
if(!empty($_REQUEST['deal_id'])){
CModule::IncludeModule('iblock');
CIBlockElement::SetPropertyValuesEx($_REQUEST['deal_id'], false, array('STATUS' => $_REQUEST['status']));
$APPLICATION->RestartBuffer();
    header('Content-Type: application/json');
    echo json_encode(array('result'=>'success'));
die();
}


text:
Q: AndroidStudio: JaCoCo code coverage report's 0% for coverage I've recently brought code coverage into my project.  It creates a report, which I can view, and it seems to be working great.
The only problem is it is missing my tests - I don't have GREAT code coverage right now, but it reports 0% coverage for all classes and other files.
I can see the tests being run, and can see them passing, but they aren't being counted.
My configuration is:
android {
    compileSdkVersion 18
    buildToolsVersion '21.1.1'
    ...
     debug {
            minifyEnabled false
            testCoverageEnabled = true
        }
}

A: This might be related to this issue:
https://code.google.com/p/android/issues/detail?id=170607

A: It's working (again) with
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'


text:
Q: Remove Spacing between li How can I remove spacing between the li found here?
http://blog.raveis.com/badge/b.html
Confused on how to do this and I don't want to use negative margins. any help would be greatly appreciated.

A: Try this.
ul { font-size: 0; }

A: Make your li tags display:block; and float:left; (instead of display:inline;)

A: This is rediculously late in the piece but I had the same problem today.
I fixed it by laying out my HTML like so, thereby removing any space between the list it:

  list-item 1

  list-item 2

  list-item 3

Example on Code Pen

A: Do you want using list center, you can using:
 ul { text-align: center; }
 li { margin-right: -4px; }

How on this link

A: Surprised that no one mentioned line-height on the ul element. It's possible I didn't get the full question because the original link is now broken, but generally, line-height might be the way to go


text:
Q: how to recover files from hard disk, missing partition and hard disk check (horror movie described by an informatic incompetent) i have a really big problem with a pc (xp) of a friend whose hard drive is detected both by bios and setup, but when going on lubuntu with a live cd it doesn't show off neither any partition from the sata disk, just ram stuff.
I'm pretty sure there was as i could access the files before, but when i turned the pc off and on again it kind of started deleting the system files of windows xp trying to correct the errors and now ubuntu does not even find the partition neither the disk.
I'd like to know what happened and how to recover important data from the drive
http://imgur.com/a/rLrPD
http://imgur.com/a/dXn6l
as you can see here without the live the pc won't do anything usefull, the stats tell that there is Sata2, the Disks and gParted and df cannot find the partition
To explain myself better, in fig 1 you can see SATA2 IDE hard disk that is a 500 Gb hard disk.
In fig 2 you can see that this disk can't be seen with the commands or programms i know that should make you see it.
I may be ignorant in the subject so forgive me in case of confusion or such
EDIT: i've opened the pc, cleaned all and checked the connections, now the folder of the 500 GB is back (don't know if it's correlated because even before i could access) but as folders of user it tells me it is a corrupted file. What the hell is going on? Help me understand that machine please
EDIT2: disappeared again, so i'm sure the thing is going, the Disk option told me its status and that was at 40°C, could not open it, neither it let me use gParted, i'm a lot more confused now, please someone may tell me what is going on?


text:
Q: Best practices to support white-labeling in C# winforms application I've developed an application that helps users to play casino games "better", based on statistical calculations.
It's an external application that sniffs network, understands certain casino room protocols(some web based, some native application) and gives real time advices to user.
Recently I was contacted by different casino room operators that want to license the software from me, customize the graphics/strings/feature set and give it to their users under their brand name.
So I'm going to have N different installs for N different casinos, with different graphics for each, different strings, different feature set enabled etc.
What are best practices to handle such requirements in c# winforms application, should I have different resource files for each vendor ? Is there something built in .net framework to handle such scenarios? Are there 3rd party software that can help me to manage this ?
Please be as verbose as possible, and thanks in advance!

A: If this was an asp.net application I'd suggest using themes.  They are not as well supported in form applications but there is good theme support in WPF.  Check out http://wpfthemes.codeplex.com/

A: This should be straightforward because winforms is pretty "battleship grey" so once you've peeled off all decoration it'll be pretty plain and ready to start building up again.
Essentially:

*

*Remove any and all references in the code/forms to product name/company/customer.

*Start adding in specific "branding" items in the form of images and text etc.

Specifically:

*

*Make sure the code has no reference to the product name/company/customer in namespaces etc.

*Have all strings loaded from resource files (this'll help with localisation anyway).

*If you want some "obvious branding" then have an image file loaded form disk or resources and displayed in a picturebox.

You can then have the same code built multiple times using a build tool, each time configuring the build with different resources.


text:
Q: Do I need re-add packages after upgrade Julia I upgrade Julia from v1.1 to v1.3 on win10, but the packages miss in new version.
In v1.1
$ julia_1.1
               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.1.0 (2019-01-21)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

(v1.1) pkg> status
    Status `C:\Users\User\.julia\environments\v1.1\Project.toml`
  [c52e3926] Atom v0.11.3
  [4c0ca9eb] Gtk v0.18.0
  [f67ccb44] HDF5 v0.12.4
  [4138dd39] JLD v0.9.1
  [e5e0dc1b] Juno v0.7.2
  [23992714] MAT v0.6.0
  [91a5bcdd] Plots v0.26.3
  [b8865327] UnicodePlots v1.1.0
  [8f399da3] Libdl

But these packages does not show in v1.3
$ julia
               _
   _       _ _(_)_     |  Documentation: https://docs.julialang.org
  (_)     | (_) (_)    |
   _ _   _| |_  __ _   |  Type "?" for help, "]?" for Pkg help.
  | | | | | | |/ _` |  |
  | | |_| | | | (_| |  |  Version 1.3.0 (2019-11-26)
 _/ |\__'_|_|_|\__'_|  |  Official https://julialang.org/ release
|__/                   |

(v1.3) pkg> status
    Status `C:\Users\User\.julia\environments\v1.3\Project.toml`
  [c52e3926] Atom v0.11.3
  [67c07d97] Automa v0.8.0
  [e5e0dc1b] Juno v0.7.2

I tried using update but still not show.
And I make sure DEPOT_PATH has same folder ("C:\\Users\\User\\.julia") and all added package in there.
# (in v1.3)
julia> DEPOT_PATH
3-element Array{String,1}:
 "C:\\Users\\User\\.julia"
 "D:\\app\\Julia\\1.3.0\\local\\share\\julia"
 "D:\\app\\Julia\\1.3.0\\share\\julia"

How do I resolve it? And in I memory, it will not happen in Linux, is it correct?
(I use different version in docker with same volume.)

A: Each minor and major Julia version (MAJOR.MINOR.PATCH) uses its own environment named vMAJOR.MINOR. For example, for Julia 1.3.0 the environment is named v1.3 as you can see indicated in the Pkg REPL mode in parentheses before the pkg>.
When you updated from 1.1.x to 1.3.0 you hence switch from environment v1.1 to v1.3, which doesn't contain any packages by default. This happens on every OS.
How to we carry over packages from, say, v1.1 to v1.3?
The environments are reflected in folders in .julia/enironments. The two files Manifest.toml and Project.toml in those folders represent the respective environment. You can simply create a copy of the folder v1.1 and name it v1.3. Then, you fire up you Julia 1.3 REPL and, to be safe, you execute ] instantiate which will make sure that everything is installed properly. That's it.
For more information on environments see here and here.

A: When you write status you get a path printed. You can copy the folder printed on 1.1 to the one printed in 1.3 (the folder just contains two text files).

A: No.
For upgrading between minor versions (and should also be true between major version, eg. 1.x->2.y) you don't need to redownload all packages, just create a new folder v1.x under [JULIA_INSTALL_DIR]/environments and copy there the two files Project.toml and Manifest.toml from the folder from which you want the same packages (e.g. v1.(x-1)).
For example, to upgrade from Julia 1.4 to Julia 1.5 in Linux, after you installed the new binaries, just type in a terminal:
$ cd ~/.julia/environments/
$ mkdir v1.5
$ cp v1.4/Project.toml v1.5/
$ cp v1.4/Manifest.toml v1.5/

When you then lunch julia and you will use a packege (using xxx) you will then notice that julia will "just" pre-recompile the package for that specific Julia version (and all its dependencies, so it may take a while) but it doesn't need to re-download the package.


text:
Q: Change submit button text after form submit <script src="http://code.jquery.com/jquery-1.11.1.js"></script>

<script>
$(document).ready(function () {
    $("#submit").click(function(event){
        $('#submit').val('Processing …');
        $('SubmitForm').submit();
    });
});
</script>
<form  id="SubmitForm" action="/scripts/t.php" method="POST" enctype="multipart/form-data" accept-charset="utf-8" data-abide >
 <input  type="submit" value="Submit"  id='submit'>

</form>

The following code works in chrome .But it doesn't work in Safari .
As in when the page is getting submitted the new text is shown in chrome but not in safari.there is no error. The form gets submitted but the text change is not seen .
Can you please guide me.
~

A: Use below code

<script src="http://code.jquery.com/jquery-1.11.1.js"></script>

<script>
$(document).ready(function () {
    $("#submit").click(function(event){
        $('#submit').val('Processing …');
        $('SubmitForm').submit();
    });
  $('form').submit(function(event){
       alert("form submitted");
       $('#submit').val('submitted');
    });
});
</script>
<form  id="SubmitForm" action="/scripts/t.php" method="POST" enctype="multipart/form-data" accept-charset="utf-8" data-abide >
 <input  type="submit" value="Submit"  id='submit'>

</form>

A: You can simply modify your #submit button value under the form #SubmitForm .submit() event:

$('#SubmitForm').submit((e) => {
    e.preventDefault();
    $('#submit').attr('value', 'Processing...');
});
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>

<form  id="SubmitForm" action="/scripts/t.php" method="POST" enctype="multipart/form-data" accept-charset="utf-8" data-abide >
   <input  type="submit" value="Submit"  id='submit'>
</form>

A: Please use

$('#submit').attr('value', 'new value');


text:
Q: Solution to the heat equation with mixed boundary conditions and step function. PDE with the given intial and boundary conditions
$\gamma \frac{\partial^{2}p}{\partial x^{2}}=\frac{\partial p}{\partial t}$
Initial condition: $p(x,t=0)=0$
Outer Boundary Condition: $p(x\rightarrow\infty,t)=0$
Inner Boundary Condition: $\left.\frac{\partial p}{\partial x}\right|_{x=0}=c\left.\frac{\partial p}{\partial t}\right|_{x=0}+\left(\alpha b\left.\frac{\partial p}{\partial t}\right|_{x=0}-t^{-\alpha}\right)\left(1-\theta\left(t-t_{i}\right)\right)$
Where $\theta$ is the unit step function
I am only interested in the solution at the inner boundary. i.e.
$p(x=0,t>0)=?$
Other information:
$0\leq\alpha\leq0.5$
$\gamma>0$
$t>0$
$c\geq0$
$b\geq0$
My Skill level:
I have solved this equation for simplified cases using Laplace transforms for $t<t_i$. However I do not know how to proceed when $t>t_i$
Any help is greatly appreciated!
I have also checked the solution numerically using COMSOL for both $t<t_i$ and $t>t_i$

A: Hint:
Of course use separation of variables:
Let $p(x,t)=X(x)T(t)$ ,
Then $\gamma X''(x)T(t)=X(x)T'(t)$
$\dfrac{T'(t)}{\gamma T(t)}=\dfrac{X''(x)}{X(x)}=-s^2$
$\begin{cases}\dfrac{T'(t)}{T(t)}=-\gamma s^2\\X''(x)+s^2X(x)=0\end{cases}$
$\begin{cases}T(t)=c_3(s)e^{-\gamma ts^2}\\X(x)=\begin{cases}c_1(s)\sin xs+c_2(s)\cos xs&\text{when}~s\neq0\\c_1x+c_2&\text{when}~s=0\end{cases}\end{cases}$
$\therefore p(x,t)=\int_0^\infty C_1(s)e^{-\gamma ts^2}\sin xs~ds+\int_0^\infty C_2(s)e^{-\gamma ts^2}\cos xs~ds$
$\left.\dfrac{\partial p}{\partial x}\right|_{x=0}=c\left.\dfrac{\partial p}{\partial t}\right|_{x=0}$ when $t\geq t_i$ :
$\int_0^\infty sC_1(s)e^{-\gamma ts^2}~ds=-c\gamma\int_0^\infty s^2C_2(s)e^{-\gamma ts^2}~ds$
$\int_0^\infty C_1(s)e^{-\gamma ts^2}~ds=-\int_0^\infty c\gamma sC_2(s)e^{-\gamma ts^2}~ds$
$C_1(s)=-c\gamma sC_2(s)$
$\therefore p(x,t)=-\int_0^\infty c\gamma sC_2(s)e^{-\gamma ts^2}\sin xs~ds+\int_0^\infty C_2(s)e^{-\gamma ts^2}\cos xs~ds=\int_0^\infty C_2(s)e^{-\gamma ts^2}(\cos xs-c\gamma s\sin xs)~ds~\text{when}~t\geq t_i$
$p(x,0)=0$ :
$\int_0^\infty C_2(s)(\cos xs-c\gamma s\sin xs)~ds=0$
$C_2(s)=0$
$\therefore p(x,t)=0$ when $t\geq t_i$
$\left.\dfrac{\partial p}{\partial x}\right|_{x=0}=(c+\alpha b)\left.\dfrac{\partial p}{\partial t}\right|_{x=0}-t^{-\alpha}$ when $0<t<t_i$ :
$\int_0^\infty sC_1(s)e^{-\gamma ts^2}~ds=-(c+\alpha b)\gamma\int_0^\infty s^2C_2(s)e^{-\gamma ts^2}~ds-t^{-\alpha}$
$\int_0^\infty(sC_1(s)+(c+\alpha b)\gamma s^2C_2(s))e^{-\gamma ts^2}~ds=-t^{-\alpha}$
$sC_1(s)+(c+\alpha b)\gamma s^2C_2(s)=-\dfrac{2\gamma^\alpha s^{2\alpha-1}}{\Gamma(\alpha)}$ (according to http://en.wikipedia.org/wiki/Gaussian_integral#Integrals_of_similar_form)
$C_1(s)=-(c+\alpha b)\gamma sC_2(s)-\dfrac{2\gamma^\alpha s^{2\alpha-2}}{\Gamma(\alpha)}$
$\therefore p(x,t)=\int_0^\infty C_2(s)e^{-\gamma ts^2}(\cos xs-(c+\alpha b)\gamma s\sin xs)~ds-\dfrac{2\gamma^\alpha}{\Gamma(\alpha)}\int_0^\infty s^{2\alpha-2}e^{-\gamma ts^2}\sin xs~ds$
$p(x,0)=0$ :
$\int_0^\infty C_2(s)(\cos xs-(c+\alpha b)\gamma s\sin xs)~ds=\dfrac{2\gamma^\alpha}{\Gamma(\alpha)}\int_0^\infty s^{2\alpha-2}\sin xs~ds$


text:
Q: Java, exception handling and closing streams with try, finally I just wanted to see if there was a better way I should be handling this. My understanding of streams is that as long as you close a stream, any streams encapsulated within it will be closed which is why I only close TarArchiveOutputStream in finally. If I get FileNotFound on the rawDir or archiveDir I want to log it, otherwise anything else I want to throw.
public static void createTarGzOfDirectory(File rawDir, File archiveFile) throws IOException {
    FileOutputStream fOut = null;
    BufferedOutputStream bOut = null;
    GzipCompressorOutputStream gzOut = null;
    TarArchiveOutputStream tOut = null;
    try {
        fOut = new FileOutputStream(archiveFile);
        bOut = new BufferedOutputStream(fOut);
        gzOut = new GzipCompressorOutputStream(bOut);
        tOut = new TarArchiveOutputStream(gzOut);
        addFileToTarGz(tOut, rawDir, "");
    } catch (FileNotFoundException e) {
        log.error("File not found: " + e);
    } finally {
        if(tOut != null) {
            tOut.finish();
            tOut.close();
        }
    }

Any other considerations or thoughts on improving things?

A:
My understanding of streams is that as long as you close a stream, any streams encapsulated within it will be closed ...

That is correct.
However, your code is (effectively) assuming that if tOut is null, then none of the other streams in the chain have been created.  That's a somewhat dodgy assumption.  Consider this sequence:

*

*The FileOutputStream is created and is assigned to fOut.

*The BufferedOutputStream is created and is assigned to bOut.

*The GzipCompressorOutputStream constructor throws an exception or error.  (Maybe the heap is full ...).

*The catch is skipped ... wrong exception.

*The finally checks tOut, finds it is null, and does nothing.

Net result: we've leaked the file descriptor / channel held by the FileOUtputStream.
The key to getting this example (absolutely) right is to understand which of those stream objects holds the critical resources, and ensuring that THAT stream gets closed.  The other streams that don't hold resources don't have to be closed.
} finally {
    if (fOut != null) {
        fOut.close();
    }
}

The other point is that you need to move the tOut.finish() call into the try block after the addFileToTarGz call.

*

*If the addFileToTarGz call throws an exception, or if you don't get that far, the finish call is a waste of time.

*The finish call will attempt to write the index to the archive, and THAT could throw an IOException.  If this happens in the finally block, then any following code in the finally block to close the stream chain won't get executed ... and a file descriptor will be leaked.

A: Although it would look ugly and is,maybe, unlikely to be the case, you should close them all in cascade. Yes, if you close the TarArchiveOutputStream, it is supposed to close the underlyning streams. But, depending on the implementation, it may not always be the case. Moreover, and probably mainly, if one of the intermediate constructors throw an exception, tOut will be null, but the other ones may not be. Meaning that your streams are opened but your did not close any.

A: You could chain all your constructors together like so:
    tOut = new TarArchiveOutputStream(new GzipCompressorOutputStream(new BufferedOutputStream(new FileOutputStream(archiveFile))));

And save yourself 6 lines of initialization and 3 local variables for debugging. Not everyone likes chaining things that way - I personally find it more readable but the rest of your team may prefer it your way.
As far as closing the stream, it looks correct to me.


text:
Q: Where does pyodbc get its user and pwd from when none are provided in the connection string I inherited a project and am having what seems to be a permissions issue when trying to interact with the database. Basically we have a two step process of detach and then delete.
Does anyone know where the user would come from if the connection string only has driver, server, and database name.
EDIT
I am on Windows Server 2008 standard
EDIT
"DRIVER={%s};SERVER=%s;DATABASE=%s;" Where driver is "SQL Server"

A: I just did a few tests and the {SQL Server} ODBC driver apparently defaults to using Windows Authentication if the Trusted_connection and UID options are both omitted from the connection string. So, your Python script must be connecting to the SQL Server instance using the Windows credentials of the user running the script.
(On the other hand, the {SQL Server Native Client 10.0} driver seems to default to SQL Authentication unless Trusted_connection=yes is included in the connection string.)

A: Since you're on Windows, a few things you should know:

*

*Using the Driver={SQL Server} only enables features and data types
supported by SQL Server 2000. For features up through 2005, use {SQL
Native Client} and for features up through 2008 use {SQL Server
Native Client 10.0}.

*To view your ODBC connections, go to Start and search for "ODBC" and
bring up Data Sources (ODBC). This will list User, System, and File
DSNs in a GUI. You should find the DSN with username and password
filled in there.


text:
Q: Pass several arguments as macro in C Sorry for bad English.
Suppose the code:
#define FOO(x,y) FOO ## x
#define BAR A, B

FOO(A, B) successfully expanded to FOOA. But when I write FOO(BAR), the C preprocessor (gcc -E) give error
error: macro "FOO" requires 2 arguments, but only 1 given

How I should change FOO macro if I want expand FOO(BAR) to FOOA?

A: #define FOO(X, Y) FOO ## X
#define BAR A, B

#define APPLY(F, X) F(X)

APPLY(FOO, BAR)

or
#define FOO(X) FOO_(X)
#define FOO_(X, Y) FOO ## X
#define BAR A, B

FOO(BAR)


text:
Q: LogMetric not working with microsoft extension framework I am using the logging extension framework in an asp.net core function app. I have following code:
log.LogMetric("TESTER", 0);

log.LogInformation($"{{logTypeStart}}: {service.GetType()}", logTypeStart);
await service.Run(log);
log.LogInformation($"{{logTypeEnd}}: {service.GetType()}", logTypeEnd);

In log analytics I query following:
AppTraces
AppMetrics

The LogInformation logs traces to the AppTraces in Log Analytics. But AppMetrics does not provide any results. Any pointers on how to troubleshoot this?

A: I tested it with Function V3, the metrics can be sent to both AI and the connected Log Analytics.
Please check the things below:
1.Test your code first locally(please follow this thread to see how azure function and application insights works locally), and see if the metrics can be shown in visual studio output. The screenshot is as below:

2.Please make sure the Azure log Analytics is actually connected with the AI you're using.
3.In Azure log Analytics, when query in AppMetrics table, make sure you have selected the proper time range. Here is the screenshot of my metrics:

Please let me know if any more issues.


text:
Q: Java: How do I create a ReST service and call a URL Can anyone help me find a good tutorial for creating a ReST client in Java that would be able to call a URL.
I need a really basic tutorial that tells me where to find the API, how to import the jars, etc.
Edit: I tried Restlet, but the documentation was difficult to follow.
Thanks,
E

A: It's been my experience that Jersey is very easy to use.  This tutorial (REST with Java (JAX-RS) using Jersey) is straightforward.

A: I assume you're talking HTTP here, so you'd likely find a good start just heading over the Apache and their HTTP Components libraries. That should keep you in trouble for a while.

A: I would recommend using Jersey Client. You can find many tutorials through google, but this should get you started with some good examples: http://www.vogella.de/articles/REST/article.html


text:
Q: Load CSV Strings With Different Types into Pandas Dataframe, Split Columns, Parse Date I have two questions concerning a large csv file which contains data in the following way formatted as strings:
 "XAU=,XAU=,XAG=,XAG="
 "25/08/2014 6:00:05,1200.343,25/08/2014 6:00:03,19.44,"
 "25/08/2014 6:00:05,1200,,,"

Is there a way to efficiently load this into a pandas dataframe object? Alternatively, also multiple pandas Series objects would do the job. So far I tried:
df = read_csv(path, header=None)
df[0].str[0:-1].str.split(',', return_type='frame')

The second line is an answer from this thread pandas split string into columns. However, I wonder if there is an even better way, especially since I have different data types? Secondly, how can I correctly parse the dates with to_datetime(). I tried to reindex df and used df.index = df.index.to_datetime(). This worked only half way because it did not strictly keep the dd/mm/yyyy ... format. Some dates were incorrectly parsed as mm/dd/yyyy .... I'm looking for fast ways because eventually I will loop over many such csv's. Thx for any help!
EDIT: Ideally data in this form should be handled as well:
     "XAU=,XAU=,XAG=,XAG="
     "25/08/2014 6:00:05,1200.343,25/08/2014 6:00:03,19.44,"
     ",,25/08/2014 6:00:05,19.50,"

So with the answer provided below,
    data = StringIO(
    '''
    "XAU=,XAU=,XAG=,XAG="
    "25/08/2014 6:00:05,1200.343,25/08/2014 6:00:03,19.44,"
    ",,25/08/2014 6:00:05,19.5,"
    ''')

df would become:
                  XAU                    XAU                       XAG      XAG
0  25/08/2014 6:00:05               1200.343        25/08/2014 6:00:03    19.44
1                   ,     25/08/2014 6:00:05                      19.5       \n

A: You can preprocess everything inside the read_csv as shown:
import csv

data = StringIO(
'''
"XAU=,XAU=,XAG=,XAG="
"25/08/2014 6:00:05,1200.343,25/08/2014 6:00:03,19.44,"
"25/08/2014 6:00:05,1200,,,"
''')

df = pd.read_csv(data, quoting=csv.QUOTE_NONE, index_col=False, escapechar='"',   \
                 parse_dates=[0, 2]).rename(columns=lambda x: x.split("=")[0])
df

df.dtypes

XAU    datetime64[ns]
XAU           float64
XAG    datetime64[ns]
XAG           float64
dtype: object

Break-up:
quoting=csv.QUOTE_NONE : Instructs writer objects to never quote fields
index_col=False: Do not use the first column as the index
escapechar=": string used to escape delimiter
parse_dates=[0, 2]: convert columns(0,2 → order) to datetime objects

To read a subset of the columns, you can do so with the help of usecols by supplying appropriate integer indices as shown:
df = pd.read_csv(data, quoting=csv.QUOTE_NONE, index_col=False, escapechar='"',   \
                 parse_dates=[0], usecols=[0,1]).rename(columns=lambda x: x.split("=")[0])

df

If you want to convert the two columns of XAU into a series object:
df.columns = df.columns + [str('_%d'%(i)) for i in list(range(len(df.columns)))]

ser = pd.Series(data=df['XAU_1'].values, index=df['XAU_0'].values, name='XAU')
ser

2014-08-25 06:00:05    1200.343
2014-08-25 06:00:05    1200.000
Name: XAU, dtype: float64

type(ser)
pandas.core.series.Series

The reason that fails for a newer case is because escapechar skips the first delimiter, as a result the empty strings aren't captured properly.
If that's the case, you are better off ignoring escapechar altogether and continuing as shown:
For the combination of old and new data:
data = StringIO(
'''
"XAU=,XAU=,XAG=,XAG="
"25/08/2014 6:00:05,1200.343,25/08/2014 6:00:03,19.44,"
"25/08/2014 6:00:05,1200,,,"
",,25/08/2014 6:00:05,19.50,"
''')

df = pd.read_csv(data, quoting=csv.QUOTE_NONE, index_col=False, na_values=[""],
                 parse_dates=[2]).rename(columns=lambda x: x.strip('"').split("=")[0])

old_cols = df.columns
# Index(['XAU', 'XAU', 'XAG', 'XAG'], dtype='object')

new_cols = [col[0] for col in list(enumerate(df.columns))]
# [0, 1, 2, 3]
df.columns = new_cols

# Converting first column to datetime dtype
df[0] = pd.to_datetime(df[0].str.replace('"', ''))
df.columns = old_cols

df

df.dtypes

XAU    datetime64[ns]
XAU           float64
XAG    datetime64[ns]
XAG           float64
dtype: object


text:
Q: Change IntelliJ default test framework for run/debug configurations Using IntelliJ 2019.3.
I'm unable to change my default test framework for run/debugging. Per https://stackoverflow.com/a/48787268 I've removed all of the default Gradle test configurations, but when I go to run an individual test, IntelliJ still reverts back to using Gradle.
I can manually configure to use another test framework, but I want to change it so that I don't have to do this for every single test/class/package.
I would expect there to be an option under the Run/Debug Configurations window, but there is not.

A: You can configure IntelliJ IDEA to use the built-in runner instead of Gradle:


text:
Q: Could someone tell me why the binary tree I am creating in this code using it's preorder and postorder is not being created in the desired way? I have written this code to create a binary tree using given preorder and inorder traversals. According to the dry run I do, there is no problem, and the tree should be created properly. But it is not happening that way.
I have printed the inorder of the tree just to check if the tree has been created of the tree. But instead of the inorder, the postorder is being printed.
On further investigation I found that the tree itself is not created rightly, that is why the error is coming. There is nothing on the right part of the root which is created. But according to the dry run, there is no problem. Could someone help me find my mistake?
Sample Input:
a
b
d
e
f
c
g
h
j
l
k
d
b
f
e
a
g
c
l
j
h
k
Output:
dfebgljkhca
     #include <stdio.h>

typedef struct Node
{
    int data;
    struct node *left;
    struct node *right;
}node;
typedef node *tree;
tree root=NULL;

char pre[11];
char in[11];

static int i;

void create( tree temp, int start_left, int end_left, int start_right, int end_right )
{
    if ( start_left <= end_left )
    {
        temp->left= (tree) malloc(sizeof( node ));
        temp=temp->left;
        temp->left=NULL;
        temp->right=NULL;
        int j;
        for ( j=start_left; j<=end_left; j++)
        {
            if ( pre[i]==in[j] )
            {
                temp->data=pre[i];
                break;
            }
        }
        i++;
        create( temp, start_left, j-1, j+1, end_left );

    }
    if ( start_right <= end_right )
    {
        temp->right= (tree) malloc(sizeof( node ));
        temp=temp->right;
        temp->left=NULL;
        temp->right=NULL;
        int j;
        for ( j=start_right; j<=end_right; j++)
        {
            if ( pre[i]==in [j] )
            {
           temp->data=pre[i];
                break;
            }
        }
        i++;
        create( temp, start_right, j-1, j+1, end_right );
    }
    return ;
}

void inorder_print(tree temp)
{
    if ( temp!=NULL )
    {
        inorder_print(temp->left);
        printf("%c",temp->data);
        inorder_print(temp->right);
    }
}

int main()
{

    for( i=0; i<11; i++)
    {
        scanf("%c", &pre[i]);
        fflush(stdin);
    }

    for( i=0; i<11; i++)
    {
        scanf("%c", &in[i]);
        fflush(stdin);
    }
    int j;
    for( j=0; j<11; j++)
    {
        if( pre[0]==in[j] )
        {
            root= (tree) malloc(sizeof( node ));
            root->data=pre[0];
            root->left=NULL;
            root->right=NULL;
            break;
        }
    }
    i=1;
    create( root, 0, j-1, j+1, 10);
    inorder_print(root);
    return 0;
}

A: What about something more generalized?
My suggestion has the following output:
prorder:
a a b b d c c d e e f f g g h h j j l k k l
inorder:
a a b b c c d d e e f f g g h h j j k k l l
   [a]
 +--+-----+
[a]      [b]
       +--+-----------+
      [b]            [d]
                +-----+-----+
               [c]         [e]
             +--+--+     +--+-----+
            [c]   [d]   [e]      [f]
                               +--+-----+
                              [f]      [g]
                                     +--+-----+
                                    [g]      [h]
                                           +--+-----+
                                          [h]      [j]
                                                 +--+-----------+
                                                [j]            [l]
                                                          +-----+
                                                         [k]
                                                       +--+--+
                                                      [k]   [l]

And the code is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct      s_tree
{
    void            *content;
    size_t          content_size;
    struct s_tree   *left;
    struct s_tree   *right;
}                   t_tree;

/*
** Tree content casted to given type
*/

#define TCONT(tree, t_type) ((t_type)((tree)->content))

/*
** Helpers
*/

void    *ft_memdup(void const *ptr, size_t size)
{
    void            *result;

    result = (void*)malloc(size);
    if (result == NULL)
        return (NULL);
    memcpy(result, ptr, size);
    return (result);
}

t_tree  *ft_tree_new(void const *content, size_t content_size)
{
    t_tree  *result;

    result = (t_tree*)malloc(sizeof(t_tree));
    if (result == NULL)
        return (NULL);
    result->left = NULL;
    result->right = NULL;
    if (content == NULL)
    {
        result->content = NULL;
        result->content_size = 0;
    }
    else
    {
        result->content = ft_memdup(content, content_size);
        result->content_size = content_size;
    }
    return (result);
}

void    ft_tree_add(
            t_tree **root,
            t_tree *new_branch,
            int (*cmp)(void*, void*))
{
    if (*root == NULL)
        *root = new_branch;
    else
    {
        if (cmp((*root)->content, new_branch->content) >= 0)
            ft_tree_add(&(*root)->left, new_branch, cmp);
        else
            ft_tree_add(&(*root)->right, new_branch, cmp);
    }
}

void    ft_tree_map(t_tree *root, void (*f)(void*), char *map)
{
    int     i;

    if (root != NULL)
        for (i = 0; map[i]; i++)
        {
            switch (map[i])
            {
                case 'R':
                    f(root->content);
                    break;
                case 'r':
                    ft_tree_map(root->right, f, map);
                    break;
                case 'l':
                    ft_tree_map(root->left, f, map);
                    break;
            }
        }
}

/*
** Print tree function
*/

int _print_t(t_tree *tree, int is_left, int offset, int depth, char s[50][256])
{
    char    b[50];
    int     width = 3;
    int     i;

    if (!tree)
        return 0;

    sprintf(b, "[%s]", TCONT(tree, char*));

    int left  = _print_t(tree->left,  1, offset,                depth + 1, s);
    int right = _print_t(tree->right, 0, offset + left + width, depth + 1, s);

    for (i = 0; i < width; i++)
        s[2 * depth][offset + left + i] = b[i];

    if (depth && is_left)
    {
        for (i = 0; i < width + right; i++)
            s[2 * depth - 1][offset + left + width/2 + i] = '-';
        s[2 * depth - 1][offset + left + width/2] = '+';
        s[2 * depth - 1][offset + left + width + right + width/2] = '+';
    } else if (depth && !is_left)
    {
        for (int i = 0; i < left + width; i++)
            s[2 * depth - 1][offset - width/2 + i] = '-';

        s[2 * depth - 1][offset + left + width/2] = '+';
        s[2 * depth - 1][offset - width/2 - 1] = '+';
    }
    return left + width + right;
}

void print_tree(t_tree *tree)
{
    char s[50][256];

    for (int i = 0; i < 50; i++)
        sprintf(s[i], "%100s", " ");

    _print_t(tree, 0, 0, 0, s);

    for (int i = 0; i < 50; i++)
        printf("%s\n", s[i]);
}

//end of print tree function

void    print_str(char *str)
{
    printf("%s ", str);
}

int     main()
{
    t_tree  *root;
    char    input[] = "abdefcghjlkdbfeagcljhk";
    char    tmp[2];
    int     i;

    tmp[1] = 0;
    root = NULL;
    for (i = 0; input[i]; i++)
    {
        tmp[0] = input[i];
        ft_tree_add(&root,
            ft_tree_new(tmp, strlen(tmp) + 10),
            (int (*)(void*, void*))(&strcmp));
    }

    //Preorder
    printf("preorder:\n");
    ft_tree_map(root, (void (*)(void*))(&print_str), "Rlr");
    printf("\n");

    //Inorder
    printf("inorder:\n");
    ft_tree_map(root, (void (*)(void*))(&print_str), "lRr");
    printf("\n");

    print_tree(root);
}

If you want to change the way of insertion, make your own comparison function and change &strcmp with &your_function.


text:
Q: Add class based on URL not working with main url I have the below code where the script checks for the li links and if that link is found within the url address a class get added and the sub ul will expand.
This works well on sub pages but on the root of the site all li's show slided down as if the url within the home link is not being detected. I think it has to do with the forward slash since the main page does not have it.
Any ideas?
$(function(){

var url = window.location.pathname,
    urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
    // now grab every link from the navigation

    $('#cssmenu > ul > li > a').each(function(){
        // and test its normalized href against the url pathname regexp
        if(urlRegExp.test(this.href.replace(/\/$/,''))){
          $('#cssmenu li').removeClass('active');
      $(this).children('li').addClass('active');
      var checkElement = $(this).next();
      if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
        $(this).children('li').addClass('active');
        checkElement.slideDown('normal');
      }

      if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
        $('#cssmenu ul ul:visible').slideUp(50);
        checkElement.slideDown(800);
      }
      if($(this).children('li').find('ul').children().length ==0) {
        return true;
      } else {
        return false;
      }
                }
            });

    });

A: How about an early return if urlRegExp is blank? Which it should be on your root path.
Assuming you don't want anything else to happen on your root page, then an
if(urlRegExp.length == 0){
  //root page
} else {
  //other page (what you are doing now)
}


text:
Q: You are taking a multiple-choice test with n questions each of which has 4 alternatives. You have mastered 60% of the material You are taking a multiple-choice test with n questions each of which has 4 alternatives. You have mastered 60% of the material. Assume this means that you have a 0.6 chance of knowing the answer to a random test question, and that if you don't know the answer to a question then you randomly select among the four answer choices. Assume that this holds for each question, independent of the others, and assume that each correct answer gives 1 point and wrong answers give 0 points, the score is the sum of all points.  For each answer define a random variable Xi (i=1,2,...,n) that takes the value 1 if the  ith answer is correct and 0 otherwise.
a.What is the probability that you answer a particular question correctly?
b.What is your expected score on the exam?
c.Write down a formula for the probability mass function (pmf) for one particular X, obtain the cumulative distribution function (CDF) for Xi and plot the CDF
WORK: for my work so far I have A = Knowing the answer B = All choices are equal and C = Student answers correctly. P(A) = .6, P(B) = .25 I am looking for P(A|C)? = P(C|A)P(A)/P(C)? Other than that I am kind of lost

A: a) The probability that he gets a particular question correct is
$$p=\left(0.6\cdot1\right)+\left(0.4\cdot0.25\right)=0.7$$
b) This is a binomial distribution with mean $np$
c)
Assuming $X$ is a random variable taking on the value $1$ if the answer is correct and $0$ if the answer is incorrect...
$$ p_{X}(x)=
\begin{cases}
0.7 & x =1 \\
0.3 & x=0 \\
0 & \text{otherwise}
\end{cases} $$
d)
$$ F_{X}(x)=
\begin{cases}
1 & x \geq 1 \\
0.3 & 0\leq x\lt 1 \\
0 & x \lt 0
\end{cases} $$
Note that even in the discrete case, we must account for all $x\in\mathbb{R}$


text:
Q: How to properly enable second level cache in Orocommerce I wrote the following configuration in config.yml, but I'm not sure if this is the right thing to do:
doctrine:
orm:
    entity_managers:
        default:
            metadata_cache_driver:
                type: service
                id:   doctrine.metadata.cache
            query_cache_driver:
                type: service
                id: doctrine.query.cache
            second_level_cache:
                region_cache_driver:
                    type: service
                    id: snc_second_level_cache
                enabled: true
                region_lifetime: 600
            result_cache_driver:
                type: service
                id: doctrine.result.cache

service configuration:
    snc_second_level_cache:
        class: '%snc_redis.doctrine_cache_predis.class%'
        arguments:
            - '@snc_redis.doctrine'

A: The Oro team has investigated this feature, and for now, we found that it brings more issues than benefits, so the application doesn't support it out of the box, and enabling it just with the configuration does not affect anything.
However, if you want to enable it for some custom entities, the configuration seems correct. Just pay attention that there are multiple entity managers in ORO, not only the default one.


text:
Q: Change canvas size from .py on kiy I am trying to change the canvas size of an image randomly. I have 10 images in a GridLayout and I want to randomly resize one of them. I have tried several ways but I can't figure it out, what am I doing wrong?

.kv
<ButOpcion>:
    canvas.before:
        Rectangle:
            pos: self.pos
            size: 250, 250
            source: "data/img/letra_d/dragon.png"

<ContainerCaza>:
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'data/img/fondobosque.jpg'

    but_1: but1
    but_2: but2
    but_3: but3
    but_4: but4
    but_5: but5
    but_6: but6
    but_7: but7
    but_8: but8
    but_9: but9
    but_10: but10

    BoxLayout:
        orientation: 'vertical'
        Label:
            text: 'Ahora debes localizar al intruso entre estas imágenes. ¡Fíjate bien, una de las imágenes es distinta!'
            size_hint_y: None
            text_size: self.width, None
            #height: self.texture_size[1]
            halign: 'center'
            valign: 'middle'
            padding: (20,15)
            font_size: 25
            color: (.66, .38, .14, 1)

        GridLayout:
            pos_hint: {"center_x": 0.5, "center_y": 0.5}
            cols: 5
            spacing: '10dp'
            #size_hint: 0.6, 0.6

            ButOpcion:
                id: but1

            ButOpcion:
                id: but2

            ButOpcion:
                id: but3

            ButOpcion:
                id: but4

            ButOpcion:
                id: but5

            ButOpcion:
                id: but6

            ButOpcion:
                id: but7

            ButOpcion:
                id: but8

            ButOpcion:
                id: but9

            ButOpcion:
                id: but10

        Button:
            size_hint:.06, 0.1
            text: "Volver al menú"
            on_release: app.root.current = 'menu'

.py
__all__ = ('Caza')

import kivy
kivy.require('1.0.6')

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from random import choice, random
from kivy.properties import ObjectProperty
from kivy.graphics import Rectangle

#Builder.load_file('caza.kv')

class ButOpcion(Widget):
    pass

class ContainerCaza(Screen):
    def __init__(self, **kwargs):
        super(ContainerCaza, self).__init__(**kwargs)

    def intruso(self):
        but_1 = ObjectProperty(None)
        but_2 = ObjectProperty(None)
        but_3 = ObjectProperty(None)
        but_4 = ObjectProperty(None)
        but_5 = ObjectProperty(None)
        but_6 = ObjectProperty(None)
        but_7 = ObjectProperty(None)
        but_8 = ObjectProperty(None)
        but_9 = ObjectProperty(None)
        but_10 = ObjectProperty(None)

        target = choice(['but1', 'but2', 'but3', 'but4', 'but5', 'but6', 'but7', 'but8', 'but9', 'but10'])
        print(target)

        if target == 'but1':
            def ChangeImage1(self):
                self.ids.but1.size = 10, 10
        elif target == 'but2':
            def ChangeImage2(self):
                self.ids.but2.size = 10, 10
        elif target == 'but3':
            def ChangeImage3(self):
                self.ids.but3.size = 10, 10
        elif target == 'but4':
            def ChangeImage4(self):
                self.ids.but4.size = 10, 10
        elif target == 'but5':
            def ChangeImage5(self):
                self.ids.but5.size = 10, 10
        elif target == 'but6':
            def ChangeImage6(self):
                self.ids.but6.size = 10, 10
        elif target == 'but7':
            def ChangeImage7(self):
                self.ids.but7.size = 10, 10
        elif target == 'but8':
            def ChangeImage8(self):
                self.ids.but8.size = 10, 10
        elif target == 'but9':
            def ChangeImage9(self):
                self.ids.but9.size = 10, 10
        else:
            def ChangeImage10(self):
                self.ids.but10.size = 10, 10

class CazaApp(App):
    def build(self):
        #Window.fullscreen = 'auto'
        caza = ContainerCaza()
        caza.intruso()
        return caza

if __name__ == "__main__":
    CazaApp().run()

How can I access the canvas.before from the .py file? I'm new to python and kivy and I'm a bit lost, there are a lot of things I don't know how to do.

A: In your intruso() method, you are defining inner methods that can change the size of a ButOpcion, but you never call those inner methods. I don't see any purpose to creating an inner method here, so I think you should just execute the code that you are putting in the inner method:
def intruso(self, *args):

    target = choice(['but1', 'but2', 'but3', 'but4', 'but5', 'but6', 'but7', 'but8', 'but9', 'but10'])
    print(target)

    if target == 'but1':
        self.ids.but1.size = 10, 10
    elif target == 'but2':
        self.ids.but2.size = 10, 10
    .
    .
    .

And rather than trying to change the size of the canvas directly, just change the size of the ButOpcion and let the canvas adjust to it. This can be done by defining your ButOpcion in the kv as:
<ButOpcion>:
    size_hint: None, None
    size: 250, 250
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: "data/img/letra_d/dragon.png"

A: Thanks John, it seems to work correctly now, but aesthetically, it places the GridLayout in the upper left corner.


text:
Q: What's the meaning of "mellow mama"? What's the meaning of "mellow mama" in this description?
I found this expression in a recipe book, but I don't understand what it means:

Pulling from the inspiration of a green goddess dressing, this blend will channel your inner mellow mama!

A: Mellow is an adjective: Mellow defines someone or something that is calm, smooth and free from harshness.

A person who is calm and peaceful and doesn't get upset easily is an example of a person who is mellow.

Source
And mama refers to "mom" which is either a mother or a lady that for instance is friendly and helpful toward a lot of people.
So in conclusion "mellow mama" refer to a lady who is calm and peaceful and doesn't get upset easily. Someone you can trust.

A: "Mama" is used slangily here to refer to a woman (not necessarily a mother). I think it's a usage that's common in "wellness" circles - someone writing an "anti-anxiety diet" book would quite likely be in that milieu and I'm not surprised they would speak this way. "Mellow mama" is alliterative and kind of a parallel to "green goddess", used earlier in the sentence, which is also alliterative (this means that every word begins with the same sound). Basically, this is a cute way of saying that the recipe will make you feel calm and relaxed.


text:
Q: PHP MYSQL Returning Results When Booking Spans Into Next Month I am editing a booking system's code (nation hotel theme in wordpress) in order to try to fix the issue that when the user selects a check-out date in the month after the check-in date it returns 0 results.
Here is the original code from the reservations page:
$dayFirst = date("d",strtotime($_POST["check-in"]));
$monthFirst = date("m",strtotime($_POST["check-in"]));
$yearFirst = date("Y",strtotime($_POST["check-in"]));
$dayLast = date("d",strtotime($_POST["check-out"]));
$monthLast = date("m",strtotime($_POST["check-out"]));
$yearLast = date("Y",strtotime($_POST["check-out"]));

$price = $wpdb->get_row( $wpdb->prepare(
    "SELECT min_price FROM {$wpdb->prefix}nation_booking_calendars WHERE id='%d'",
    $calID
    ) );
$minPrice = $price->min_price;
                                               $roomAvailty = $wpdb->get_results( $wpdb->prepare(
    "SELECT * FROM {$wpdb->prefix}nation_booking_availability
    WHERE calendar_id='%d'
        AND day >= $dayFirst
        AND month >= $monthFirst
        AND year >= $yearFirst
        AND day < $dayLast
        AND month <= $monthLast
        AND year <= $yearLast
        AND availability >= %d ",
    $calID,$_POST["room-number"]
    ) );

if ( count($roomAvailty) == count( $dateRange ) ) {
    $roomAvailable = true;
}

My problem is that count($roomAvailty) returns 0 when the booking goes over into the next month.
I figured that the problem was how the mysql select statement worked so I changed that part to the following:
if($monthFirst==$monthLast) {
    $roomAvailty = $wpdb->get_results( $wpdb->prepare(
        "SELECT *
        FROM {$wpdb->prefix}nation_booking_availability
        WHERE calendar_id='%d'
            AND day >= $dayFirst
            AND month >= $monthFirst
            AND year >= $yearFirst
            AND day < $dayLast
            AND month <= $monthLast
            AND year <= $yearLast
            AND availability >= %d ",
        $calID,$_POST["room-number"]
        ) );
}
else {
    $roomAvailty = $wpdb->get_results( $wpdb->prepare(
        "(SELECT * FROM {$wpdb->prefix}nation_booking_availability
            WHERE calendar_id='%d'
                AND day >= $dayFirst
                AND day <= $maxdays
                AND month = $monthFirst
                AND year = $yearFirst
                AND availability >= %d)
        UNION ALL
            (SELECT * FROM {$wpdb->prefix}nation_booking_availability
            WHERE calendar_id='%d'
                AND day >= $mindays
                AND day < $dayLast
                AND month = $monthLast
                AND year = $yearLast
                AND availability >= %d)
        UNION ALL
            (SELECT * FROM {$wpdb->prefix}nation_booking_availability
                WHERE calendar_id='%d'
                    AND month > $monthFirst
                    AND month < $monthLast
                    AND year = $yearFirst
                    AND availability >= %d) ",
        $calID,$_POST["room-number"]
        ) );
}

But its still returning 0 results. Any ideas? Here is a picture of my database:
id  calendar_id day month year availability price
101 11          2   9     2014 1            95
102 11          3   9     2014 1            95
103 11          4   9     2014 1            95
104 11          5   9     2014 1            95
105 11          6   9     2014 1            95
106 11          7   9     2014 1            95
107 11          8   9     2014 1            95
108 11          9   9     2014 1            95
109 11         10   9     2014 1            95


text:
Q: Active Record Validation Rails 4 I'm trying to validate presence of a zip code upon creation of a book store by checking if the entered zip code corresponds to any zip code in my zip_codes table.
In the book store model, something like:
validates_presence_of :zip_code, unless: ........

The sql statement to find such zip codes is:
select zip_code from book_stores where zip_code not in (select distinct zip_code from zip_codes);

A: You'll want to define your own validation method:
validate :zip_code_exists

def zip_code_exists
    errors.add(:zip_code, 'is not valid') unless ZipCode.exists?(zip_code: zip_code)
end

That will add an error message on the zip_code attribute of your model, unless the ZipCode model contains a record who's zip_code matches the zip_code provided.

A: I would use a before_save hook instead here.  The way this works, is it calls a function and only saves the record if the function returns true.  So for example:
BookStore.rb:
before_save :check_zip_code

def check_zip_code
  connection = ActiveRecord::Base.connection

  zip_codes=connection.execute('select "zip_code" from "book_stores" where "zip_code" not in (select distinct "zip_code" from "zip_codes")').to_a

  if self.zip_code&&(zip_codes.include?(self.zip_code)
    return true
  else
    return false
  end
end

You can also validate the presence of zip_code to simplify the before_save call, since validations happen before the before_save method is called.  You could then assume that self.zip_code is defined.


text:
Q: How to make SQL Query with Two Different Table I cannot fine same question in here, so I write it.
I need one SQL query for below details;
I have two tables and 2st table has team_id and 2nd table have home_team_id and away_team_id and home and away scores.
I can make home and away matches separately as below queries already:
Home Matches Query :
SELECT Distinct m.week,m.match_date, h.team_name as Home, a.team_name as AWAY,m.home_score,m.away_score,m.league_id
FROM matches m,teams h,teams a, leagues l
WHERE h.team_id=m.home_team_id and a.team_id=m.away_team_id
and h.team_name ='Real Madrid'  and m.league_id = 1;

Away Matches Query :
SELECT Distinct m.week,m.match_date, h.team_name as Home, a.team_name as AWAY,m.home_score,m.away_score,m.league_id
FROM matches m,teams h,teams a, leagues l
WHERE h.team_id=m.home_team_id and a.team_id=m.away_team_id
and a.team_name ='Real Madrid'  and m.league_id = 1;

I want to see one team home and away results in same query.
My Tables are: (matches and teams)
matches table columns are;
match_id
match_date,
home_team_id,
away_team_id,
home_score,
away_score
teams table columns are;
team_id,
team_name
I want to see below result :
One team's Home and Away score in one table as
Example: Team is Real Madrid
Results:

Home Team
Away Team
Home Score
Away Score

Real Madrid
Barcelona
1
0

Real Madrid
Cadiz
1
1

Real Madrid
A. Madrid
2
2

Villareal
Real Madrid
2
0

Valencia
Real Madrid
1
3

A: Use the same query, but test the team name against either h.team_name or a.team_name.
SELECT Distinct m.week,m.match_date, h.team_name as Home, a.team_name as AWAY,m.home_score,m.away_score,m.league_id
FROM matches m
JOIN teams h ON h.team_id=m.home_team_id
JOIN teams a ON a.team_id=m.away_team_id
WHERE 'Real Madrid' IN (h.team_name, a.team_name) and m.league_id = 1;

A: You have to join two tables with teams table and matches table. Use OR paramater instead of AND.


text:
Q: JPA Typed query set parameter I have a named parameter in JPA typed query. I am setting a list of value in condition.
I am setting a list of integer, but when JPA converts typed query to corresponding sql query it is adding a to_number function and index of the table is not used.
 List<Integer> studentIds=ArrayList<Integer>
 //Student id is number in database and indexed.
 query = "SELECT T.* FROM STUDENT WHERE STUDENT_ID IN (:studentIds)"
 TypedQuery<Object[]> typedQuery = entityManager().createQuery( query, Object[].class);
 typedQuery.setParameter("studentIds", studentIds);

The issue is when JPA generates the query it is adding to_number function to convert the list
SELECT * from student t4 where student_id in (?,?,?);
 filter("T4"."student_id"=TO_NUMBER(:9) OR "T4"."student_id"=TO_NUMBER(:10) OR
  "T4"."student_id"=TO_NUMBER(:11) OR "T4"."PRODUCT_SET_ID"=student_id(:12)

Any thoughts how to make sure JPA does not add a to_number function, so index will be used.

A: I had to use an array when I was passing values into a '.in' predicate. Try this:
List<Integer> studentIds=ArrayList<Integer>
Integer[] ids = new Integer[studentIds.size()];
ids = studentIds.toArray(ids);
//Student id is number in database and indexed.
query = "SELECT T.* FROM STUDENT WHERE STUDENT_ID IN (:studentIds)"
TypedQuery<Object[]> typedQuery = entityManager().createQuery( query, Object[].class);
typedQuery.setParameter("studentIds", ids);


text:
Q: Same location with different proxy urls nginx We am trying to get nexus via nginx reverse proxy working as a private registry for docker images. We are able to perform all the operations such as pull,search and tag but not able to push to nexus registry .
Below is the nginx configuration under location block.
    location ~ ^/(v1|v2)/
    {
            proxy_set_header        Host $http_host;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header        X-Forwarded-Proto "https";
            proxy_pass              http://box.company.net:5555;
            proxy_read_timeout      90;
    }

We are able to search and pull images.
But with push we face below error.
x.x.x.x - admin [23/Jun/2017:14:32:34 +0800] "POST /v2/fedora/apache/blobs/uploads/?from=fedora%2Fssh&mount=sha256%3Aacd6cf67daf4cd1fcff55ece5a906a45e1569b81271b80136a1f5fecfa4546ed HTTP/1.1" 404 717 "-" "docker/1.12.6 go/go1.7.4 kernel/3.10.0-514.10.2.el7.x86_64 os/linux arch/amd64 UpstreamClient(Docker-Client/1.12.6 \x5C(linux\x5C))"

when we try with proxy _pass url as http://box.company.net:4444, we are able to push but cant pull the images .
Is it possible in nginx to pass two different proxy_pass urls under the same location but for different request methods . Any help would be really great ..Thanks

A: You can use if or map directives to select backend port.
Note, that If is Evil, not in you case of course.
location ~ ^/(v1|v2)/
{
    set $port 5555;
    if ($request_method = POST) {
        set $port 4444;
    }
    proxy_set_header        Host $http_host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header        X-Forwarded-Proto "https";
    proxy_pass              http://box.company.net:$port;
    proxy_read_timeout      90;
}

A: @sempasha : Thanks for you help . It working for me just with a minor tweak .
Below is the location block added to get it working.
  location / {
      proxy_set_header        Host $http_host;
      proxy_set_header        X-Real-IP $remote_addr;
      proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

        if ($request_method !~* GET) {
                proxy_pass              http://box.company.net:4444;
        }
        if ($request_method = GET) {
                proxy_pass              http://box.company.net:5555;
        }
      proxy_read_timeout      90;
    }


text:
Q: What is the series solution to $y''-3x^2y'-6xy=0$ In attempting this, I got that the answer was
$$y(x) = a_0 \sum_{n=0}^\infty \frac{3^n}{(3n)!!!}x^{3n} + a_1 \sum_{n=0}^\infty \frac{3^n}{(3n+1)!!!}x^{3n+1} + a_2 \sum_{n=0}^\infty \frac{3^n}{(3n+2)!!!}x^{3n+2}$$
but I can't find any way to verify that this is indeed correct.

A: Let $\displaystyle y = \sum_{n=0}^{+\infty} a_n x^n$.  Then
\begin{align}
  y' &= \sum_{n=0}^{+\infty} na_n x^{n-1},\\[0.3cm]
  y''  &= \sum_{n=0}^{+\infty} n(n-1)a_n x^{n-2}.
\end{align}
Substituting these series into the original equation gives us
\begin{align}
  0 &= y'' - 3x^2y - 6xy\\[0.3cm]
    &= \sum_{n=0}^{+\infty}n(n-1)a_nx^{n-2} - 3x^2\sum_{n=0}^{+\infty}na_nx^{n-1} - 6x\sum_{n=0}^{+\infty} a_nx^n\\[0.3cm]
    &= \sum_{n=0}^{+\infty}n(n-1)a_nx^{n-2} - \sum_{n=0}^{+\infty}3na_nx^{n+1} - \sum_{n=0}^{+\infty} 6a_nx^{n+1}
\end{align}
Let's modify these series so we can combine them into one series to easily determine the coefficients.  Note that we will most likely need to have some "stray" terms sitting outside of the summation notation when we do this.  This is fine.
\begin{align}
  \sum_{n=0}^{+\infty}n(n-1)a_nx^{n-2} &= 0 + 0 + \sum_{n=2}^{+\infty}n(n-1)a_nx^{n-2}\\[0.3cm]
    &= \sum_{n=0}^{+\infty} (n+2)(n+1)a_{n+2}x^n
\end{align}
The second equality above is obtained by re-indexing the series.  Specifically, we replaced $n$ with $n+2$.
\begin{align}
  \sum_{n=0}^{+\infty}3na_nx^{n+1} &= 0 + \sum_{n=1}^{+\infty}3na_nx^{n+1}\\[0.3cm]
    &= \sum_{n=2}^{+\infty}3(n-1)a_{n-1}x^n
\end{align}
The second equality above comes from replacing $n$ with $n-1$.  The same with this equality below:
\begin{align}
  \sum_{n=0}^{+\infty} 6a_nx^{n+1} &= \sum_{n=1}^{+\infty} 6a_{n-1}x^n
\end{align}
So then we have:
\begin{align}
  0 &= y'' - 3x^2y - 6xy\\[0.3cm]
    &= \sum_{n=0}^{+\infty}n(n-1)a_nx^{n-2} - 3x^2\sum_{n=0}^{+\infty}na_nx^{n-1} - 6x\sum_{n=0}^{+\infty} a_nx^n\\[0.3cm]
    &= \sum_{n=0}^{+\infty}n(n-1)a_nx^{n-2} - \sum_{n=0}^{+\infty}3na_nx^{n+1} - \sum_{n=0}^{+\infty} 6a_nx^{n+1}\\[0.3cm]
    &= \sum_{n=0}^{+\infty} (n+2)(n+1)a_{n+2}x^n - \sum_{n=2}^{+\infty}3(n-1)a_{n-1}x^n - \sum_{n=1}^{+\infty} 6a_{n-1}x^n\\[0.3cm]
    &= (2)(1)a_2 + (3)(2)a_3x + \sum_{n=2}^{+\infty} (n+2)(n+1)a_{n+2}x^n - \sum_{n=2}^{+\infty}3(n-1)a_{n-1}x^n - \left[6a_0x + \sum_{n=2}^{+\infty} 6a_{n-1}x^n\right]\\[0.3cm]
    &= 2a_2 + 6(a_3-a_0)x + \sum_{n=2}^{+\infty} \left[(n+2)(n+1)a_{n+2} - 3(n-1)a_{n-1} - 6a_{n-1}\right]x^n
\end{align}
Since the only constant term is $2a_2$, we must have $a_2 = 0$.  Similarly, we must have $a_0 = a_3$.  Looking at the coefficients on the series, we see that we must have
$$(n+2)(n+1)a_{n+2} - 3(n-1)a_{n-1}-6a_{n-1} = 0$$
as well.  So then
\begin{align}
  0 &= (n+2)(n+1)a_{n+2} - 3(n-1)a_{n-1}-6a_{n-1}\\[0.3cm]
    &= (n+2)(n+1)a_{n+2} - [3(n-1)+6]a_{n-1}\\[0.3cm]
    &= (n+2)(n+1)a_{n+2} - 3(n+1)a_{n-1}\\[0.3cm]
  3a_{n-1} &= (n+2)a_{n+2}\\[0.3cm]
  3a_n &= (n+3)a_{n+3}
\end{align}
The last equality above comes from replacing $n$ with $n+1$.  So then we finally obtain
$$ a_{n+3} = \frac{3}{n+3}a_n.$$
Since we have a second-order ODE, we expect $a_0$ and $a_1$ to be the arbitrary constants by which all the other coefficients are determined.  And we already know that $a_2 = 0$.  So for the first few values of $n$, we have
\begin{align}
  a_3 &= \frac{3}{0+3}a_0 = \frac{3}{3}a_0\\[0.3cm]
  a_4 &= \frac{3}{1+3}a_1 = \frac{3}{4}a_1\\[0.3cm]
  a_5 &= \frac{3}{2+3}a_2 = 0\\[0.3cm]
  a_6 &= \frac{3}{3+3}a_3 = \frac{3}{6} \cdot \frac{3}{3} a_0\\[0.3cm]
  a_7 &= \frac{3}{4+3}a_4 = \frac{3}{7} \cdot \frac{3}{4} a_1\\[0.3cm]
  a_8 &= \frac{3}{5+3}a_5 = 0\\[0.3cm]
  a_9 &= \frac{3}{6+3}a_6 = \frac{3}{9} \cdot \frac{3}{6} \cdot \frac{3}{3}a_0\\[0.3cm]
  a_{10} &= \frac{3}{7+3}a_7 = \frac{3}{10} \cdot \frac{3}{7} \cdot \frac{3}{4} a_1\\[0.3cm]
  a_{11} &= \frac{3}{8+3}a_8 = 0\\[0.3cm]
\end{align}
So we have $a_0, a_1$ arbitrary and $a_2 = 0$, and for $n > 0$ we have
\begin{align}
  a_{3n} &= \frac{3^n}{(3n)!!!}a_0\\[0.3cm]
  a_{3n+1} &= \frac{3^n}{(3n+1)!!!}a_1\\[0.3cm]
  a_{3n+2} &= 0
\end{align}


text:
Q: NSTimer and performing a selector on the main thread Is it possible to run a selector which is invoked by the nstimer on the main thread?
The NSTimer is spawned in it's own thread.
My structure is that a thread invokes a method with a nstimer, the nstimer invokes a method that do some updates, but I need these updates to happen on the main thread. What is the solution? Add another method and say performOnMainThread?

A: Yes, from your timer routine just call use performOnMainThread.   From the docs:

Timers work in conjunction with run
  loops. To use a timer effectively, you
  should be aware of how run loops
  operate—see NSRunLoop and Threading
  Programming Guide. Note in particular
  that run loops retain their timers, so
  you can release a timer after you have
  added it to a run loop.

also a caveat about invalidating repeating timers:

for a repeating timer, you must
  invalidate the timer object yourself
  by calling its invalidate method.
  Calling this method requests the
  removal of the timer from the current
  run loop; as a result, you should
  always call the invalidate method from
  the same thread on which the timer was
  installed


text:
Q: Response code 404 while connecting Android client to python server My application uses standard httpUrlConnection code to connect to a python code on apache http server.
All permissions of network access and internet are given. Previously I could not run this code as I was not using Asych (a different thread for network access) as I am working on Android 3.0 - Latest version. Now I am finished with this part.
No when I call the code below the response code is 200 which is all good:
#!/Python27/python
print "Content-type: text/html"
print
print ""
print ""
print ""
print "Hello."
print ""

But when I use this code:
# Echo server program
import socket

HOST = '127.0.0.1'
PORT = 80
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()

it gives 404 response code saying Exception FileNotFoundException.
More addition, yes the code above is for a server and this is a sample code from python socket library (so all the comments are not mine). I am writing a similar server that would give database connectivity and post/get features.
So, Just need to make sure what is the problem with the server code above?
Any hints are more than welcomed.
Thanks.

A: The above echo server code could not be connected as this was not a http server and so no response code was programmed and other information required from a http server are not implemented.
The code above it worked as it was ran from Apache so obviously that worked..
Thanks for commenting...


text:
Q: Automating dirb for scanning several URLs I have a bit of a problem making this script work and was wondering if anyone knew what the problem is. It is supposed to take a list of urls as input, scan them for sub directories and then output it to different files.
for i in $(urls.txt); do echo $i; fn=$(echo $i | sed "s/\///g"); echo $fn; dirb $i /usr/share/wordlists/dirb/small.txt > $fn; done

This script does correctly remove slashes for the new file but I get the error (translated from Swedish) that ": no such file or directory". Probably from the > $fn part.
for i in $(urls.txt); do echo $i; fn=$(echo $i | sed "s/\///g"); echo $fn; dirb $i /usr/share/wordlists/dirb/small.txt -o $fn; done

And trying to use dirb's own output I instead get an error like
"OUTPUT_FILE httpwww.website.com
(!) FATAL: Error opening output file: httpwww.website.com"

And some clarification regarding the one liners:
1) loop through a list of urls
2) output the url to terminal
3) generate filename from url using sed
4) output filename to terminal
5) run url through dirb and try to output it to file name
The supposed output file names look fine to me but aren't working. Does anyone know why that is?

A: Assuming bash or ksh93:

*

*Loop through the list of URLs

*Output the URL to terminal
while read -r url; do
  printf 'URL: "%s"\n' "$url"
done <urls.txt

*Create filename by removing unwanted characters from the URL (changing characters that is not in A-Za-z0-9 to _, removing consecutive _).

*Output filename to terminal
while read -r url; do
  printf 'URL: "%s"\n' "$url"

  outfile="$( tr -s -c 'A-Za-z0-9' '_' <<<"$url" )"
  printf 'File: "%s"\n' "$outfile"
done <urls.txt

*Use dirb and direct output to file
while read -r url; do
  printf 'URL: "%s"\n' "$url"

  outfile="$( tr -s -c 'A-Za-z0-9' '_' <<<"$url" )"
  printf 'File: "%s"\n' "$outfile"

  dirb "$url" /usr/share/wordlists/dirb/small.txt -o "$outfile"
done <urls.txt

My version does a bit more sanitization of the filename than just removing forward slashes.
Also, the echo $i will invoke filename globbing (test with i='*').
Since I don't have an example from your urls.txt file, it hard to say anything more about it.


text:
Q: CRC16 code from Java to PHP How to convert the Java CRC16 code to PHP code? PHP doesn't accept byte and >>>
public static int CRC16(final byte[] buffer) {
        int crc = 0xffff;

        for (int i = 0; i < buffer.length; i++) {
            crc = ((crc >>> 8) | (crc << 8)) & 0xffff;
            crc ^= (buffer[i] & 0xff);
            crc ^= ((crc & 0xff) >> 4);
            crc ^= (crc << 12) & 0xffff;
            crc ^= ((crc & 0xff) << 5) & 0xffff;
        }
        crc &= 0xffff;

        return crc;
    }

A: Replace crc >>> 8 with (crc >> 8) & 0xff.


text:
Q: Use multiple mongo DBs in same application for same model & same Repository I need to implement Spring boot - MongoDb application where There are 2 mongo DBs which have exact same database name & collections. Based on User making a request, i need to choose whether to fetch data from DB1 or DB2 (only difference in mongo URI host - IP).
E.g. I need some way to create 2 mongoTemplates like mTempA & mTempB in my Repository & based on some condition, use either of the template to execute query as below:
@Repository
public class MyCustomRepository {

private Logger logger = LoggerFactory.getLogger(MyCustomRepository.class);

@Autowired
private MongoTemplateA mongoTemplateA;// Need to know if this is possible & how

@Autowired
private MongoTemplateB mongoTemplateB;// Need to know if this is possible & how

public List<MyModel> findByCriteria(MyRequest request) {
    List<MyModel> result;
    //Query query = <build query based on request>

    if (request.getUserType().equals("A")) {
        result = mongoTemplateA.find(query, MyModel.class);
    } else {
        result = mongoTemplateB.find(query, MyModel.class);
    }

    logger.debug("Result fetched with {} records", result.size());
    return result;
}
}

I don't want to have 2 separate Repo (Class or Interfaces) or different models to be used. Just want to have 2 different mongoTemplates to be injected in single repo.
Is this possible? If yes, please give some example code.
I have followed below tutorial:
https://dzone.com/articles/multiple-mongodb-connectors-with-spring-boot

A: As rightly pointed out by @Lucia, below is how it can be done:

*

*Have 2 different configuration placeholders

@Configuration
@EnableMongoRepositories(basePackages = "com.snk.repository", mongoTemplateRef = "mongoTemplateA")
public class MongoConfigA {
    // Configuration class for DB 1 access
}

@Configuration
@EnableMongoRepositories(basePackages = "com.snk.repository", mongoTemplateRef = "mongoTemplateB")
public class MongoConfigB {
    // Configuration class for DB 2 access
}

*Get one class which will help in reading custom properties for mongo db properties in application.properties:

@ConfigurationProperties(prefix = "mongodb")
public class MultipleMongoProperties {

    private MongoProperties adb = new MongoProperties();
    private MongoProperties bdb = new MongoProperties();

    public MongoProperties getAdb() {
        return adb;
    }

    public MongoProperties getBdb() {
        return bdb;
    }
}

*Add a configuration class to create mongoTemplates:

@Configuration
@EnableConfigurationProperties(MultipleMongoProperties.class)
public class MultipleMongoConfig {

    @Autowired
    private MultipleMongoProperties mongoProperties = new MultipleMongoProperties();

    @Bean(name = "mongoTemplateA")
    @Primary
    public MongoTemplate mongoTemplateA() {
        return new MongoTemplate(aDbFactory(this.mongoProperties.getAdb()));
    }

    @Bean(name = "mongoTemplateB")
    public MongoTemplate mongoTemplateB() {
        return new MongoTemplate(bDbFactory(this.mongoProperties.getBdb()));
    }

    @Bean
    @Primary
    public MongoDbFactory aDbFactory(final MongoProperties mongo) {
        return new SimpleMongoDbFactory(new MongoClientURI(mongo.getUri()));
    }

    @Bean
    public MongoDbFactory bDbFactory(final MongoProperties mongo) {
        return new SimpleMongoDbFactory(new MongoClientURI(mongo.getUri()));
    }
}

*Add below decelerations to your service/repository:

    @Autowired
    @Qualifier("mongoTemplateA")
    private MongoTemplate mongoTemplateA;

    @Autowired
    @Qualifier("MongoTemplateB")
    private MongoTemplate MongoTemplateB;

*Add below properties in your application.properties:

mongodb.adb.uri=mongodb://user:pass@myhost1:27017/adb
mongodb.bdb.uri=mongodb://user:pass@myhost2:27017/bdb

If you have mongo rplica set, URL can be set as:
mongodb.adb.uri=mongodb://user:pass@myhost1,myhost2,myhost13/adb?replicaSet=rsName
mongodb.bdb.uri=mongodb://user:pass@myhost1,myhost2,myhost13/bdb?replicaSet=rsName

Based on your logic, use either of the template.
Thought, there are few catches:

*

*Notice the @Primary annotation, one bean needs to be marked as primary. I haven't find any solution if no template is marked primary.

*If any of the mongo DB is down & application is started/restarted, application will not start/deploy. to avoid this, @Autowired needs to be changed to @Autowired(required = false).

*If any of the mongo DB is down & application is already running, it automatically uses 2nd mongo BD (which is not down). So, even if you want to use A DB, if it's down, requests are processed with B DB & vice-versa.


text:
Q: Reading a custom encoded network stream from a MediaElement control I'm developing a Windows 8 Windows Store app (XAML/C#) in which I have a MediaElement control. The MediaElement control takes as a source either a Uri or a IRandomAccessStream.
In my case I have as input a URI pointing to a custom encoded resource (and the stream is endless, so I need to be able to read it whilst it's downloading).
What I'd like to do is set the source of my MediaPlayer to my url, let the player handle the download, yet be called whenever it needs to read something so I can decode it on the fly.
In Silverlight, a MediaStreamSource would seem to be the way to go but it does not exist in WinRT (a light implementation sample does exist though).
What would be the best way to set that up?

A: The Media extensions sample should be what you are looking for. It explains how to provide your own decoder.

A: Here's the solution:
I started from Microsoft's "MediaStreamSource media extension sample" and then implemented my own MediaStreamSource class in C#.
Yet, using a custom media stream source, I could not reuse the existing download mechanism so I created my own based on WinRT's HttpClient class which worked great.
Final recipe is:

*

*Implement your custom media stream source so the MediaElement can read your file,

*Use the HttpClient class to issue HTTP requests to download my stream chunk by chunk and pass it through my media source to my media element.


text:
Q: facebook log in button error I tried to add facebook log in button in my app, even after successful compiling it is getting crashed in emulator.
following is the error report as per logcat, kindly help me to resolve it out.
Thanks

06-12 15:10:39.983  18518-18518/? I/art﹕ Late-enabling -Xcheck:jni
06-12 15:10:41.167  18518-18528/com.example.prashant.nuhani_go W/art﹕ Suspending all threads took: 361.261ms
06-12 15:10:41.353  18518-18518/com.example.prashant.nuhani_go D/Key Hash:-﹕ gMvqxy6TyRo8c0U4xwDiHZhq8gY=
06-12 15:10:41.363  18518-18543/com.example.prashant.nuhani_go D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
06-12 15:10:41.367  18518-18518/com.example.prashant.nuhani_go D/﹕ HostConnection::get() New Host Connection established 0xb42d68e0, tid 18518
06-12 15:10:41.377  18518-18518/com.example.prashant.nuhani_go D/Atlas﹕ Validating map...
06-12 15:10:41.471  18518-18543/com.example.prashant.nuhani_go D/libEGL﹕ loaded /system/lib/egl/libEGL_emulation.so
06-12 15:10:41.472  18518-18543/com.example.prashant.nuhani_go D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_emulation.so
06-12 15:10:41.484  18518-18543/com.example.prashant.nuhani_go D/libEGL﹕ loaded /system/lib/egl/libGLESv2_emulation.so
06-12 15:10:41.502  18518-18543/com.example.prashant.nuhani_go D/﹕ HostConnection::get() New Host Connection established 0xaf0395c0, tid 18543
06-12 15:10:41.530  18518-18543/com.example.prashant.nuhani_go I/OpenGLRenderer﹕ Initialized EGL, version 1.4
06-12 15:10:41.709  18518-18543/com.example.prashant.nuhani_go D/OpenGLRenderer﹕ Enabling debug mode 0
06-12 15:10:41.760  18518-18543/com.example.prashant.nuhani_go W/EGL_emulation﹕ eglSurfaceAttrib not implemented
06-12 15:10:41.760  18518-18543/com.example.prashant.nuhani_go W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xaf0358a0, error=EGL_SUCCESS
06-12 15:10:41.970  18518-18518/com.example.prashant.nuhani_go I/Choreographer﹕ Skipped 33 frames!  The application may be doing too much work on its main thread.
06-12 15:10:41.988  18518-18553/com.example.prashant.nuhani_go E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #4
    Process: com.example.prashant.nuhani_go, PID: 18518
    java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Object.hashCode()' on a null object reference
            at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:746)
            at java.util.concurrent.ConcurrentHashMap.containsKey(ConcurrentHashMap.java:774)
            at com.facebook.internal.Utility.queryAppSettings(Utility.java:825)
            at com.facebook.login.widget.LoginButton$1.run(LoginButton.java:486)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
06-12 15:10:43.514  18518-18518/com.example.prashant.nuhani_go I/Choreographer﹕ Skipped 92 frames!  The application may be doing too much work on its main thread.

and my activity.java code snippet is as follows

package com.example.prashant.nuhani_go;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.content.pm.Signature;

import com.facebook.FacebookSdk;

public class learningActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());

        setContentView(R.layout.activity_learning);
        getUserInfo();
    }

    public void getUserInfo() {

        try{
        PackageInfo info= getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
        for(Signature signature:info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("Key Hash:- ", Base64.encodeToString(md.digest(), Base64.DEFAULT));
        }

        }
        catch (PackageManager.NameNotFoundException e) {}
        catch (NoSuchAlgorithmException e){}

    }

}


text:
Q: Blocking sudoer from deleting file i have a hypotetical problem. Assume that I want to educate a kid aged 7 on linux. I do not want him to waste time with youtube kids channels. So I enforced an extension on chrome that blocks these kind of channels. But while learning linux, he might want to delete force installation config files of extension. How can I give him sudo privilege (so he can learn linux with full experience) while preventing him from deleting that config file?
For some cases he could learn workarounds for situations involving  being sudoer:
Example: for sudo apt install he can actually download source code and compile and install whatever he wants.
But he cannot modify /etc/resolf.conf as a non sudoer.
As far as I know, 2 different sudoers can modify each other's files.
Last but not least,
I do not want to change owner of  files of OS. What is the correct version to do this?

A: What you are asking for is quite impossible, as you are trying to subtract commands from the ALL set. Blacklisting commands for a root-like administrator is fairly impossible and so does man sudoers explain in detail:

SECURITY NOTES
Limitations of the '!' operator
It is generally not effective to "subtract" commands from ALL using the '!' operator.  A user can trivially circumvent this by copying the deired command to a different name and then executing that.  For example:
bill    ALL = ALL, !SU, !SHELLS

Doesn't really prevent bill from running the commands listed in SU or SHELLS since he can simply copy those commands to a different name, or use a shell escape from an editor or other program.  Therefore, these kind of restrictions should be considered advisory at best (and reinforced by policy).
In general, if a user has sudo ALL there is nothing to prevent them from creating their own program that gives them a root shell (or making their own copy of a shell) regardless of any '!' elements in the user specification.

What you could consider:

*

*Define a whitelist instead of a blacklist.

*Run the OS in a VM, then restrict the website accesses via the host.

*Restrict Web access via firewall settings in the router.


text:
Q: What does the shuffling phase actually do? What does the shuffling phase actually do?

Possibility - A
As shuffling is the process of bringing the mapper o/p to the reducer o/p, it just brings the specific keys from the mappers to the particular reducers based on the code written in partitioner

eg. the o/p of mapper 1 is {a,1} {b,1}
the o/p of mapper 2 is {a,1} {b,1}

and in my partitioner, I have written that all keys starting with 'a' will go to reducer 1 and all keys starting with 'b will go to reducer 2 so the o/p would be:

reducer 1: {a,1}{a,1}
reducer 2: {b,1}{b,1}

Possibility - B
Or along with he above process, does it also groups the keys:
So, the o/p would be:

reducer 1: {a,[1,1]}
reducer 2: {b,[1,1]}

In my opinion I think it should be A because grouping of keys must take place after sorting because sorting is only done so that reducer can easily point out when one key is ending and the other key is starting. If yes, when does grouping of keys actually happen, please elaborate.

A: Mappers and Reducers are not separate machines but just separate code. Both, the mapping code as well as the reducing code runs on the same set machines present in the cluster.

So, after all machines in the cluster have run mapper, the results are:

*

*Binned locally on the node (Consider it a "local-grouping"); and,

*Shuffled/Redistributed across all nodes on the cluster.

Consider the step-2 a "global-grouping" because it is done in a manner that all values belonging to one key, go to their assigned unique node.
Now, the nodes run the Reducer code on the (key, value) pairs residing on their memory.


text:
Q: NoDefClassFoundError in Java public void setParent(Window parent) {
    if (true) {
        this.parent = ((abc.InvestRegPropertySeize) parent);
    } else {
        this.parent = ((cde.InvestRegPropertySeize) parent);
    }
}

In above when i compile this code it has succesfully compiled and after complition i manully delete the class file of 'cde.InvestRegPropertySeize' and when i try to run this code the follwing error is occuring.
NoDefClassFoundError of'cde.InvestRegPropertySeize'

But i think this should not be occur because condition always true and no need of 'cde.InvestRegPropertySeize' class file at run time then why it is occuring please tell me the solution.

A: The only way to do something like this is by using reflection. Remove the two casts in your code, so the classes won't be resolved at runtime. Then use reflection to access fields and call methods. Reflection is powerful, but the code is not very readable and it comes with some performance overhead. So think twice before using it.


text:
Q: Template Friending syntax Say I have two Template classes.
template<class T>
class baseclass1
{
    template<class> friend class baseclass2;
}

template<class D>
class baseclass2
{
     template<class T> void foo( D& x, T& y)
     {
          ...
     }
}

The Above code allows all types of baseclass1 to friend all types of baseclass2, a many-to-many relationship. I have two questions,
What is the syntax to allow baseclass1 to friend just the function
baseclass2<class D>::foo<class T>( D& x, T& y).

And, what is the syntax to allow baseclass1 to friend just the function
baseclass2<class D>::foo<class T>( D& x, T& y) where T from baseclass1 matches The T from Function foo.
EDIT
To those who keep claiming you can't friend a template specialization.  This code works
template<class cake>
class foo
{
    public:
        static void bar(cake x)
        {
            cout << x.x;
        }
};

class pie
{
    public:
        void set( int y){ x = y; }
    private:
        int x;

        friend void foo<pie>::bar(pie x);
};

class muffin
{
    public:
        void set( int y){ x = y; }
    private:
        int x;

    friend void foo<pie>::bar(pie x);
};

int main
{
        pie x;
        x.set(5);
        foo<pie>::bar(x);

        muffin y;
        y.set(5);
        //foo<muffin>::foo(y); //Causes a compilation Error because I only friended the pie specialization
}

Even notice where muffin friends the wrong foo, and still causes a compilation error.  This works with both functions and classes. I am totally willing to accept that this isn't possible in my specific situation (It's actually looking more and more that way)  I'd just like to understand why.

A: Befriending all possible specializations of baseclass2<D>::foo is rather easy:
template<class T> class baseclass1;

template<class D>
class baseclass2{
public:
  template<class T>
  void foo(D&, T&){ baseclass1<T> x; x.priv_foo(); }
};

template<class T>
class baseclass1{
  template<class D>
  template<class U>
  friend void baseclass2<D>::foo(D&, U&);

  void priv_foo(){}
};

template<class T>
class baseclass1{
  template<class D>
  template<class U>
  friend void baseclass2<D>::foo(D&, U&);
};

Live example.
A forward declaration of baseclass2 (so baseclass1 knows that baseclass2 exists and is a template) and two templates, one for the class, one for the function. It also looks like this for out-of-class definitions for function templates of class templates. :)
Befriending specifically baseclass2<D>::foo<T> is not possible, however, or I can't find
the correct syntax for it.
A workaround might be some global function that forwards the access and together with the passkey pattern, but meh, it's a mess (imho):
template<class D> class baseclass2;

template<class D, class T>
void baseclass2_foo(baseclass2<D>& b, D&, T&);

template<class D, class T>
class baseclass2_foo_key{
  baseclass2_foo_key(){} // private ctor
  friend void baseclass2_foo<>(baseclass2<D>&, D&, T&);
};

template<class T>
class baseclass1{
public: // public access, but only baseclass2_foo can create the key
  template<class D>
  void priv_foo(baseclass2_foo_key<D, T> const&){}
};

template<class D, class T>
void baseclass2_foo(baseclass2<D>&, D&, T&){
  baseclass1<T> x;
  x.priv_foo(baseclass2_foo_key<D, T>());
}

template<class D>
class baseclass2{
public:
  template<class T>
  void foo(D& d, T& t){ baseclass2_foo(*this, d, t); }
};

Live example.

A: AFAIK you may specify all instantiation of foo as friend but not an specific instantiation:
template< class T >
class C1 {
public:
    template< class Q > void foo( T& x, Q& y ) {
    }
};
template< class T >
class C2 {
    template< class Y >
    template< class Q > friend void C1<Y>::foo( Y&, Q& );
};


text:
Q: For comprehension that has to handle 2 optional values and return a Option[T] The below code works fine, but as you can see the 2nd clause in the for comprehension has a call that is unsafe.
case class ProductView(product: Product, stores: List[Store], warehosue: Option[Warehosue])

def loadView(...): ConnectionIO[Option[ProductView]] =
for {
   product <- getProductById(id)  // ConnectionIO[Option[Product]]
   warehouse <- getWarehouse(product.get.warehouseId.get.id) // ConnectionIO[Option[Warehouse]]
   stores <- loadStores(...)     // ConnectionIO[List[Store]]
} yield product map { p =>
    ProductView(p, stores, warehouse)
}

I tried to make that a safe call, but my types don't seem to line up.
   warehouse <- getWarehouse(product.get.warehouseId.get.id)

How can I improve this, if any of the options is a None, I just want to return a None.
This is suppose to return a Option[Warehouse]
I tried this:
warehouse <- product.map(p => p.warehouseId.map(id => getWarehouse(id)))

Hoping someone can help with this part of my for comprehension.

A: The easiest way is using OptionT and flatTraverse
def loadView(id: Int):
  ConnectionIO[Option[ProductView]] =
    (for {
      product <- OptionT(getProductById(id))
      warehouse <- OptionT.liftF(product.warehouseId.flatTraverse(getWarehouse))
      stores <- OptionT.liftF(loadStores(...))
    } yield ProductView(product, stores, warehouse)).value

Also alternative variant without OptionT
  def loadView(id: Int): ConnectionIO[Option[ProductView]] = {
    getProductById(id).flatMap {
      _.traverse { product =>
        for {
          warehouse <- product.warehouseId.flatTraverse(getWarehouse)
          stores <- loadStores(...)
        } yield ProductView(product, stores, warehouse)
      }
    }
  }