text:
Q: Can i put special characters like ® in the .resx file? I have created a ProductResources.resx file. The name and value fields contain the ® character. THis is the R with a circle around it. It is a reg trademark. Obviously this needs to be there. An the resource file itself gives a red circle with a question mark inside it. Please help.

A: Depending on the encoding you declare for the resx XML, you can probably use one of the following:
   ®      (iso-8859-1  or utf-8)
   ™     (unicode)

A: here's what you must do:

*

*add a app_local_resources folder(right click on your project --> add asp.net folder)

*name the resource folder as the following: PageName.aspx.resx

*add the button name and property ( eg. Button1.Text) in the resource file name field

*copy (by just highlight the registered trade mark from any source and copy it, paste in the value field from here

*go to your button and add the following such as:
 asp:Button ID="Button1" runat="server" Text="" onclick="Button1_Click" meta:resourcekey="Button1"

alt text http://img7.imageshack.us/img7/2108/59469768.jpg
hope this is what you want :)


text:
Q: Laravel 4 exception handling - same code works in 1 case and not in 2 other cases I am trying to handle a few exceptions in Laravel 4, and the same snippet of code works for one of them but not for the others.
I declared an Exceptions.php file that I added to my composer.json.
In Exceptions.php, I declared the following:
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
Class NotAllowedException extends Exception {};

The following handler, in Exceptions.php, works properly:
// snippet 1
App::error(function(NotAllowedException $e, $code, $needed)
{
return Response::make(View::make('special.error')->with('error', array('headline' => 'Not Allowed',
                          'description' =>'
Your user has not enough privileges to perform the requested operation.
')), 401);

});

When I try to do the same to handle HttpNotFoundExceptions and ModelNotFoundExceptions, the following 2 snippets which are copies of the first do not work and yield an Undefined variable: error error.
// snippet 2
App::error(function(ModelNotFoundException $e)
{
return Response::make(View::make('special.error')->with('error', array('headline' =>'Not Found',
                'description' => '
It seems you have tried to access a page that does not exist.
')), 404);
});

// snippet 3
App::error(function(NotFoundHttpException $e)
{
return Response::make(View::make('special.error')->with('error', array('headline' =>'Not Found',
                'description' => '
It seems you have tried to access a page that does not exist.
')), 404);
});

I was only able to make the NotFoundHttpException work by putting this into global.php:
App::missing(function($exception)
{
return Response::make(View::make('special.error')->with('error', array('headline' =>'Not Found',
                'description' => '
It seems you have tried to access a page that does not exist.
')), 404);
});

But I do not know why it works if I put it there and it does not work if I put it in Exceptions.php.
Trying to put snippets 2 and 3 in global.php yield in both case an Internal Server error.
To recap, Questions:

*

*I think I am following the ModelNotFoundException handling as per Laravel4's documentation; what What am I doing wrong / how to make it work?

*why does the App::missing work only if I put it in global.php ? I fear that I might be missing something important about Laravel's inner workings.

Thanks in advance to anyone who can shed some light on those 2 issues

redpajama_set_name: RedPajamaStackExchange


text:
Q: Code secure protection I wrote an R script on an institutional computer. I saved it on an external device (USB PenDrive) and tested it on a computer not of my institution. When I run it to test it using R from Terminal and from GUI I never saved it on the host computer.
This because it has to remain secret until it will be published. I simply would like to know if R or Unix itself saved it elsewhere while running although I load it directly giving the path of Volumes and so on.
In other words the question is does running an R script off a USB leave any trace of it on the host computer.
P.S.: I checked the R history to look for it but it seems not to be saved.


text:
Q: Error with smarty ( Syntax Error in template ) Error appears on page , I use smarty for template
Error smarty is:
  Fatal error: Uncaught exception 'SmartyCompilerException' with message
 'Syntax Error in template ".\templates\footer.tpl"
on line 72 "var reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;"

Line 72 is ( js ) :
<script type="text/javascript">
    function validateEmail(email) {
        var reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return reg.test(email);
    }
...

A: Use the {literal} tag to escape these parts that may conflict.
I quote:

{literal}
{literal} tags allow a block of data to be taken literally. This is
  typically used around Javascript or stylesheet blocks where {curly
  braces} would interfere with the template delimiter syntax. Anything
  within {literal}{/literal} tags is not interpreted, but displayed
  as-is. If you need template tags embedded in a {literal} block,
  consider using {ldelim}{rdelim} to escape the individual delimiters
  instead.


text:
Q: Simple permutation multiplication of two 4-cycles from $S_4$, specifically, $ (1324)(1423)$. For some reason I am confused on how to multiply these together with $4$ elements. I can do it with $2$ elements but theres a little gap in my logic and I am sure one of you can help me with a simple clarification of where the elements get sent to. Thanks!

A: Let $\sigma=(1324), \tau=(1423)$.
Then from right to left, we have
$$\begin{align}
1&\stackrel{\tau}{\mapsto}4\stackrel{\sigma}{\mapsto}1,\\
2&\stackrel{\tau}{\mapsto}3\stackrel{\sigma}{\mapsto}2,\\
3&\stackrel{\tau}{\mapsto}1\stackrel{\sigma}{\mapsto}3,\\
4&\stackrel{\tau}{\mapsto}2\stackrel{\sigma}{\mapsto}4.
\end{align}$$
Thus $(1324)(1423)={\rm id},$ the identity permutation.

A: I'll add an explanation on how the determine very simply the inverse of a cycle (and thus see instantly that in your case, the cycles are inverses of each other):
If $\gamma=(a_1\,a_2\,\dots\,a_{n-1}\,a_n)$ is any cycle, imagine it consists of $n$ points on a circle, one after the other counterclockwise. The inverse cycle $\gamma^{-1}$ consists of the same points, one after the other, but clockwise, so that we get, always starting with $a_1$:
$$ \gamma^{-1}=(a_1\,a_n\,a_{n-1}\,\dots\,a_2).$$


text:
Q: Finding the smallest element of a binary max heap stored as Ahnentafel array I have a binary max heap (largest element at the top), and I need to keep it of constant size (say 20 elements) by getting rid of the smallest element each time I get to 20 elements. The binary heap is stored in an array, with children of node i at 2*i and 2*i+1 (i is zero based). At any point, the heap has 'n_elements' elements, between 0 and 20. For example, the array [16,14,10,8,7,9,3,2,4] would be a valid max binary heap, with 16 having children 14 and 10, 14 having children 8 and 7 ...
To find the smallest element, it seems that in general I have to traverse the array from n_elements/2 to n_elements: the smallest element is not necessarily the last one in the array.
So, with only that array, it seems any attempt at finding/removing the smallest elt is at least O(n). Is that correct?

A: For any given valid Max Heap the minimum will be at the leaf nodes only. The next question is how to find the leaf nodes of the heap in the array ?. If we carefully observe the last node of the array it will be the last leaf node. Get the parent of the leaf node by the formula
parent node index = (leaf Node Index)/2

Start linear search from the index (parent node index +1) to last leaf node index get the minimum value in that range.
FindMinInMaxHeap(Heap heap)
   startIndex = heap->Array[heap->lastIndex/2]
   if startIndex == 0
          return heap->Array[startIndex]
   Minimum = heap->Array[startIndex + 1]
   for count from startIndex+2 to heap->lastIndex
            if(heap->Array[count] < Minimum)
                Minimum := heap->Array[count]
   print Minimum

A: There isn't any way I can think of by which you can get better that O(n) performance for finding and removing the smallest element from a max heap by using the heap alone. One approach that you can take is:
If you are creating this heap data structure yourself, you can keep a separate pointer to the location of the smallest element in the array. So whenever a new element is added to the heap, check if the new element is smaller. If yes, update the pointer etc. Then finding the smallest element would be O(1).
MBo raises a good point in the comment about how to get the next smallest element after each removal. You'll still need to do the O(n) thing to find the next smallest element after each removal. So removal would still be O(n). But finding the smallest element would be O(1)
If you need faster removal as well, you'll need to also maintain a min-heap of all the elements. In that case, removal would be O(log(n)). Insertion will take 2x time because you have to insert into two heaps and it will also take 2x space.
By the way, if you have only 20 elements at any point of time, this is not really going to matter much (unless it is a homework problem or you are just doing it for fun). It would really matter only if you plan to scale it to thousands of values.

A: There is minmax heap data structure: http://en.wikipedia.org/wiki/Min-max_heap . Of course, it's code is rather complex, but with two separate heaps we have to use a lot of additional space (for the second heap, for maintaining one-to-one mapping) and to do the job twice.


text:
Q: How to do basic auth to acces external url and advoid System.HttpResponse[Status=Forbidden, StatusCode=403] I have a basic auth which I have working with Postman but when I do this with apex I get an Forbidden error. The variables userKeyVal and  userSecretVal are filled correctly, my url is correct and I granted acces trough remote site setings. What am I missing.
Postman
    **Key**             **Value**
    Content-Type    application/json
    Authorization   Basic AAAAAAAAAAAAAAAAAAAAAAAAAAA==

Update(not needed):
    client_id       123456789
    client_secret   BBBBBBBBBBBBBBBBBBBB

Apex
  @TestVisible static Boolean doCallout = true;
    @future(callout=true)
    //Get Stock
    public static void  getStock() {
        if(doCallout) {
        fetchConfiguration();
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            request.setEndpoint(UrlVal +'stock/?');
            request.setMethod('GET');
            request.setHeader('Content-Type','application/json');

            Blob headerValue = Blob.valueOf(userKeyVal + ':' + userSecretVal);
            String authorizationHeader = 'BASIC ' +EncodingUtil.base64Encode(headerValue);
            request.setHeader('Authorization', authorizationHeader);

            HttpResponse response = http.send(request);
            if (response.getStatusCode() == 200) {
            System.debug('response: ' + response);
            }
        }
    }

A: For someone how bumps into this. Im my case the code was working properly. The Ip addresses of Salesforce needed to be whitelisted on the other end.


text:
Q: How to add border to custom marker icon in Angular2, agm-marker?
Hi everyone, I need help in this. I am trying this from yesterday. Actually my requirement is to add custom marker icons dynamically to each lat/lng and there are additional values with each marker icon like a "color name" which I have to use as border color.
In agm-marker I can set url and icon height/width in [iconUrl] as
[iconUrl]='{
  "url":  imgurl,
  "scaledSize": {
      "height": 100,
      "width": 100
  }
}'

but I unable to find anything in which I can add border to the marker icon.
However I have done this before using Rickmarker script in javascript.
Below is the screenshot of desired output

A:
ISSUE RESOLVED :)

agm-overlays
It helped me to achieve required output. Thanks to the developer.


text:
Q: Setting up two seperate stores that share the same inventory We have 2 stores in Magento, one for wholesale and one for retail. Both stores sell the same products, except the wholesale store will be selling only one category of the overall products.
We want the inventory to be shared between the two stores, except they are totally independent of each other.
Just to explain a scenario:
If I have 100 of the same product available, I want the 100 to be available in both wholesale AND retail stores (Lets say 70 are available in the wholesale store, and 30 in the retail store).  If a wholesale buyer purchases 30 in the wholesale store, immediately only 70 will be available in both stores, leaving 40 available in the wholesale store and 30 will still be left in the retail store.
We're currently on Magento Enterprise ver. 1.12.0.1
What extensions would be needed to set this up, or can Magento do this by default?

A: This is a magento default functionality. You would set different root categories for the two websites you would be creating. The stock is automatically shared unless you take actions to make magento behave different.


text:
Q: Using multiple .Paginate ranges with Hugo I'm struggling in creating multiple ranges using hugo.
 {{ range (.Paginate (where site.RegularPages "Section" "research")).Pages }}
    {{ partial "research-card" .}}
  {{ end }}

  {{ range (.Paginate (where site.RegularPages "Section" "services")).Pages }}
       {{ partial "services-card" .}}
  {{ end }}

I want to use each of these to create cards for different sections however they are in the same html file. The issue I am having is that when I add the second range it removes the cards from the first one and if I create pages for each I get nil variable errors.
Is there a way to use more than one range on the same page in hugo to create a home page that loads different sections?

A:
The error message is pretty clear: It is not supported with two paginagors on one page, "/page/1" then … what do we do with the second? We may make some magic in this department in the future, but that is a big maybe. You will have to figure a way to exclude one or both of the paginators.

Says Bjørn Erik Pedersen here.

A: You can not use .Paginate with different parameters on the same page. As per the documentation, it can be used only once per page.

If you call .Paginator or .Paginate multiple times on the same page,
you should ensure all the calls are identical. Once either .Paginator
or .Paginate is called while generating a page, its result is cached,
and any subsequent similar call will reuse the cached result. This
means that any such calls which do not match the first one will not
behave as written.

https://gohugo.io/templates/pagination/


text:
Q: How to get ImageView scale to fill the layout as much as the width permits What I want is for the ImageView to scale with the same ratio to fill the layout without being cropped. Since the width is going to match first, effectively, this means scaling until the width is maximized.
My code is:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display);
    ImageView img = findViewById(R.id.displayImg);
    img.setImageBitmap(bmp); // bmp is a public static Bitmap set by another class
    img.setRotation(90);
    img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}

My layout is:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/displayImg" />

</android.support.constraint.ConstraintLayout>

As per Android ImageView ScaleType: A Visual Guide CENTER_INSIDE should

Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).

The black image is what I'm currently, and I've drawn what I believe I should be seeing instead (as you can tell, I'm the modern-day Michelangelo).

A: Add these two lines to your ImageView:
android:scaleType="fitXY"
android:adjustViewBounds="true"
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"
        android:id="@+id/displayImg" />

A: wrap_content if the reason why.... change that to fill_parent or match_parent.
Take a look at this:
https://developer.android.com/reference/android/widget/ImageView.ScaleType.html

CENTER_INSIDE Scale the image uniformly (maintain the image's aspect
  ratio) so that both dimensions (width and height) of the image will be
  equal to or less than the corresponding dimension of the view (minus
  padding).

If the ratio of your image is off, it wont stretch.
Java
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);

XML
android:scaleType="fitCenter"

side note: fillXY might be better.

A: You may acheive your desired result by making the dimensions of the ImageView match to the parent layout and apply fitCenter as a scaleType so it fills the view without losing aspect ratio:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
   <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitCenter"
        android:id="@+id/displayImg" />
</android.support.constraint.ConstraintLayout>

A: I think you use wrong value. Try android:scaleType="fitXY" on xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/displayImg"
        android:scaleType="fitXY" />

</android.support.constraint.ConstraintLayout>

You don't need set again scaleType on activity.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display);
    ImageView img = findViewById(R.id.displayImg);
    img.setImageBitmap(bmp); // bmp is a public static Bitmap set by another class
    img.setRotation(90);
    //img.setScaleType(ImageView.ScaleType.ImageView.ScaleType.FIT_XY); You don't need this
}


text:
Q: Network analyzing tools I am doing a project in collage. My project is to compare two different simulators, one id GNS3 and the other OPNET. what I have to do is generate traffic through the simulators and measure it. I will be using the same network on both simulators. two switches and two routers with two nodes. Wireshark is a good tool, but I would like something more graphical if can get it.

A: I don't know what kind of analyzing you want to perform, but I think getting a Kali Linux system (works also live) would be the best, as it contains by default numbers of tools for network analysis (even some of that kind that would be illegal to use if you don't own the network you perform it onto, or at least have permission to do so). I think the most famous app there for network analysis is wireshark.


text:
Q: Не работает альтернативный экранный буфер в Node.js > node --version
v14.3.0
> uname -sr
Linux 5.4.41-1-lts

Не работают ansi escape-коды для создания альтернативного скрин буфера. Терминал поддерживает альтернативный буфер экрана, почти аналогичный код на Python работает.
Делаю так:
let open_screen = () => process.stdout.write("\u001B[?1049h\u001B[H");
let close_screen = () => process.stdout.write("\u001B[?1049l");

open_screen();

let i = 0;
let loop = setInterval(() => {
    process.stdout.write('some text\n');
    i++;
    if (i >= 10) clearInterval(loop);
}, 1000);

close_screen();

A: Оказалась проблема в невнимательности. Может кому-нибудь пригодится, т. к. по данной теме только один модуль на npmjs и тот не понятно как работает...
let open_screen = () => process.stdout.write("\u001B[?1049h\u001B[H");
let close_screen = () => process.stdout.write("\u001B[?1049l");

open_screen();

let i = 0;
let loop = setInterval(() => {
    process.stdout.write('some text\n');
    i++;
    if (i >= 10) {
        clearInterval(loop);
        close_screen();
    }
}, 1000);


text:
Q: "NullInjectorError: No provider for Subscription! Why I get this error in the console? Here is what I'm doing in a componemt:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { interval, Subscription } from 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit, OnDestroy {
  constructor(private firstObsSubscription: Subscription) {}

  ngOnInit() {
    interval(1000).subscribe((count) => console.log(count));
  }

  ngOnDestroy() {
    this.firstObsSubscription.unsubscribe();
  }
}

Component is than bundled into module, which is later injected into another module.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { UserComponent } from './user/user.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  declarations: [AppComponent, HomeComponent, UserComponent],
  imports: [BrowserModule, AppRoutingModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

Apparently, I'm doing something wrong here

A: What you probably want to do is this:
import { Component, OnDestroy, OnInit } from '@angular/core';
import { interval, Subscription } from 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit, OnDestroy {

  private firstObsSubscription: Subscription

  constructor() {}

  ngOnInit() {
    this.firstObsSubscription = interval(1000).subscribe((count) => console.log(count));
  }

  ngOnDestroy() {
    this.firstObsSubscription?.unsubscribe();
  }
}

As others mentioned in the comments: IF you add a parameter to a constructor in an Angular Application, Angular will try to find a dependency of that type which is not available in your case. And probably shouldn't be in this particular case.


text:
Q: Displaying Other values of the row after getting the max of a subquery So I have is this query:
select MAX(C.Sales) as 'NumOfSales'
from
    (select COUNT(SalesOrderID) as 'Sales',
    TerritoryID
    from Sales.SalesOrderHeader
    group by TerritoryID) C

right now it just shows the max of C.Sales
I want to be able to get the Territory of the max value.

A: If you want one record only, then the following should do the job:
MySql:
select COUNT(SalesOrderID) as Sales,
TerritoryID
from Sales.SalesOrderHeader
group by TerritoryID
order by Sales desc limit 1

Sql-Server:
select top 1 COUNT(SalesOrderID) as Sales,
TerritoryID
from Sales.SalesOrderHeader
group by TerritoryID
order by Sales desc

A: Order by descending on taking the top 1 row:
SELECT TOP 1 COUNT(SalesOrderID) AS Sales,
    TerritoryID
FROM Sales.SalesOrderHeader
GROUP BY TerritoryID
ORDER BY Sales DESC

If you need all rows that have the same max amount of sales, it is more involved:
Here is a way to achieve this with some example data:
DECLARE @SalesOrerHeader TABLE
(
    SalesOrderID INT IDENTITY(1,1),
    TerritoryID INT
)

INSERT INTO @SalesOrerHeader (TerritoryID) VALUES
(1),(1),(2),(2),(2),(2),(3),(4),(4),(4),(5),(5),(5),(5)

DECLARE @final TABLE
(
    TerritoryID INT,
    NumberOfSales INT
)

INSERT INTO @final
SELECT TerritoryID, COUNT(SalesOrderID) AS NumberOfSales FROM @SalesOrerHeader
GROUP BY TerritoryID

SELECT * FROM @final
WHERE NumberOfSales = (SELECT MAX(NumberOfSales) FROM @final)

OUTPUT:
TerritoryID NumberOfSales
2           4
5           4

A: It should be like this if you want both C.Sales and C.TerritoryID:
select MAX(C.Sales) as 'NumOfSales', C.TerritoryID
from
    (select COUNT(SalesOrderID) as 'Sales',
    TerritoryID
    from Sales.SalesOrderHeader
    group by TerritoryID) C

If you only want TerritotyID you can add this:
Select T.TerritoryID
from
    (select MAX(C.Sales) as 'NumOfSales', C.TerritoryID
    from
        (select COUNT(SalesOrderID) as 'Sales',
        TerritoryID
        from Sales.SalesOrderHeader
        group by TerritoryID) C
    ) T
ORDER BY T.NumOfSales

A: select K.Sales, K.TerritoryID
from(select COUNT(SalesOrderID) as 'Sales',
    TerritoryID
    from Sales.SalesOrderHeader
    group by TerritoryID) K
    inner join (
        select MAX(M.Sales) as 'MostSales'
        from(
            select COUNT(SalesOrderID) as 'Sales'
            from Sales.SalesOrderHeader
            group by TerritoryID) M
        ) MaxSales on K.Sales = MaxSales.MostSales

This the solution that I came up with after a little more research


text:
Q: Piecewise linear function reduces to threshold function? I was reading a book where piecewise function is defined as

where varphi is the peicewise function

It says the special forms of piecewise-linear function is :

*

*A linear combiner arises if the linear region of operation is maintained without running into saturation

*The piecewise-linear function reduces to a threshold function if the amplification factor of the linear region is made infinitely large
I tried to understand no 1 as the function value will rise if the adder output value of NN sticks to this area: ( -.5 to .5 ) :

not in <-.5 and >.5 region. I don't know if that's correct.
As for no 2, i have no idea what is being implied. A threshold function is presented in the book as :

What is "amplification factor" and how it behave like threshold function when made infinitively large ?


text:
Q: making a simple sytem call for linux 2.6.39 kernel I am learning to make a simple system call from this website.
When i go to my "/usr/src" directory, I see 2 folders
1) Linux
2) Linux-Source-2.6.39.4
To which one should i make changes in order to make my system call ?

A: Neither.  Download a fresh copy of the kernel source code, extract it into your home directory, and do your development work there using your normal user account.  You only need root to install the kernel after you compile it.
The root-owned files in /usr/src are probably associated with the stock kernel that came with your system, and shouldn't be used for development.  Especially since you'd have to do your development as root, just to have write permission.


text:
Q: DatetimeIndex cannot perform the operation mean I'm trying to implement a line of best fit to a plot from a pandas Dataframe.
I get the error 'DatetimeIndex cannot perform the operation mean' and this is what my dataframe looks like:
      date  new builds  new houses  new homes  help to buy
0   2014-06-08       4          29         79           12
1   2014-06-15       4          31         79           11
2   2014-06-22       5          31         80           12
3   2014-06-29       5          29         81           11
4   2014-07-06       5          31         82           12
5   2014-07-1        5          33         82           12
6   2014-07-20       4          32         85           12
7   2014-07-2        5          33         89           13

This is the code i'm using to try and plot a line of best fit
sns.regplot(x='date',y='new builds',data=data, fit_reg=True)


text:
Q: Linearisation of a group If $G$ is a connected  Lie group  acting on a vector $\mathbb{C}$-space $V$  then it is well known that the algebra of invariants  $\mathbb{C}[V]^G$ coincides with  the algebra of invariants $\mathbb{C}[V]^L$ of  corresponding Lie algebra $L.$
Question. Let now $G$ be a finite group, $V$ be its representation. Is there exists a Lie algebra $L$ and its representation on $V$ such that $\mathbb{C}[V]^G=\mathbb{C}[V]^L$?
It is easy to see  that it impossible  for symmetric group $S_n$. But maybe there are classes of finite groups for which can be found the positive answer?
Edit. Let $V=< v_1,v_2,\ldots,v_n >$  be standard representation of the symmetric group $S_n.$ Suppose that there exist a derivation $D=f_1 \frac{\partial}{\partial x_1}+\cdots+ f_n \frac{\partial}{\partial x_n}, f_i \in S(V)$  of the symmetric algebra $S(V)$ such that $D(I)=0$ for all $I \in \mathbb{C}[V]^{S_n}$.
Let $I_1,I_2,\ldots, I_n \in S(V)$ be a minimal generating set for $\mathbb{C}[V]^{S_n}.$  Since $D(I_k)=0, \forall k,$  we get  the system of polynomial equations on $f_1,f_2,\ldots,f_n:$
$$
f_1 \frac{\partial I_1}{\partial x_1}+\cdots+ f_n \frac{\partial I_1}{\partial x_n}=0,\\
f_1 \frac{\partial I_2}{\partial x_1}+\cdots+ f_n \frac{\partial I_2}{\partial x_n}=0,\\
\ldots \\
f_1 \frac{\partial I_n}{\partial x_1}+\cdots+ f_n \frac{\partial I_n}{\partial x_n}=0.
$$
The Jacobian of system of invariants $I_1,I_2,\ldots, I_n$ is not zero. It follows   the  system has only trivial  solution $f_i=0.$

A: You asked for it! Here's the Hilbert series argument. I need to assume that the derivation $D$ is homogeneous, or equivalently comes from extending a linear map $V \to V$. This covers the case of a Lie algebra action on $V$.
First, recall that $\dim S^n(V^{\ast}) = {\dim V + n - 1 \choose \dim V - 1}$ has asymptotic growth rate $\Theta(n^{\dim V - 1})$ for $\dim V$ fixed and $n \to \infty$.
Let $g_n = \dim S^n(V^{\ast})^G$ denote the dimension of the $n^{th}$ graded component of $\mathbb{C}[V]^G$. An explicit expression for the Hilbert series $\sum g_n t^n$ can be obtained from Molien's theorem which shows in particular that the leading term in the asymptotic expansion of $g_n$ is at least $\frac{1}{|G|} n^{\dim V - 1}$ (hence, as above, that $\mathbb{C}[V]^G$ has Krull dimension $\dim V$). There should be a more elementary way to obtain this estimate.
On the other hand, let $D$ be a derivation induced from a linear map $V \to V$. Let $e_1, ..., e_n$ be a Jordan basis of $D$ with generalized eigenvalues $\lambda_1, ..., \lambda_n$. Then the monomial $e_1^{k_1} ... e_n^{k_n}$ in $\mathbb{C}[V]$ is a generalized eigenvector of $D$ with generalized eigenvalue $\sum k_i \lambda_i$. In particular, the $n^{th}$ graded component of $\mathbb{C}[V]^D$ has dimension at most the number of monomials of degree $n$ of generalized eigenvalue $0$. The exponents of these monomials are determined by the kernel of the map
$$\mathbb{Z}^n \ni (k_1, ..., k_n) \mapsto \sum_{i=1}^n k_i \lambda_i \in \mathbb{C}.$$
If at least one of the $\lambda_i$ is nonzero, the kernel of the above map is a submodule of rank at most $n-1$, from which it follows that the dimension $d_n$ of the $n^{th}$ graded component of $\mathbb{C}[V]^D$ has asymptotic growth rate at most as fast as $O(n^{\dim V - 2})$.
If all of the $\lambda_i$ are equal to zero, then $D$ is nilpotent. In this case we need to inspect the action of $D$ on monomials more carefully. Permute the Jordan basis so that $D(e_i)$ is either $e_{i-1}$ or $0$ and so that $D(e_2) = e_1$, and consider the lexicographic order on $\mathbb{C}[V]$ with respect to the $e_i$. Then $D(e_1^{m_1} ... e_k^{m_k})$ has leading term $m_2 e_1^{m_1+1} e_2^{m_2-1} ... e_k^{m_k}$, from which it follows that the image of $D$ acting on $S^n(V^{\ast})$ has dimension at least the number of monomials with $m_1 \ge 1$, or the dimension of $S^{n-1}(V^{\ast})$. The two dimensions are polynomials in $n$ with the same leading term and $d_n$ is their difference, so we again find that the asymptotic growth rate of $d_n$ is at most $O(n^{\dim V - 2})$.

A: Geometric considerations suggest the answer is always no: we expect $\text{Spec } \mathbb{C}[V]^G \cong V/G$ to have dimension $\dim V$, but we expect $\text{Spec } \mathbb{C}[V]^L \cong V/L$ to have dimension at most $\dim V - \dim L$, at least if the action is sufficiently nontrivial.
One proof is as follows. First recall that $\mathbb{C}(V)$ is a Galois extension of $\mathbb{C}(V)^G$, which is in turn the fraction field of $\mathbb{C}[V]^G$.
Lemma: Let $L/K$ be a separable extension and let $D : L \to L$ be a derivation. Then $D$ is uniquely determined by its restriction to $K$. In particular, if $D |_K = 0$, then $D = 0$.
Proof. Let $x \in L$ and let $p(x) = \sum p_i x^i$ be its minimal polynomial over $K$. Then
$$D(\sum p_i x^i) = \sum \left( D(p_i) x^i + i p_i x^{i-1} D(x) \right) = 0$$
hence $D(x)$ is uniquely determined by the $D(p_i)$ as long as $\sum i p_i x^{i-1} \neq 0$. But this is guaranteed by separability. $\Box$
Now, any derivation on $\mathbb{C}[V]$ extends uniquely to a derivation on $\mathbb{C}(V)$, and by the lemma if such a derivation vanishes on $\mathbb{C}(V)^G$ (in particular, if it vanishes on $\mathbb{C}[V]^G$) then it vanishes identically.

Edit: Here is a reinterpretation of the above argument which is closer to the geometric intuition. The above lemma can be adapted to show that the inclusion $\mathbb{C}[V]^G \to \mathbb{C}[V]$ induces an isomorphism on Zariski tangent spaces at any point $v \in V$, where by the Zariski tangent space at a point $p$ of a variety $X$ I mean the space of linear functions $d : \mathcal{O}_{X, p} \to \mathbb{C}$ such that $d(ab) = d(a) b(p) + a(p) d(b)$. On the other hand, if $D : \mathbb{C}[V] \to \mathbb{C}[V]$ is a nonzero derivation, then there exists a point $v \in V$ such that composing $D$ with the evaluation map at $v$ gives a nonzero Zariski tangent vector at $v$, from which it follows that the inclusion $\mathbb{C}[V]^D \to \mathbb{C}[V]$ cannot induce an isomorphism on Zariski tangent spaces at $v$.


text:
Q: Solving a pair of ODEs I'm trying to solve a pair of ODEs for which I've obtained a solution. However, my problem is that my answer is slightly different from mathematica's answer.
$$ \frac{dA}{dt} = \theta - (\mu + \gamma)A, \  \ A(0) = G$$
$$ \frac{dT}{dt} = 2 \mu A - (\mu + \gamma)T, \ \ T(0) = B$$
Using an integrating factor of $e^{(\mu + \gamma)t}$, I got the following solution to the first ODE:
$$ A(t) = \frac{\theta}{\mu + \gamma} + \left(G -\frac{\theta}{\mu + \gamma}\right)e^{-(\mu + \gamma)t}$$
For simplicity, let $\mu + \gamma = \alpha$ such that:
$$ A(t) = \frac{\theta}{\alpha} + \left(G -\frac{\theta}{\alpha}\right)e^{-\alpha t}$$
For the second ODE (again using an integrating factor of $e^{(\mu + \gamma)t}= e^{\alpha t}$ ):
$$ e^{\alpha t}\frac{dT}{dt} + e^{\alpha t}\alpha T = 2 \mu A e^{\alpha t}  $$
$$ T(t)e^{\alpha t}  =  \int 2 \mu e^{\alpha t}\left(\frac{\theta}{\alpha} + \left(G -\frac{\theta}{\alpha}\right)e^{-\alpha t}\right)dt $$
$$ T(t) = \frac{2 \mu \theta}{\alpha^2} + \left(B - \frac{2 \mu \theta}{\alpha^2}\right)e^{-\alpha t} $$
However, when I computed these two ODEs in mathematica, it gave back the following solution:
$$ T(t) = Be^{-\alpha t} + 2G \mu te^{-\alpha t}+ \frac{2 \mu \theta}{\alpha^2} - \frac{2 \mu \theta e^{-\alpha t}}{\alpha^2} - \frac{2 \mu \theta t e^{-\alpha t}}{\alpha} $$
I've tried solving my equation over and over again but I can't seem to understand why my solution is different from mathematica's. The only I thought about was possibly in the substitution of arbitrary constant. Am I missing something obvious here?

A: You forgot the integration constant. Following on from your integral for $T(t)$, we find
\begin{align}
T(t)e^{\alpha t} &= \int 2 \mu e^{\alpha t}\left(\frac{\theta}{\alpha} + \left(G -\frac{\theta}{\alpha}\right)e^{-\alpha t}\right)dt \\
&= \int 2 \mu e^{\alpha t}\left(\frac{\theta}{\alpha}\right) + 2 \mu \left(G -\frac{\theta}{\alpha}\right) dt \\
&= 2 \mu e^{\alpha t}\left(\frac{\theta}{\alpha^{2}}\right) + 2 \mu \left(G -\frac{\theta}{\alpha}\right)t + C \\
\implies T(t) &= 2 \mu \left(\frac{\theta}{\alpha^{2}}\right) + 2 \mu \left(G -\frac{\theta}{\alpha}\right)t e^{-\alpha t} + Ce^{-\alpha t} \\
T(0) &= B \\
&= 2 \mu \left(\frac{\theta}{\alpha^{2}}\right) + C \\
\implies C &= B - 2 \mu \left(\frac{\theta}{\alpha^{2}}\right) \\
\implies T(t) &= 2 \mu \left(\frac{\theta}{\alpha^{2}}\right) + 2 \mu \left(G -\frac{\theta}{\alpha}\right)t e^{-\alpha t} + \bigg(B - 2 \mu \left(\frac{\theta}{\alpha^{2}}\right) \bigg)e^{-\alpha t} \\
&= \frac{2 \mu \theta}{\alpha^{2}} + 2 \mu G t e^{-\alpha t}  - \frac{2 \mu G \theta}{\alpha}t e^{-\alpha t} + B e^{-\alpha t} - \frac{2 \mu \theta}{\alpha^{2}} e^{-\alpha t} \\
&= B e^{-\alpha t} + 2 \mu G t e^{-\alpha t} + \frac{2 \mu \theta}{\alpha^{2}} - \frac{2 \mu G \theta}{\alpha}t e^{-\alpha t} - \frac{2 \mu \theta}{\alpha^{2}} e^{-\alpha t}
\end{align}


text:
Q: How to load .kv files? I started to learn kivy and I also tried to use kivy language, but my program app.py did not read my app.kv file, so all I get is a blackscreen.
I heard that it is possible to load the the .kv file, but I could not find the command.

A: Try this:
from kivy.lang import Builder
Builder.load_file('kivi.kv')


text:
Q: Performance Overhead of AOP I was wondering if there are any major performance issues with using AspectJ if it is being used to intercept every (or just most) method in an application. Of course, performance would also be affected by the advice that got executed on every interception.
For the sake of this example, let's say its very simple advice that runs very quickly and with minimal overhead/no memory leaks. Are there still significant performance killers since every method is being intercepted?

A: It certainly won't accelerate your code.
I've seen horrible results where 19 stackframes had been added between a caller and a callee for an otherwise direct rapid event handling method. Suffice to say AOP is dead in my mind.
If you are lucky, you may have compiled code, which is inlined by the jit compiler and merely adds the actual work you chose to add as if you wrote it in place. Worst cases, like the spring/osgi crap out there, you end up with some unusable snail.


text:
Q: Definition of Lebesgue measure on the Circle $X=\mathbb{R}/\mathbb{Z}$. I was given the following definition:

I feel this is not adequate and would only define Lebesgue on $[0,1]$? (Wikipedia uses a pushforard of the complex exponential) Also later I am given a proof that rotation by $\alpha$, $T:X→ X, T(x) = x+\alpha \mod 1$ is $\mu$-invariant(Lebesgue on circle), but is it enough?

This seems to treat the circle as $[0,1]$ at times which is confusingly inconsistent.

A: I think that the definition is fine. Given an interval $[a, b]$ we have two cases. Either $b-a >=1$ and $\mu([a,b]/\sim) = \mu(X) = 1$, or $0< b-a < 1$ and $\mu([a, b]) = b-a$.
Now, you might wish that the definition treat the case of intervals of the form $[3/4, 1/4]$. To that I would pedantically say something like "do you mean an image of $[3/4, 5/4]$ or of $(-\infty, 1/4]\cup [3/4, \infty)$ or what?"
Then we get to the proof of rotational invariance. Again, I think its fine, so long as we realise that $(a, b)$ is perfectly good description of a subset of $X$ regardless of where $a$ and $b$ are compared to $0$, $1$ or any other integer.


text:
Q: Issue while installing psycopg2 in MacOS for Python3.7 I'm trying to install psycopg2 for Python 3.7 but I'm having a weird (and long) output issue.
I've tried to follow several stackoverflow replies but without success.
This is the code that I've tried.
python3.7 -m pip install psycopg2
  Using cached https://files.pythonhosted.org/packages/23/7e/93c325482c328619870b6cd09370f6dbe1148283daca65115cd63642e60f/psycopg2-2.8.2.tar.gz
Building wheels for collected packages: psycopg2
  Building wheel for psycopg2 (setup.py) ... error
  ERROR: Complete output from command /usr/local/bin/python3.7 -u -c 'import setuptools, tokenize;__file__='"'"'/private/var/folders/yl/jy_t4s4j6ld8y14kxs6_lg8c0000gn/T/pip-install-z93rthie/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/yl/jy_t4s4j6ld8y14kxs6_lg8c0000gn/T/pip-wheel-l54i7ghe --python-tag cp37:
  ERROR: running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.macosx-10.9-x86_64-3.7
  creating build/lib.macosx-10.9-x86_64-3.7/psycopg2
  copying lib/_json.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2
  copying lib/extras.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2
  copying lib/compat.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2
  copying lib/errorcodes.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2
  copying lib/tz.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2
  copying lib/_range.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2
  copying lib/_ipaddress.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2
  copying lib/_lru_cache.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2
  copying lib/__init__.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2
  copying lib/extensions.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2
  copying lib/errors.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2
  copying lib/sql.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2
  copying lib/pool.py -> build/lib.macosx-10.9-x86_64-3.7/psycopg2
  running build_ext
  building 'psycopg2._psycopg' extension
  creating build/temp.macosx-10.9-x86_64-3.7
  creating build/temp.macosx-10.9-x86_64-3.7/psycopg
  gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DPSYCOPG_VERSION=2.8.2 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=110002 -DHAVE_LO64=1 -I/Library/Frameworks/Python.framework/Versions/3.7/include/python3.7m -I. -I/usr/local/Cellar/postgresql/11.2_1/include -I/usr/local/Cellar/postgresql/11.2_1/include/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.9-x86_64-3.7/psycopg/psycopgmodule.o
  gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DPSYCOPG_VERSION=2.8.2 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=110002 -DHAVE_LO64=1 -I/Library/Frameworks/Python.framework/Versions/3.7/include/python3.7m -I. -I/usr/local/Cellar/postgresql/11.2_1/include -I/usr/local/Cellar/postgresql/11.2_1/include/server -c psycopg/green.c -o build/temp.macosx-10.9-x86_64-3.7/psycopg/green.o
  gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DPSYCOPG_VERSION=2.8.2 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=110002 -DHAVE_LO64=1 -I/Library/Frameworks/Python.framework/Versions/3.7/include/python3.7m -I. -I/usr/local/Cellar/postgresql/11.2_1/include -I/usr/local/Cellar/postgresql/11.2_1/include/server -c psycopg/pqpath.c -o build/temp.macosx-10.9-x86_64-3.7/psycopg/pqpath.o
  psycopg/pqpath.c:135:17: warning: implicit conversion from enumeration type 'ConnStatusType' to different enumeration type 'ExecStatusType' [-Wenum-conversion]
                  PQstatus(conn->pgconn) : PQresultStatus(*pgres)));
                  ^~~~~~~~~~~~~~~~~~~~~~
  psycopg/pqpath.c:1710:11: warning: code will never be executed [-Wunreachable-code]
      ret = 1;
            ^
  psycopg/pqpath.c:1815:17: warning: implicit conversion from enumeration type 'ConnStatusType' to different enumeration type 'ExecStatusType' [-Wenum-conversion]
                  PQstatus(curs->conn->pgconn) : PQresultStatus(curs->pgres)));
                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
               ^
  1 warning generated.
  gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch x86_64 -g -DPSYCOPG_VERSION=2.8.2 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=110002 -DHAVE_LO64=1 -I/Library/Frameworks/Python.framework/Versions/3.7/include/python3.7m -I. -I/usr/local/Cellar/postgresql/11.2_1/include -I/usr/local/Cellar/postgresql/11.2_1/include/server -c psycopg/typecast.c -o build/temp.macosx-10.9-x86_64-3.7/psycopg/typecast.o
  gcc -bundle -undefined dynamic_lookup -arch x86_64 -g build/temp.macosx-10.9-x86_64-3.7/psycopg/psycopgmodule.o build/temp.macosx-10.9-x86_64-3.7/psycopg/green.o build/temp.macosx-10.9-x86_64-3.7/psycopg/pqpath.o build/temp.macosx-10.9-x86_64-3.7/psycopg/utils.o build/temp.macosx-10.9-x86_64-3.7/psycopg/bytes_format.o build/temp.macosx-10.9-x86_64-3.7/psycopg/libpq_support.o build/temp.macosx-10.9-x86_64-3.7/psycopg/win32_support.o build/temp.macosx-10.9-x86_64-3.7/psycopg/solaris_support.o build/temp.macosx-10.9-x86_64-3.7/psycopg/connection_int.o build/temp.macosx-10.9-x86_64-3.7/psycopg/connection_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/cursor_int.o build/temp.macosx-10.9-x86_64-3.7/psycopg/cursor_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/column_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/replication_connection_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/replication_cursor_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/replication_message_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/diagnostics_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/error_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/conninfo_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/lobject_int.o build/temp.macosx-10.9-x86_64-3.7/psycopg/lobject_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/notify_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/xid_type.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_asis.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_binary.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_datetime.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_list.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_pboolean.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_pdecimal.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_pint.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_pfloat.o build/temp.macosx-10.9-x86_64-3.7/psycopg/adapter_qstring.o build/temp.macosx-10.9-x86_64-3.7/psycopg/microprotocols.o build/temp.macosx-10.9-x86_64-3.7/psycopg/microprotocols_proto.o build/temp.macosx-10.9-x86_64-3.7/psycopg/typecast.o -L/usr/local/lib -lpq -lssl -lcrypto -o build/lib.macosx-10.9-x86_64-3.7/psycopg2/_psycopg.cpython-37m-darwin.so
  ld: library not found for -lssl
  clang: error: linker command failed with exit code 1 (use -v to see invocation)
  error: command 'gcc' failed with exit status 1
  ----------------------------------------

I would really appreciate if someone could guide me on how to approach this issue.

A: From the output, it looks like a dependency issue.
You have a couple options:

*

*You can go through the output and try to install the missing dependencies

*You can install the binary, but this isn't recommended for production

*Or you can try installing a previous version of psycopg2

Trying this in a clean python 3.7 environment, based on this answer, what worked was specifying psycopg2 2.7.7:
pip install psycopg2==2.7.7

Hope this helps!


text:
Q: How to write Junit tests for this code with 100% code coverage? Junit tests for Spring Boot application.
Does anyone have any suggestions on how I might achieve this using JUnit and Mockito?
@Autowired
JdbcTemplate jdbcTemplate;

public List<Student> getStudentDetails(String department) {

   List<Student> results = new LinkedList<String>();
   results =  jdbcTemplate.query("SELECT * FROM STUDENT WHERE DEPARTMENT = ?", new PreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement preparedStatement) throws SQLException {
            preparedStatement.setString(1, department);
            preparedStatement.setFetchSize(10);
        }
    }, new ResultSetExtractor<List<Student>>() {
        @Override
        public List<Student> extractData(ResultSet rs) throws SQLException {
            List<Student> students = new ArrayList<>();
            while (rs.next()) {
                Student student = new Student<>();
                student.setDepartment(rs.getString("NAME"));
                student.setName(rs.getString("DEPARTMENT"));
                students.add(student);
            }
            return students;
        }
    });
   return results
  }

A: Code that you have is related to database and in my opinion it should be tested using some database. Usual practice is to use embedded database ( e.g. h2 ). People do it, since using unit tests it's not possible to check if query really works, since you don't actually run it. So I would combine integration and unit tests for testing of this class.
Unit test would be something like this:
@ExtendWith(MockitoExtension.class)
class StubTest {

    @Mock
    JdbcTemplate jdbcTemplate;
    @InjectMocks
    Stub stub;

    @Test
    void whenExecuteQuery_thenExtractDataCorrectly() throws SQLException {
        //GIVEN
        ArgumentCaptor<PreparedStatementSetter> setterCaptor = ArgumentCaptor.forClass(PreparedStatementSetter.class);
        ArgumentCaptor<ResultSetExtractor> extractorCaptor = ArgumentCaptor.forClass(ResultSetExtractor.class);
        //WHEN
        stub.getStudentDetails("TEST");
        //THEN
        verify(jdbcTemplate).query(anyString(), setterCaptor.capture(), extractorCaptor.capture());
        //AND
        PreparedStatementSetter setter = setterCaptor.getValue();
        PreparedStatement preparedStatement = Mockito.mock(PreparedStatement.class);
        setter.setValues(preparedStatement);
        verify(preparedStatement).setString(1, "TEST");
        verify(preparedStatement).setFetchSize(10);
        verifyNoMoreInteractions(preparedStatement);
        //AND
        ResultSetExtractor extractor = extractorCaptor.getValue();
        ResultSet rs = Mockito.mock(ResultSet.class);
        when(rs.next()).thenReturn(true).thenReturn(false);
        when(rs.getString(anyString())).thenReturn("TEST","name");
        verifyNoMoreInteractions(rs);
        List<Student> students = (List<Student>) extractor.extractData(rs);
        assertThat(students.get(0).getName()).isEqualTo("name");
        assertThat(students.get(0).getDepartment()).isEqualTo("TEST");
    }
}

Here I'm just capturing arguments with business logic that we send to query method. Then I run overridden methods of arguments and verify that they work as we expect.


text:
Q: how to sort items in a list alphabetically by the letters in their respective names. I am trying to sort values in a list by the letters in their name: I want, for example,  ["8a", "8c", "8b", "8d"] to become ["8a", "8b","8c", "8d"]. Does this have something to do with a key?

A: The answer is easy if the data looks like in your question. If the data is more complex you will have to give the sort method a key which contains only characters from the alphabet.
data =  ["34b", "2a5t", "2a5s", "abcd"]
data.sort(key=lambda x: ''.join(c for c in x if c.isalpha()))
print(data)

This will give you ['abcd', '2a5s', '2a5t', '34b'].
If you want to see how the constructed key looks like you can check it like this:
for value in data:
    print(value, ''.join(c for c in value if c.isalpha()))

34b b
2a5t at
2a5s as
abcd abcd

A: Assuming your format is always number followed by letter, you need to give the sort method a specific key to sort by: in this case you want to sort by the last character. A lot of the other answers are just sorting your list alphabetically using the number followed by letter whereas I get the feeling you only want to sort by the letter. This is one possible way:
 s = ['9d', '12a', '1e']
 sorted_s = sorted(s, key=lambda x:x[-1])   # sorts by the last character of every entry

This will return:
['12a', '9d', '1e']

A: You can accomplish this by sorting it by a list.
list = ["8a", "8c", "8b", "8d"]
list.sort()
print(list)

A: That would solve solve your problem:
_list = ["8a", "8c", "8b", "8d"]
_list.sort()
print _list

Output:
['8a', '8b', '8c', '8d']

A: The .sort() method for lists has been mentioned; there's a sorting function that takes the list as an argument, and returns a sorted list without modifying the list in place:
>>> mylist = ["8a", "8c", "8b", "8d"]
>>> sorted(list)
['8a', '8b', '8c', '8d']
>>> mylist
['8a', '8c', '8b', '8d']

A:
trying to sort values in a list by the letters in their name

The example you mentioned is very simple. Based on your requirement, below is the code using re.findall() and sorted() to sort based on letters in any order within string:
>>> import re
>>> s = ['a9d', '1a2ba', '1e2s', '1b3tr']
>>> sorted(s, key=lambda x: re.findall("[a-zA-Z]+", x))
['1a2ba', 'a9d', '1b3tr', '1e2s']  # Sorted based on: aba, ad, btr, es


text:
Q: How should I integrate this function? Thank you for your precious time!
Here is the integration I want to calculate:
$$
s=\int_{0}^{2 \pi} \int_{0}^{2 \pi} e^{-j l_{2} \varphi_{2}} e^{j l_{1} \varphi_{1}} e^{j k \frac{r_{1} r_{2} \cos \left(\varphi_{1}-\varphi_{2}\right)}{r}} \\e^{j k \frac{1}{2 r}\left(r_{1}^{2} \cos ^{2} \theta \cos ^{2} \varphi_{1}+r_{2}^{2} \cos ^{2} \theta \cos ^{2} \varphi_{2}-2 r_{1} r_{2} \cos ^{2} \theta \cos \varphi_{1} \cos \varphi_{2}\right)} d \varphi_{1} d \varphi_{2}$$
In which, $l_2$ and $l_1$ are integers, and $r_1$, $r_2$, $r$, $k$ and $\theta$ are constants.
I though this formula has something to do with the bessel function of the first kind, so I tried to use it:
$$J_{n}(x)=\frac{1}{2 \pi} \int_{-\pi}^{\pi} e^{i(n \tau-x \sin \tau)} d \tau$$
Let's ignore $\varphi_2$ for a monent:
\begin{align}
&\int_{0}^{2 \pi} e^{-j l_{2} \varphi_{2}} e^{j l_{1} \varphi_{1}} e^{j k \frac{r_{1} r_{2} \cos \left(\varphi_{1}-\varphi_{2}\right)}{r}} e^{j k \frac{1}{2 r}\left(r_{1}^{2} \cos ^{2} \theta \cos ^{2} \varphi_{1}+r_{2}^{2} \cos ^{2} \theta \cos ^{2} \varphi_{2}-2 r_{1} r_{2} \cos ^{2} \theta \cos \varphi_{1} \cos \varphi_{2}\right)}d\varphi_1
\\=&e^{-j l_{2} \varphi_{2}} e^{jk\frac{r_{2}^{2} \cos ^{2} \theta \cos ^{2} \varphi_{2}}{2r}}\int_{0}^{2 \pi}  e^{j l_{1} \varphi_{1}} e^{j k \frac{r_{1} r_{2} \cos \left(\varphi_{1}-\varphi_{2}\right)}{r}} e^{j k \frac{1}{2 r}\left(r_{1}^{2} \cos ^{2} \theta \cos ^{2} \varphi_{1}-2 r_{1} r_{2} \cos ^{2} \theta \cos \varphi_{1} \cos \varphi_{2}\right)}d\varphi_1
\\=&e^{-j l_{2} \varphi_{2}} e^{jk\frac{r_{2}^{2} \cos ^{2} \theta \cos ^{2} \varphi_{2}}{2r}}\int_{0}^{2 \pi}  e^{j l_{1} \varphi_{1}} e^{j k \frac{2r_{1} r_{2} \cos \left(\varphi_{1}-\varphi_{2}\right)+r_1^2cos^2\theta cos^2\varphi_1-2r_1r_2cos^2\theta cos\varphi_1cos\varphi_2}{2r}} d\varphi_1
\end{align}
Due to the extra terms in $e^{j k \frac{2r_{1} r_{2} \cos \left(\varphi_{1}-\varphi_{2}\right)+r_1^2cos^2\theta cos^2\varphi_1-2r_1r_2cos^2\theta cos\varphi_1cos\varphi_2}{2r}}$, bessel integral can't be performed.
Could you give some advice on this integration? It would really help a lot


text:
Q: PolymerJS: How to use paper-input instead of input I am rebuilding Polymer Todo MVC and right now I want to exchange all normal elements with paper-elements.
This is the input field that accepts and input and adds tasks to an array:
<header id="header">
    <input
        autofocus
        is="td-input"
        id="new-todo"
        placeholder="What needs to be done?"
        on-td-input-commit="addTodoAction"
        on-td-input-cancel="cancelAddTodoAction">
</header>

Works fine. But now I would like to use the paper-input instead like this.
<header id="header">
    <paper-input
        autofocus
        label="What needs to be done?"
        is="td-input"
        id="new-todo"
        on-td-input-commit="addTodoAction"
        on-td-input-cancel="cancelAddTodoAction">
    </paper-input>
</header>

But it does not work. Probably because I bind the previous input field to an td-input element that looks like this:
<script>
(function () {
    'use strict';

    var ENTER_KEY = 13;
    var ESC_KEY = 27;

    Polymer({
        is: 'td-input',

        extends: 'input',

        listeners: {
            'keyup': '_keyupAction',
            'keypress': '_keypressAction'
        },

        _keypressAction: function(e, detail, sender) {
            // Liten for enter on keypress but esc on keyup, because
            // IE doesn't fire keyup for enter.
            if (e.keyCode === ENTER_KEY) {
                this.fire('td-input-commit');
            }
        },

        _keyupAction: function(e, detail, sender) {
            if (e.keyCode === ESC_KEY) {
                this.fire('td-input-cancel');
            }
        }
    });
})();
</script>

Apparently the is="td-input just extends: 'input' and when I want it to exchange paper-input I get:

Failed to execute 'registerElement' on 'Document': Registration failed for type 'td-input'. The tag name specified in 'extends' is a custom element name. Use inheritance instead.

How do I use the paper-input instead of the normal input?
On a sidenote, is there an online editor where I could upload this webapp to make the code editable? Right now I tried Plunker, but the amount of dependencies a normal todo-app with paper-elements needs makes Plunker a bad choice, because it requires too much time.
Anyway, here is the code I am using: Polymer Todo App on TodoMVC.com
And this is the file I want to use the paper-input instead:
td-todos.html

A: What you are trying to do is have a custom element (paper-input) extend another custom element (td-input) which will not work because currently you can only extend native HTML elements in Polymer. See the docs here
What you could do is add an on-keyuplistener to thepaper-input` that calls a function which checks whether the key press was enter or escape then performs the actions you want.
Your HTML:
...
<paper-input
  autofocus
  label="What needs to be done?"
  id="new-todo"
  on-keyup="_checkKeyPress"
</paper-input>
...

JS:
Polymer({
  is: "td-todos",
  _checkKeyPress: function (event) {
    if (event.keyCode === ENTER_KEY) {
      // add/save
    } else if (event.keyCode === ESC_KEY) {
      // cancel
    }
  }
  ...
});


text:
Q: Obtain excel activeworkbook activesheet activecell value and put into a c# winform textbox I'm trying to get a string value that may be in any excel 2010 workbook in the activecell and use that value in a c# applications winform textbox. I'm using vs2015 and excel 2010.
Here's what I've tried with no success.
//Get active excel instance

Excel.Application xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");

//Get active excel workbook

Excel.Workbook xlWorkBook = (Excel.Workbook)xlApp.ActiveWorkbook;

//Get active excel worksheet

Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet;

//Get value for excel

string AValue = xlWorkSheet.Cells[2, 2].ToString();

//Put value in c# winform textbox

txtSearchPattern.Text = AValue;

A: using Microsoft.Office.Interop.Excel
Members of a Range.Cells collection are Range objects, not strings.  Try Cells[x,y].Value2 to retrieve the cell's value.
Also, the currently selected Range object is an application-wide variable Application.Selection, so you should be able retrieve the value of the top-left most cell in the active selection using Application.Selection.Cells[1,1].Value2 without referencing any workbook/worksheets.
Edit: In this instance, you're probably better off using Application.Activecell because Selection can return non-range objects (pictures, etc).

A: I'm not sure if this is the best way but it seemed to allow the program to run and catch the null exception error.
            try
            {
            //Get active excel instance
            Excel.Application xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");

            //Get active excel workbook
            Excel.Workbook xlWorkBook = (Excel.Workbook)xlApp.ActiveWorkbook;

            //Get active excel worksheet
            Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet;

            //Get value for excel
            string AValue = xlApp.ActiveCell.Value2.ToString();

            //Return value to winform textbox
            txtSearchPattern.Text = AValue;
            }

            catch(NullReferenceException)
            {
                MessageBox.Show("ActiveCell was null");
            }

A: Assign the following code to a WinForm having a button (button1) with click event handler (button1_Click) as follows:
using Microsoft.Office.Excel.Interop;

namespace XYZ
{
    public partial class ABC : Form
    {
    Excel.Range activecell = null;
    Excel.Application xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");

    public ABC()
    {
    InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (xlApp.Selection is Excel.Range)
        {
            activecell = xlApp.Selection as Excel.Range;

            //Return value to winform textbox
            txtSearchPattern.Text = activecell.Value2.ToString();
        }
    }
}
}

When you click on a cell in an Excel worksheet which contains a value and subsequently click on button1, the textbox (txtSearchPattern) has its value updated correspondingly.


text:
Q: Do I need a regular expression in C for this string comparison I need all strings starting KAS. For example  KAS, KASDGFT, KASddfdd etc.
But in my case it is just KAS. It does not look at KASGHFJHFT, but it starts with KAS. So I need it. I thought to add a regular expression which means nothing or something after KAS like KAS* in strcmp. But it did not work; what should I be doing?
int function (double a, int b, char *program)
{
   if (strcmp(program,"KAS")==0){
       if (cgpa >= 2 && courses_complete >= 5) {
          return 1;
       }
   } else if (cgpa >= 3 && courses_complete >= 8) {
       return 1;
   }
   return 0;
}

A: Instead of using strcmp, use strncmp which compares the first n characters.
For example, if (strncmp(program,"KAS",3)==0)

A: None of the standard C string functions support regular expressions; you'll have to use something outside of the standard C library (such as the GNU extensions) for regular expression matching.
If you only need to search for the substring "KAS", though, you can use strstr:
if ( strstr( program, "KAS" ) )
{
  // program contains substring "KAS"
}

A: Cannot agree any more with Vicky,
and I try to write the function strncmp
int my_strncmp(const char* str1, const char* str2, unsigned int num)
{
    unsigned int i = 0;
    for( ; (*str1==*str2)&&(*str1!='\0')&&(i<num-1); str1++, str2++, i++)
        ;
    return *str1-*str2;
}

hope can be help


text:
Q: Connect Excel to Oracle database: invalid username/password: logon denied error I'm trying to connect excel to a Oracle database for the first time, but it throws the "ORA-01017: invalid username/password; logon denied" error every time I try to run the code below. The user name and password are definitely correct.
Sub test()

Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Set cnn = New ADODB.Connection
Set rst = New ADODB.Recordset
Dim ConnectionString As String

'ConnectionString
Const hostName = "12.3.4.567"
Const portNo = "1531"
Const srvSID = "mySID"
Const usrID = "myUser"
Const usrPwd = "myPassword"

strDriver = "Provider=OraOLEDB.Oracle;"
strParams = "Data Source=(DESCRIPTION=(CID=MyVbaApp)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" + hostName + ")(PORT=" + portNo + ")))(CONNECT_DATA=(SID=" + srvSID + ")));"
strUser = "UID=" + usrID + ";PWD=" + usrPwd + ";"
ConnectionString = strDriver + strParams + strUser

cnn.Open ConnectionString
End Sub

I can connect to the database from SQL Developer and Dbeaver with no problems. I don't really know what could be the problem, I tried to connect to a db with a  full lower case pwd and username in order to discard that possible issue.
I would be very thankful for any help since idk much about this topic, thanks!


text:
Q: Google Chrome Canary Version 54.0.2830.0 not loading Type script source I am using Google Chrome canary Version 54.0.2830.0. Typescript files are there but those are not loading the code to debug.

A: Posting an answer here so that it may help others.
I was using visual studio Web API project and project settings were not allowing client the access to static files. Due to which chrome was unable to load the Typescript files and map files.
To solve this, i had to add the following line in my web.config file to allow state contents.
<system.webServer>
    <staticContent>
      <mimeMap fileExtension=".ts" mimeType="application/x-typescript" />
    </staticContent>
</system.webServer>


text:
Q: pyqt4 Button image doesnt appear in .app I create an .app using py2app, and the GUI was made with pyqt4, and one of the buttons has an image on ti, but when i run the app the image doesnt appear and when i run it on the terminal it appears, how can I solve this?
Thank you in advance

A: when you launch python setup.py py2app you can pass two extra arguments:
--iconfile path/to/icon.icns
--resources path/to/other/required/stuff

With the first one you set the Dock and App icon, with the second one you embed other needed resources into the .app folder, so that they are available when the app is started.


text:
Q: printf %.4f for IP? I would like to print an IP in fixed way.. example
12.12.1.0
would tured to
012.012.001.000
what's the best method do it ?
printf("%.4f.%.4f.%.4f.%.4f",$ip); ?

A: With zero padding:
$ip = "12.12.1.0";

vprintf("%03d.%03d.%03d.%03d", explode('.', $ip));


text:
Q: Is there any difference between qualified ::toplevel_namespace and unqualified toplevel_namespace? Generally, the difference between ::any_name and any_name should be clear. If preceded by :: the name is always and only looked up in the global namespace.
I was wondering however whether there is an technical(*) difference, given a namespace that I already know to be toplevel (i.e. directly below the global namespace) and where I know that there is no second (nested) namespace (or any name) of the same name.
For example, is there any difference between using ::std::string vs. std::string?

(*) Readability, style and maintenance issues aside.

A:
"For example, is there any difference between using ::std::string vs. std::string?"

Think about such weird situation
LegacyString.hpp
namespace Legacy {
    namespace std {
        class string {
            // ...
        };
    }
}

#include <string>
#include "LegacyString.hpp"

using namespace Legacy;

In this case it would certainly make a difference if you say ::std::string or just std::string in the following code.
And yes, as also stated in your other question's accepted answer, it's perfectly legal to name any construct, be it namespace, class, struct, typedef, etc. std.

As for your question edits:

"and where I know that there is no second (nested) namespace (or any name) of the same name."

If you know this is the case, the both forms are equivalent of course. As you mentioned the resolving of namespaces ends up at global level and will resolve it correctly without the prefixed ::.
IMHO usually we rely on, that at least no one is that stupid, to name any construct std actually. But to cite Einstein:

"Two things are infinite: the universe and human stupidity; and I'm not sure about the the universe."


text:
Q: apache bin rpm from source I have apache source(1.3.x) and I have configured and installed it. Now I need to build a binary rpm with the compiled version that I have so that it can be installed in multiple other machines. The OS and environment I will be installing these will be constant. I understand I need to build a spec file but I am not sure how and what I need to know to build it.
I am just thinking if make install command can be used in some way to get my spec file, or the list of files I need to install, and modifications I need to do to some confs.
The apache 2.0.46, seem to have a spec file along, but for 1.3.x I do not see one.
oh yeha, I do not have the option to move to 2.2.x now, so I have to work with 1.3.x for some time.

A: *

*you can try with CheckInstall. From the homepage:

When make install is done, CheckInstall will create a Slackware, RPM or Debian compatible package

*

*you can look in the archives of an old RedHat (if I remember correctly 4) release which had apache 1.3.x and take the spec file as a start point

*you can take the spec file of the 2.2.x version and adapt it


text:
Q: Swift: How to access a Switch Statement in a Swift file (error: Statements are not allowed at the top level)? I am still new to Swift and coding in general and I am trying to create some kind of option for the user to change colored themes.
But I am clueless on how to access a switch statement in a swift file (or how to encapsulate it) and how to access the set variable?
So far I let the user choose a theme in a settings view controller and the name of the theme is saved in UserDefaults in the key "theme".
In a file called themes.swift I have created a switch statement to check for the names. Each case can obviously set a couple of variables I have declared above the switch statement.
But I get the error that "Statements are not allowed at the top level"?
How can I fix this?
And what can I do to let the switch statement run each time a view controller is presented to check for the correct colors or let it run once a new theme is selected and set the variables? I understand the error message but I have no idea on how to fix this.
For instance this is how I have set up the themes.swift file so far:
import UIKit

var theme = UserDefaults.standard.string(forKey: "themes")

var background: UIColor?
var labelColor: UIColor?
var buttonColor: UIColor?

switch theme {
    case "Red":
        background = UIColor(named: "darkRed")
        labelColor = UIColor(named: "labelRed")
        buttonColor = UIColor(named: "buttonRed")
    case "Blue":
        background = UIColor(named: "darkBlue")
        labelColor = UIColor(named: "labelBlue")
        buttonColor = UIColor(named: "buttonBlue")
    default:
        return
}

So how can I access those variables?
Besides the top level error, can I just access the variables like I would normally do because they are global variables?
Eg. startButton.setTitleColor(buttonColor, for: .normal) ?

A: You are getting this error because you have your switch statement just sitting inside some class or struct (it's not clear where you have this code implemented).  To fix your error you will need to put that switch inside a function.  Perhaps you could create a function called setTheme, like so:
var theme = UserDefaults.standard.string(forKey: "themes")

var background: UIColor?
var labelColor: UIColor?
var buttonColor: UIColor?

func setTheme() {
  //First, check to make sure theme is not nil
  guard let theme = self.theme else { return }
  switch theme {
  case "Red":
    background = UIColor(named: "darkRed")
    labelColor = UIColor(named: "labelRed")
    buttonColor = UIColor(named: "buttonRed")
  case "Blue":
    background = UIColor(named: "darkBlue")
    labelColor = UIColor(named: "labelBlue")
    buttonColor = UIColor(named: "buttonBlue")
  default:
    return
  }
}

Another option would be to make your UIColor? attributes computed variables.  For example:
var background: UIColor? {
  guard let theme = self.theme else { return nil }
  switch theme {
    case "Red": return UIColor(named: "darkRed")
    case "Blue": return UIColor(named: "darkBlue")
    default: return nil
  }
}


text:
Q: border вокруг QWidget У меня есть QWidget с несколькими элементами и мне надо вокруг него сделать серую рамку ( можно через qss ), но я прочитал что QWidget нет border-radius.
Как можно обернуть в рамку QWidget?

A: Используй QFrame если нужна поддержка border-radius.
Например:
setStyleSheet("QFrame#myWidget {border 1px solid; border-radius: 2px}")


text:
Q: Compute $\int_{\mathbb R} (x^2+a^2)^{-s} dx$ I want to solve the integral
$$\int_{\mathbb R} (x^2+a^2)^{-s} dx$$
for $a>0$ whenever it is defined. I guess this sould be the case for $\Re(s)>1/2$. A simple substitution gives me
$$\int_{\mathbb R} (x^2+a^2)^{-s} dx = a^{1-2s} \int_{\mathbb R} (x^2+1)^{-s} dx.$$
Using WolframAlpha I tried a lot of particular values for $s$ and came up with the following formular
$$\int_{\mathbb R} (x^2+a^2)^{-s} dx = \frac{\sqrt{\pi} \ \Gamma(s-1/2)}{a^{2s-1}\Gamma(s)}.$$
Now I want to know if it is correct and see in this case a proof. As already explained it is enough to prove the formular for $a=1$.


text:
Q: I have created a macro using the if function but it doesn't seem to work. What am I misisng? I created a macro to show the following:
If (I3<>0,I3*G3,H3*G3) and this repeats itself for cell N3, R3, V3, Z3 etc.
Option Explicit
Sub Eg()
    Range("J3, N3,R3, V3,Z3,AD3,AH3,AL3,AP3,AT3,Ax3,BB3,XF3,BJ3").Formula = "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"
End Sub

However this doesn't seem to work.
Let me explain a bit more how this should work:
This report needs to be downloaded from an application.
The macro needs to be attached to this report so that when I download the report the macro automatically runs this formula in the appropriate columns.
Also I'll have to populate the spreadsheet for all the rows with this formula.
The columns where the formula should sit are not blank but this needs to be catered for in the report automatically once the macro is run.
What am I missing here?

A: When you use Range.Formula = formulaAsString, and the range refers to multiple cells, you specify the exact formula string as required by (only) the first cell in the range, while appropriately using relative vs. absolute cell references because the assignment to multiple (succeeding) cells will occur as if you were pasting the first cell in the range into the others, exactly as if you'd done a copy & paste without VBA -- you use absolute addressing A1 vs. A$1 vs. $A$1 vs. $A1 etc...  as desired to achieve the right alteration of the formula for the succeeding cells.
For example,
Range ("A1, C1, E1").Formula = "=A2+$A2"

will have the same result as
Range ( "A1" ).Formula = "=A2+$A2"
Range ( "C1" ).Formula = "=C2+$A2"
Range ( "E1" ).Formula = "=E2+$A2"

A: You are mixing up .Formula with .FormulaR1C1! Your string is R1C1 style, but you assign it to the A1 style formula.
Therefore, simply, change it to:
Range("J3, N3,R3, V3,Z3,AD3,AH3,AL3,AP3,AT3,Ax3,BB3,XF3,BJ3").FormulaR1C1 = _
    "=IF(RC[-1]<>0,RC[-1]*RC[-3],RC[-2]*RC[-3])"

or
Range("J3, N3,R3, V3,Z3,AD3,AH3,AL3,AP3,AT3,Ax3,BB3,XF3,BJ3").Formula = _
    "=IF(I3<>0,I3*G3,H3*G3)"

As Erik points out in his answer, also the later will work and adjust the formula for each cell in the same way (which is not necessary in R1C1 as the formula stays the same anyway...)


text:
Q: Records count by field name. Dynamic SQL The task is, to calculate number of records for each column in the table where value is ''.
As an example, TABLE MARA has column 'LVORM' so my query will look like this:
select count(*) from MARA where LVORM = ''

what I have done is created the cursor script:
declare @TABLE_NAME varchar(50), @COLUMN_NAME varchar(50), @NOBLANKS INT, @q  nvarchar(max);

DECLARE cur_headers CURSOR
STATIC FOR SELECT top 50 TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'MARA' and COLUMN_NAME = 'LVORM'
OPEN cur_headers
IF @@CURSOR_ROWS > 0
 BEGIN
 FETCH NEXT FROM cur_headers INTO @TABLE_NAME, @COLUMN_NAME
 WHILE @@Fetch_status = 0
 BEGIN
    set @NOBLANKS = 0;
    select  @q = 'select @NOBLANKS = count(*) from MARA where ' + @COLUMN_NAME + ' = '''' ';
    exec(@q)
    select @NOBLANKS;
    select @q;
 FETCH NEXT FROM cur_headers INTO @TABLE_NAME, @COLUMN_NAME
 END
END
CLOSE cur_headers
DEALLOCATE cur_headers
SET NOCOUNT OFF

For some reason I'm not getting numbers of records back in variable @NOBLANKS
@q returns the right query
Any idea why?

A: You need to pass the variable:
select  @q = 'select @NOBLANKS = count(*) from MARA where ' + @COLUMN_NAME + ' = '''' ';
exec(@q)

=>
EXEC sp_executesql
     N'select @NOBLANKS = count(*) from MARA where ' + @COLUMN_NAME + ' = '''' ',
     N'@NOBLANKS INT OUT',
     @NOBLANKS OUT;

DECLARE cur_headers CURSOR STATIC FOR
SELECT top 50 TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'MARA';
  --AND COLUMN_NAME = 'LVORM';
  -- here the COLUMN_NAME is defaulted to `LVORM` so it should be removed

Semicolons are optional, but it is good to end each statement with them. After all we write code for humans.


text:
Q: KivyMD | List Item print its "text" on_press How can I code a OneLineListItem in KivyMD to print its "text" on a console?
I came up with something like this:
[...]
item = OneLineListItem(text="DEMO", on_press= lambda x: ??????? )
list.add_widget(item)
[...]

I would like to have the word "DEMO" printed on the console after pressing on Item.

A: You can do it like below:
item = OneLineListItem(text="DEMO", on_press=lambda x: print(x.text))


text:
Q: Ionic check multiple Promises are finished I want to run multiple promises and print the result if all promises are finished. Currently I try below approach:
for (let p of this.invoiceProduct) {
  this.promotionSvc.checkPromoBuyNGetN(this.username, p).then(result => {
    console.log(result);
    this.promoBuyNGetNData.push(result);
  })
}

Promise.all(this.promoBuyNGetNData).then(values => {
  console.log(values);
})

In the console, it prints [] for console.log(values) and {id: "e620c8a8-dca8-11e7-8443-2c56dcbcb038", productIdGet: "98926f8c-6afb-11e7-8dd4-2c56dcbcb038", productGet: "Style Laki", getN: 1, description: ""} for console.log(result).
From above result we can see that the Promise.all doesn't work. How should I fix this?

A: Promise.all expects an array of promises. You need to change your for loop to put the promises into this.promoBuyNGetNData.  If I understand you correctly, this code should do what you want.
for (let p of this.invoiceProduct) {
  const promise = this.promotionSvc.checkPromoBuyNGetN(this.username, p);
  promise.then(result => {
    console.log(result);
  });
  this.promoBuyNGetNData.push(promise);
}

Promise.all(this.promoBuyNGetNData).then(values => {
  console.log(values);
});

You can make this cleaner by getting rid of the promise.then console log, and turning the for loop into a map.
this.promoBuyNGetNData = this.invoiceProduct.map(p => this.promotionSvc.checkPromoBuyNGetN(this.username, p));
Promise.all(this.promoBuyNGetNData).then(values => {
  console.log(values);
});

A: you seem to be trying to push the results of the promises in the array and then calling Promise.all.
Promise.all takes an array of promise objects and calls all of them and then fires then on completion of all promises. YOu can do:
promoData:any[]=[];//class variable

for (let p of this.invoiceProduct) {
  this.promoBuyNGetNData.push(this.promotionSvc.checkPromoBuyNGetN(this.username, p));//push the promise function into array
}

Promise.all(this.promoBuyNGetNData).then(values => {
  console.log(values);// all results within values array
  this.promoData=values;
})

And in your HTML,
<tr *ngFor="let p of promoData">


text:
Q: 403 when testing local post request using clj-http I have a route defined as:
(POST "/login" [req] req)

in my httpkit server. I wanted to test this route so I tried to use:
(client/post "http://localhost:3000/login" {})

using clj-http.client, but I just get error 403 (forbidden) when I attempt to run it (in calva). Any one have any ideas? Works fine for GET routes!
EDIT:
As the request of @cfrick, here is a MRE:
server.clj
(ns api.server
  (:require [org.httpkit.server :as server]
            [compojure.core :refer [defroutes GET POST]]
            [ring.middleware.defaults :as default])

(defn auth-start [req]
  {:status 200
     :headers {"Content-Type" "text/html"}
     :body  "<h1> logged-in </h1>"})

(defroutes app-routes
  (GET "/" [] "<h1> Hello </h1>")
  (POST "/login" [req] auth-start)
  (route/not-found "Error, page not found!"))

(defn -main
  "This is our main entry point"
  [& args]
  (let [port (Integer/parseInt (or (env :PORT) "3000"))]
    ; Run the server with Ring.defaults middleware
    (server/run-server (default/wrap-defaults #'app-routes default/site-defaults) {:port port})
    ; Run the server without ring defaults
    ;(server/run-server #'app-routes {:port port})
    (println (str "Running webserver at http://127.0.0.1:" port "/"))))

test.clj
(ns api.test
  (:require [clj-http.client :as client]))

(client/post "http://localhost:3000/login" {})

project.clj dependencies:
:dependencies [[org.clojure/clojure "1.11.1"]
                 ; Compojure - A basic routing library
                 [compojure "1.6.1"]
                 ; Our Http library for client/server
                 [http-kit "2.3.0"]
                 ; Ring defaults - for query params etc
                 [ring/ring-defaults "0.3.2"]
                 ; For testing api routes
                 [clj-http "3.12.3"]]


text:
Q: how to set date through protractor I tried with sendkeys but that is not working.
Below is the code during inspect:
<input _ngcontent-c10="" class="col-md-6 col-lg-6 col-sm-12 col-xs-12 mat-input-element mat-form-field-autofill-control ng-pristine ng-valid ng-touched" date="true" formcontrolname="toDate" matinput="" name="toDate" placeholder="To Date" readonly="" aria-haspopup="true" min="2019-12-23" id="mat-input-1" aria-invalid="false" aria-owns="mat-datepicker-1">
<img _ngcontent-c10="" class="img-calendar" src="./assets/calendar.png">
<mat-datepicker _ngcontent-c10=""></mat-datepicker>

A: It will help to you,
In your .ts file :
date = new Date((new Date().getTime() - 3888000000));

In html file
<mat-datepicker  [startAt]="date" #picker></mat-datepicker>


text:
Q: spring batch job should wait for prometheus to scrape before shutdown We have spring batch jobs running with prometheus as our monitoring system.
When the job is running metrics are being collected just fine, but when the job finish it shutdowns before prometheus manage to collect the metric of "spring.batch.job" which is crucial because it has 'duration' and 'status' tag which indicate wether the job succeeded or failed.
How can I program the job to wait for 'one last scrape' after its done before its shutdown?

A: You can define what action you can do before shutdown using the configuration param in your application.yml
management.metrics.export.prometheus.pushgateway.shutdown-operation
and possible options are listed in org.springframework.boot.actuate.metrics.export.prometheus.PrometheusPushGatewayManager$ShutdownOperation


text:
Q: DAX Power Pivot: "= CONCATENATEX(CALCULATETABLE(" how to avoid duplicates? I've seen similar posts before, but none of the solutions worked for me as my formula is complex and includes filters.
I'm trying to create a new column in a table, concatenating all matches from a column in a different table.(e.g. Order table concatenating all product names associated with a given order)
Full formula: =
CONCATENATEX (
    CALCULATETABLE (
        RoW_SIC_table,
        FILTER (
            RoW_SIC_table,
            RoW_SIC_table[Excel Company ID] = Row_main[Excel Company ID]
        ),
        FILTER ( RoW_SIC_table, NOT ( ISBLANK ( RoW_SIC_table[Broad] ) ) )
    ),
    RoW_SIC_table[Broad],
    ", "
)

I want CONCATENATEX to only concatenate unique values, and I haven't made it work with either DISTINCT or VALUES. Can you help me?

A: How about like this?
Full formula: =
CONCATENATEX (
    CALCULATETABLE (
        DISTINCT ( RoW_SIC_table[Broad] ),
        FILTER (
            RoW_SIC_table,
            RoW_SIC_table[Excel Company ID] = Row_main[Excel Company ID]
        )
    ),
    RoW_SIC_table[Broad],
    ", "
)

A: I used as reference this:

e.g. Order table concatenating all product names associated with a
given order

So what came to my mind is the following model:
SIC Table

Main Table

"Data Model"

Result

ProductsListedByOrderIFBroadISNOTBLANK=
VAR COrderID=SIC[OrderID]
VAR PIDWLineage=
SELECTCOLUMNS(
    CALCULATETABLE(SIC,
    ALL(SIC), SIC[OrderID]=COrderID, NOT(ISBLANK(SIC[Broad]))),
 "ProductID", SIC[ProductID], "ProductName", RELATED(Main[ProductName]))
RETURN
CONCATENATEX(PIDWLineage, [ProductName], ",")


text:
Q: Export from Outlook for Mac 2011 to gmail - Mission impossible? Can anyone tell me how I can export my calendar and contacts from my Outlook for Mac 2011 (I'm using a MacBook Pro) to calendar & contacts on my Google account?

A: This is what I found for doing it 'on the cheap'. This is not flawless by any means, so please don't do this with your eyes closed ;-) Do pay attention to the warning about uploading duplicate entries in Google.
I specifically did this for migrating data up to Google Apps, but having done similar things for my own personal Google account, I don't believe there's much difference.
I decided to write this up because it still seemed like a largely unanswered question out there. The Mac version of Outlook certainly doesn't make any of this much easier, what with formats like OLM! So much so that there are more than a few vendors of OLM to PST conversion software.
[Oh for those of you wondering why I didn't use the Google Apps Migration tool for Exchange (GAMME), it was because our hosted MS Exchange service only gave us limited access.]

Migrating Contacts:
In Outlook:

*

*Go to File -> Export

*Select the "Contacts to a list (tab-delimited text)" radio button

*Note where you've saved that file

In Excel:

*

*Open Excel, then open the file you saved in the last step

*Excel will prompt you with the Text Import Wizard. Click through ensuring that Tab is the selected Delimiter.

*Unfortunately, since the export isn't perfect, it's a good idea to eyeball this list of contacts and ensure that the data appears to be in the right columns. E.g. First names appear in the First Name column, etc.

*Now save the file as a CSV file: click File -> Save As. Select Comma Separated Values (.csv) as the Format (near the top of that list), and save.

*Note where you've saved that file.

In Google Apps:

*

*Navigate to the Contacts section (either via Gmail) or the top navigation menu bar.

*Click the More menu (with the down-arrow next to it) and select Import…

*Use the Choose File button to select the CSV file you saved in the last section, then click Import.

Note: if you need to edit your CSV file and re-import to Google Contacts, it's best to delete all of the contacts from Google before performing the import again. This is because Google doesn't overwrite the original contacts, but creates new contacts, which will create duplicates in most cases.

Migrating Calendar:
In Outlook:

*

*Go to Outlook -> Preferences

*Click Sync Services

*Check the Calendar box and ensure that your main account is checked under "accounts to sync"

*Now close that dialog box (red circle)

*You will get a prompt titled "You have turned on Sync Services". Click OK.

In Calendar:

*

*Open Calendar (used to be called iCal)

*Ensure that your calendar(s) from Outlook are there

*Right-click on the calendars you want to copy and select Export.

*Keep or change the name and click Export

In Google Calendar:

*

*After logging into your Google Apps account, select Calendar from the top menu

*Click the drop-down menu next to the gear icon (top right-hand corner) and select Settings

*Click the Calendars link (top left-hand corner)

*Now you either create a new calendar or import into the default one that uses your name as the title.

*Click Import Calendar

*Browse to the .ics file on your computer which you had previously saved in step #4 above. 6. Select the calendar you want to import into and click Import.

*You should see that some # of events were processed, and then see those events when you browse back to the main Calendar page.

Hope this helps someone out there!

A: You can sync outlook to OS X's built-in Address book and then sync the Address book with your google account.
Outlook > Address Book:
http://www.scrubly.com/blog/index.php/2011/01/how-to-sync-outlook-2011-for-mac-with-mac-address-book/
Address Book > Google:
http://osxdaily.com/2009/12/27/sync-your-mac-address-book-with-google-contacts/


text:
Q: Return Array Element inside of an Object array I have this code below. I want to access the array(named link1 and link2) elements inside of the obj array.
$(function() {
    var storage = chrome.storage.local;
    storage.clear();
    var link1 = 'myLinks1';
    var link2 = 'myLinks2';

    var obj= {};

    obj[link1] = ['www.google.com', 'yahoo.com', 'www.msn.com'];
    obj[link2] = ['www.microsoft.com', 'live.com', 'www.espn.com'];

    storage.set(obj);

    storage.get(null,function(result){
        //returns obj with array of links inside
        console.log(result);
        // Returns array of obj but doesn't contain array of links inside.
        console.log(Object.keys(result));
    });
});

EDIT: I want to be able to access the links such as www.Google.com
Thanks

A: You should be able to get the keys and array values in the result by writing the following for loop
Object.keys(obj).forEach(function(key) {
    console.log(key, obj[key]);
   for (var i in obj[key])
    console.log(obj[key][i]);
});

output:

myLinks1 ["www.google.com", "yahoo.com", "www.msn.com"]
  www.google.com
  yahoo.com
  www.msn.com
  myLinks2 ["www.microsoft.com", "live.com", "www.espn.com"]
  www.microsoft.com
  live.com
  www.espn.com


text:
Q: When I tried to run a node js file .I am getting ReferenceError: XMLHttpRequest is not defined From google search I came to know that it is because XMLHttp not installed(many sites are saying the same reason).I installed that using install xmlhttprequest. I guess it is installed properly .Again the same error is showing .How can I solve that problem.Since I am on my learning period,I don't have much idea about debugging.I have added the code a little and the error pattern obtained while running in terminal.Can somebody give what is happening and what should i do to overcome this error
const setEditModal = (isbn) => {
    const xhttp = new XMLHttpRequest();

    xhttp.open("GET", `http://localhost:3000/book/${isbn}`, false);
    xhttp.send();

Error:
ReferenceError: XMLHttpRequest is not defined
            at loadBooks (C:\Users\Hp\book-list.js:38:19)
            at Object.<anonymous> (C:\Users\Hp\book-list.js:73:1)

A: Ok you installed it but it seams that you did't import it:)
const {XMLHttpRequest} = require("xmlhttprequest");

or
import {XMLHttpRequest} from 'xmlhttprequest'

depending of your version
documentation here


text:
Q: Can the MMSE estimator be just interpreted as Tikhonov regularization? Given an ordinary least squares problem with the normal setup (error Gaussian i.i.d. with $\sigma^2$, $N$ observations and $L$ unknowns):
$$
\mathbf{y} = \mathbf{X}\mathbf{b} + \mathbf{e}
$$
The estimation is given as
$$
\hat{\mathbf{b}} = (\mathbf{X}^T\mathbf{X})^{-1} \mathbf{X}^T \mathbf{y}
$$
The coefficient error (covariance matrix) is given as:
$$
\mathbf{\Sigma_b} = \sigma^2 (\mathbf{X}^T\mathbf{X})^{-1}
$$
The average mean-squared error, i.e., the error between $\mathbf{b}$ and $\hat{\mathbf{b}}$ can be approximated as the average of the cofficient errors (trace):
$$
\overline{\mathrm{MSE}} = \mathbb{E}\{ \|\hat{\mathbf{b}}-\mathbf{b}\|_2^2 \} \approx \frac{1}{L}\sigma^2 \operatorname{Tr} (\mathbf{X}^T\mathbf{X})^{-1}
$$
According to the Gauss-Markov theorem, the Least Squares estimate provides the best linear unbiased estimator which is also the minimum variance unbiases estimator (MVUE) because the noise is Gaussian.
This estimator minimizes the residuals $\|\mathbf{X}\mathbf{b}-\mathbf{y}\|_2^2$ .
Do I understand correctly that this estimator ONLY minimizes the MSE among other unbiased estimators but does not generally minimize the MSE?
Tikhonov regularization provides a biased estimate but can result in lower MSE:
$$
\hat{\mathbf{b}} = (\mathbf{X}^T\mathbf{X} + \mathbf{\Gamma}^T \mathbf{\Gamma})^{-1} \mathbf{X}^T \mathbf{y}
$$
Is it valid to say that Tikhonov regularization minimizes the mean-squared-error (i.e., it is a MMSE estimator) and as such is the best estimator (despite being biased)?
In that case, is the MMSE estimator given by the Tikhonov regularization with $\mathbf{\Gamma} = \sigma \mathbf{I}$?
Is there a relation between Tikhonov regularization and the MMSE estimator?

A: *

*Yes, the OLS is the UMVUE, that is among the unbiased linear estimator it is the best (smallest variance). In general you can tell nothing concrete about the unbiased estimators as this class is is "too big". No contradiction and no surprise that by introducing bias you can get smaller variance, it is called the bias-variance trade-off.
https://en.wikipedia.org/wiki/Bias%E2%80%93variance_tradeoff#targetText=In%20statistics%20and%20machine%20learning,across%20samples%2C%20and%20vice%20versa.

*Take the simple form of Ridge regularization, that is, $\Gamma ^ T \Gamma  = \lambda \mathrm{I}$, in this case if $\lambda$ is very large then the estimators are dominated by its value and not that much by the data itself. That is, they become smaller (biased) in absolute value with lower variance. If you check the univariate case where $y = x\beta + \epsilon$, then the OLS if $\beta$ is
$$
(X'X)^{-1}X'y = \frac{\sum x_i y_i}{ \sum x_i^2}
$$
where the ridge model estimator of $\beta$ is given by
$$
(X'X + \lambda I)^{-1}X'y = \frac{\sum x_i y_i}{ \sum x_i^2 + \lambda}  ,
$$
so
$$
| \hat{\beta} ^{OLS} |\ge | \hat{\beta}^{Ridge} |
$$
and the same with the variance, i.e.,
$$
Var( \hat{\beta} ^{OLS}  ) = \frac{\sigma ^2}{ \sum x_i^ 2} \ge \frac{\sigma ^2 \sum x_i ^2}{ (\sum x_i^ 2 + \lambda )^2} = Var( \hat{\beta} ^{Ridge}).
$$
If you take $\lambda \to \infty$ then you clearly observe the fact that Ridge's estimator and its variance tend to zero.


text:
Q: How to access Neo4j remotely I am hosting a Neo4j server on my laptop, and I am trying to access it via an amazon EC2 instance. I am using Neo4j desktop to run the server.
I've configured my server to accept external traffic:
dbms.default_listen_address=0.0.0.0
dbms.connector.bolt.listen_address=0.0.0.0:7687
dbms.connector.http.address=0.0.0.0:7474

I use a reverse ssh from my laptop -> ec2 instance to expose ports 7474 and 7487. I use a reverse ssh from server -> client because my laptop is private and I don't want to port forward from my public IP.
ssh -R7687:localhost:7687 -R7474:localhost:7474 ec2-user@EC2IP
On my EC2 instance, I am using self.driver = GraphDatabase.driver(bolt://localhost:7687", auth=auth, max_transaction_retry_time=20)to access the database. It fails with error
Failed to establish connection to ResolvedIPv6Address(('::1', 7687, 0, 0)) (reason [Errno 99] Cannot assign requested address))
2022-01-20 00:36:28 neo4j WARNING: Transaction failed and will be retried in 1.6414348276387707s (Couldn't connect to localhost:7687 (resolved to ('127.0.0.1:7687', '[::1]:7687')):


text:
Q: Writting Duplicate Object data to a binary file I'm going to try to keep it as simple as possible. I have a Program that adds values to the table. When a button is clicked it reads values from the table, creates an object and writes to a binary file(.ser).
When I loop trough the list (e.g. 3 times if i added three object values to the table) of the table, then I create an object and write it to a file. But when I read the same file it just reads the same object ( 3 times if I added 3 objects to the Table). Why is it doing that? I'm new to Java any help would be great thanks
Object Structure
public class Empleados implements Serializable {

public int NoEmpleado;
public String ENombre;
public String EApellido;
public String EGrupo;
.
.
Setters and getters
}

Following code runs when I click a button to write to binary file (takes data from a table previously filled with data). I am also closing the file after all of this is done.
            try // open file
            {
                outputS = new ObjectOutputStream(new FileOutputStream( "empleados.ser" ) );
            } // end try
            catch ( IOException ioException )
            {
                System.err.println( "Error opening file." );
            } // end catch

            for (int num = 0; num < tableModel2.getRowCount();num++)
            {
                try
                {

                empleado1.setNumero(Integer.parseInt(tableModel2.getValueAt(num, 0).toString()));
                empleado1.setNombre(tableModel2.getValueAt(num, 1).toString());
                empleado1.setApellido(tableModel2.getValueAt(num, 2).toString());
                empleado1.setGrupo(tableModel2.getValueAt(num, 3).toString());

                int n = empleado1.getNumero();

                if (empleado1.getNumero() > 0)
                {
                    outputS.writeObject(empleado1);
                }
                else
                {
                    System.out.println("Numero debe ser mayor a 0.");
                }
                }
                .
                .
                fallow by rest of catch stataments


text:
Q: PRINTF prevents to enter in low power mode i am testing the low power mode in my bl072z lora board, i call the low power mode function and when i wake up from this state (after a timer set to 20 seconds) the led blinks, everything ok, but if i print a message using PRINTF instead the blink led to know if the board wakes up i never enter in low power mode and just see the PRINTF message in the terminal, why i can't use PRINTF with the low power function?
//does not works

while(1)
{

LPM_EnterLowPower( );
PRINTF("woke up\n\r");

}

//works

while(1)
{

LPM_EnterLowPower( );
BSP_LED_Toggle(LED_GREEN);

}

//works

while(1)
{

LPM_EnterLowPower( );
PRINTF("woke up\n\r");
HAL_Delay(500); //works with this delay but i don't know why

}

//low power function:
void LPM_EnterLowPower(void)
{
 HAL_PWR_EnterSTOPMode ( PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI );
}

i use the "woke up" message to know if i exit from sleep mode, i call the low power function and after 20 seconds i expect to see "woke up" just once in the terminal and then go to sleep again and repeat the process, everything works fine with the led but does not works printing a message,in the terminal i only see (indefinitely):
woke up
woke up
woke up
woke up

A: As soon as PRINTF("woke up"\n\r); is called, you call LPM_EnterLowPower();.
The message "woke up" can't be displayed before the low power function is called, because there's no delay between the two, so low power mode is never entered except for the first time.