text:
Q: Converting a JPA object to XML / JAXB I would like to convert data from a table to an XML file. The data is in the following    format
    Continent   Country     County      Town
    --------------------------------------------------------------
    Africa      Kenya       South       Mombasa
    Africa      Egypt       South       Cairo
    Europe      England     North       Birmingham
    Asia        Japan       South       Tokyo

The resultant XML document that will be produced is similar to the one shown below:
<continents>
    <continent name="Africa">
        <countries>
            <country>
                <countryName>Kenya</countryName>
                <county>South</county>
                <town>Mombasa</town>
            </country>
            <country>
                <countryName>Egypt</countryName>
                <county>South</county>
                <town>Cairo</town>
            </country>
        </countries>
    </continent>
    <continent name="Europe">
        <countries>
            <country>
                <countryName>England</countryName>
                <county>North</county>
                <town>Birminghan</town>
            </country>
        </countries>
    </continent>
    <continent name="Asia">
        <countries>
            <country>
                <countryName>Japan</countryName>
                <county>South</county>
                <town>Tokyo</town>
            </country>
        </countries>
    </continent>
</continents>

What i am planning to do is read the data from the database into a JPA object. This returns a list of the following object
@Entity
@Indexed
@Table(name="TOWN")
public class Town {

    protected String continent;
    protected String country;
    protected String county;
    protected String town;

    @Id
    @Column(name="CONTINENT")
    public String getContinent() {
        return continent;
    }

    public void setContinent(String continent) {
        this.continent = continent;
    }

    @Column(name="COUNTRY")
    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Column(name="COUNTY")
    public String getCounty() {
        return county;
    }

    public void setCounty(String county) {
        this.county = county;
    }

    @Column(name="TOWN")
    public String getTown() {
        return town;
    }
    public void setTown(String town) {
        this.town = town;
    }
}

When i run the call to retrieve the rows from the database, i will get the list in the following format:
List<Town> towns = entityManager.getAllTowns();

To be able to generate the XML file, i have to iterate the list and process each of the "Town" object. I can use DOM but i feel that there will be lots of for loops and if statements to be able to generate the XML document. Is it possible to generate the XML document without having to iterate through the list to build the xml file shown above?
I have converted a JPA object to Jaxb but this was a flat relationship with a one to one mapping (i.e. no child or inner elements in the XML structure). I dont understand how to do the child elements and the conditional rules that would be required for the sample xml file.
I am using JPA/Hibernate with Spring 3. Is it possible to generate the sample xml file or do i need to do it manually (Using for loops and if statements) because of the format of the XML file?
Thanks

A: Take a look at Dozer. Let's say you have one JPA entity class and one JAXB class. Dozer is a framework for making mapping between two such beans. You will however need to specify which attribute should be mapped where.

A: I've generally found it easier to go the other way from what you're doing. That is, generate the JAXB objects using XJC, and then use an orm.xml file to do the JPA mapping to the database. You can customize the generated Java objects using standard XJC plugins and JAXB configuration files.
This approach has the advantage of maintaining only one set of Java classes (maybe with some supplemental child classes of the JAXB model), and it also has a tendency to promote a more stable XML contract.
For some reason, people have a tendency to look down upon using a separate XML file for ORM. There are cases, though, where it makes sense, and I believe that this is one of those cases.


text:
Q: How can I screenshot a custom URL page and send it back into the channel? I am trying to make a screenshot using puppeteer and send it back into the channel where the command was typed. Anyways I can't do it, so please help me.
const Discord = require("discord.js");
const fetch = require('node-fetch');
const cheerio = require("cheerio");
const puppeteer = require('puppeteer');
const client = new Discord.Client();

module.exports =  {

  async run(client, message, args) {
    const browser = await puppeteer.launch();

    const url = message.client;
    const page = await browser.newPage();
    await page.goto(url);

    console.log(await page.content());
    await page.screenshot({path: 'screenshot.png'});

    let screenshot = await page.screenshot();
    await browser.close();

    message.channel.send("Screenshot", {files: [screenshot]});
    }

  }

A: It seems that you may have made a typo.
const url = message.client;

should probably be
const url = message.content; // or something similar?

message.client is a Client object, and even as a string, is [object Object]. These are not valid URLs.
As a result, an UnhandledPromiseRejectionWarning should have been logged to the console, stating that the URL could not be deserialized.
You should validate the URL or catch errors in your command in the case of invalid URLs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Perspective on the diamond lemma in ring theory As the title indicates, I am seeking some perspective (explained below) on Bergman's diamond lemma (DOI link to Bergman's paper) in ring theory.
I know that it can be used, for instance, to prove the Poincaré-Birkhoff-Witt theorem for universal enveloping algebras.  This is shown in Bergman's original paper.  And then it can be used also for quantized enveloping algebras, quantized function algebras, etc.
I am also aware of this page at Secret Blogging Seminar, which discusses the diamond lemma in the graph-theoretic setting.  It is stated there that this version can be used to prove the Jordan-Hölder theorem on composition series for a finite group (and presumably for modules over a ring, etc).
For this to be a well-formulated question, I need to make clear what I mean by "perspective".  Here is a quote from the introduction to the paper:

The main results in this paper are trivial. But what is trivial when described in
the abstract can be far from clear in the context of a complicated situation where
it is needed.

And then, later, after describing the results, he says:

This fact has been considered obvious and used freely by some ring-theorists
(e.g., [17, Sect. !5l), but others seem unaware of it and write out tortuous
verifications.

So, what I am looking for is examples of situations where the formalism of the diamond lemma really clarified or simplified some algebraic construction, or examples of people writing out "tortuous verifications" when they could have appealed to the diamond lemma instead.
PS  If you've never looked at Bergman's paper before, you should!  It's one of my favorites.  Everything is so clear and well-motivated.  If only I could write like that...

A: What I believe is really important is that you can use Diamond Lemma to make homological conclusions, and not just prove results on the size of your algebra. For instance, a homogeneous algebra with a quadratic Groebner basis (i.e. with quadratic relations which form a confluent system) is Koszul. Same applies in more tricky case, e.g. operads, where it becomes quite important since verifications become even more torturous (which you might know already from my comment to that SBS entry).

A: One example of a paper which uses the Diamond Lemma in an algebraic setting is
Michael Hutchings, Integration of singular braid invariants and graph cohomology,
Transactions of the AMS 350 (1998), 1791-1809.
See Theorem 4.1  He essentially uses a Diamond Lemma argument, although he never uses the term (not that his argument is any less clear for that).  Further to V. Dotsenko's point, he also essentially proves that the "chord diagram algebra" is Koszul, although he also never uses the word Koszul (probably because he doesn't actually need Koszulness for his purposes).

A: My paper http://arxiv.org/abs/math/0609832 is about some applications of the Diamond Lemma.

A: The thesis
Moore, E. Graphs of groups: word computations and free crossed
  resolutions. Ph.D. Thesis, University of Wales, Bangor (2001).
considers (following Higgins) a  normal form for  the fundamental groupoid of a graph of groups, and the diamond lemma method is used as a  way of establishing this. Graphs of groupoids are also considered.  The thesis is available as a pdf file here.
Note that Higgins' method avoids the usual choices of a base point and a tree.

A: What I totally did not have in mind when writing my first answer to this in 2012 is that the confluence condition of the Diamond Lemma can be interpreted quite nicely in terms of the Maurer-Cartan equation in the resolution of the corresponding monomial algebra, see https://arxiv.org/abs/2010.14792 .


text:
Q: Односвязный список рекурсивно Создаю односвязный список с добавлением элемента рекурсивно. Разобралась с функциями ввода/вывода рекурсивно и создала функцию добавления элемента. Подскажите, как последнюю сделать рекурсивно?
Буду благодарна!
#include <iostream>

using namespace std;

struct tnode {
    int info;
    tnode *next;

};
typedef tnode *pnode;

pnode Formback_Ree() //rec done
{
    pnode top;
    int info;
    cin>>info;
    if (!info) return NULL;
    top= new tnode;
    top-> info=info;
    top-> next =Formback_Ree();

    return top;
}
int insert_after(pnode top, int info, int newinfo) { //вставка элемента
    pnode cur, newNode;

    if (top == NULL) //проверка на пустоту
        return 0;
    cur = top;
    while (cur) {
        if (cur->info == info) { //cовп ли мой эл с нужным
            newNode = new tnode; //выделяем
            newNode->info = newinfo;
            newNode->next = cur->next;
            cur->next = newNode;
            return 1;
        }
       cur = cur->next;
      //  insert_after((cur->next), info, newinfo);
    }
    return 0;
}
void output1(pnode a)
{
    pnode cur;
    cur = a;
    if (cur){
    cout << cur->info << " ";
    output1(cur->next);
    }
    return;
}
 int main() {
        pnode d;
        d= Formback_Re();

        int info1;
        int newinfo1;
        cout << "\n(after) Введите номер элемента N:\n";
        cin >> info1;

        cout << "\n(after) Введите номер нового элемента N:\n";
        cin >> newinfo1;
        if (insert_after(d, info1, newinfo1)) {
            cout << "(after) Элемент N: " << newinfo1 << " успешно добавлен.\n";
            output1(d);
        }

A: Заменить цикл рекурсией?
int insert_after(pnode top, int info, int newinfo) { //вставка элемента
    if(!top) return 0;
    if(top->info == info) {
        top->next = new node{newinfo, top->next};
        return 1;
    }
    return insert_after(top->next, info, newinfo); // recursion step
}


text:
Q: Host ASP.NET Core 3.1 Angular Template in IIS The server responded with a non-JavaScript MIME type of "text/html" We are trying to put the default ASP.NET Core 3.1 template with Angular into IIS as a test and we are getting the following errors:

Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
  main-es2015.7a946a5153b4f357caaf.js:1
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
  polyfills-es2015.27661dfa98f6332c27dc.js:1
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

We have published the application to the folder structure with a release build.  The program and startup are as the default template creates.  We have installed the dotnet-hosting package as well.
Are there additional configuration steps required in IIS to host this as the documentation doesn't allude to anything else that is required.
Thanks in advance for any help.


text:
Q: Multiple get requests jquery I'm trying to read in several urls as text and store them into an array with jquery's ajax/get. I need to wait for all data to be obtained (and pushed to an array) and then return it in a function. From what I read online, this isn't possible.
I figured if I set a global array variable and pushed into that every time new data is obtained, then checked using a while loop if the array is saturated, when it is return. See below
You can assume all errors are handled within the get call
function fetchData(){
   x = [1,2,3,4,5,6,7,8,9,10];
   a = [];

   //Loop, get and push data
   $.each(x, function( i, val ) {
       $.get("http://someurl/"+i, function( data ) {
           a.push(data);
       });
   });

   // Wait till our array is populated?
   while(a.length < x.length){
       console.log(a.length);
   }
   return a;
}

However, this approach does not seem to be working and nothing is ever added to the array..
Can someone point me in the right direction?
Thank you

A: The solution you are looking for is to use a callback
function fetchData(callback) {
    var requests = [];
    for (var i = 1; i <= 10; i++) {
        requests.push($.get("http://someurl/" + i))
    }

    $.when.apply($, requests).then(function () {
        var array = $.map(arguments, function (arg) {
            return arg[0];
        });
        callback(array);
    })
}

fetchData(function (array) {
    //do something with array
})

PoC: Fiddle

A: issue 1
Here you are doing console.log on the result array even before the callbacks get fired. So the array a will always be empty. What you want to do is to trigger the console.log after all the values in array x are processed.
issue 2
You are trying to return the result array back. Instead you should try getting the code that processes a inside the callback.
like
function fetchData(cb){
   x = [1,2,3,4,5,6,7,8,9,10];
   a = [];

   //Loop, get and push data
   $.each(x, function( i, val ) {
       $.get("http://someurl/"+i, function( data ) {
           a.push(data);

           if(a.length == x.length) {
                //looping logic taken inside callback
                while(a.length < x.length){
                   console.log(a.length);

               }
               //calling the callback on result
               cb(a);
           }

       });
   });

}

fetchData(function(data){

    //process a here

});

A: In this way you can't make sure ajax calls will be done synchronously. To do so you can do a normal ajax call or you can use ajaxSetup.
In those ways you can make sure array will be read after all calls been processed. You better to have a timeout too, because some call may not return in time.


text:
Q: How to deserealize custom type using messagepack and tcp sockets? I was trying to send serealized object of custom type on server's side and deserealize it on client's side. I want to do that with Messagepack and tcp sockets. But when the bytes comes to client, programm occurred with error: "Failed to deserealize ". Type has two fields: Name and Age.
Server's side:
 var tcpListener = new TcpListener(IPAddress.Any, 8888);
        try
        {
            tcpListener.Start();
            Console.WriteLine("Server is currently run, waiting for incoming connections");
            Person Tom = new Person("Tom",40);
            while (true)
            {
                using var tcpClient = await tcpListener.AcceptTcpClientAsync();
                var stream = tcpClient.GetStream();
                var data = MessagePackSerializer.Serialize(Tom);
                await stream.WriteAsync(data);
                Console.WriteLine($"Data was sent to {tcpClient.Client.RemoteEndPoint} client");

            }
        }
        finally
        {
            tcpListener.Stop();
        }

Client's side:
using TcpClient tcpClient= new TcpClient();
await tcpClient.ConnectAsync("127.0.0.1",8888);
Console.WriteLine("Client is run");
try
{
    var stream = tcpClient.GetStream();
    var resData = MessagePackSerializer.Deserialize<Person>(stream);
    Console.WriteLine($"Person's name: {resData.Name} /n Person's age: {resData.Age}");
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}

How should I deserealize this object correctly? Alreade read topic: Error "This stream does not support seek operations" in C#. I've got the same mistake, but that doesnt help

A: Well, actually Error "This stream does not support seek operations" in C# helped, the problem was in absent atribute [MessagePackObj] before my type


text:
Q: Numbers aren't showing up right Hello there!
I'm kind of confused , I literally tried every possible sollution i could think of.
Yet the program isn't functioning right ! The purpose of this program is to seperate the odd numbers and the pair numbers from one single array and put each one of them on an array!
When i execute , and after putting some simple numbers , another random big numbers appear in each array!
why is that and how can i fix this ?
void Pairs_impairs(int* n,int T[], int P[], int Imp[]){
int i,j=0;
for (i=0;i<*n;i++){
    if(T[i]%2==0){
        P[j]=T[i];
        j++;}
    else{
        Imp[j]=T[i];
        j++;
}}
*n=j;
}
int main(){
int t[100],p[100],imp[100];
int n;
puts("saisir n :");
scanf("%d",&n);
puts("saisir le tableau : ");
int i;
for(i=0;i<n;i++){
    scanf("%d",&t[i]);
}
for(i=0;i<n;i++){
    printf("%d ",t[i]);
}
Pairs_impairs(&n,t,p,imp);
printf("\nLes pairs : ");
for(i=0;i<n;i++){
    printf("%d ",p[i]);
}
printf("\nLes impairs : ");
for(i=0;i<n;i++){
    printf("%d ",imp[i]);
}
return 0;

}

A: The function is incorrect. You need to keep separate indices for the arrays P and Imp within the function. For example
void Pairs_impairs(int* n,int T[], int P[], int Imp[]){
int i,j1=0, j2 = 0;
for (i=0;i<*n;i++){
    if(T[i]%2==0){
        P[j1]=T[i];
        j1++;}
    else{
        Imp[j2]=T[i];
        j2++;
}}
*n=j1;
}

Also you should guarantee that the both arrays P and Imp will have equal number of elements. Otherwise you need to return from the function two indices.
For example
struct Pair
{
    size_t first;
    size_t second;
};

struct Pair Pairs_impairs( const int T[], size_t n, int P[], int Imp[] )
{
    struct Pair p = { .first = 0, .second = 0 };

    for ( size_t i = 0; i < n; i++ )
    {
        if ( T[i] % 2 == 0 )
        {
            P[first++] = T[i];
        }
        else
        {
            Imp[second++] = T[i];
        }
    }

    return p;
}


text:
Q: Не работают медиа-запросы в sass Вот пример кода
@media only screen (max-width: 750px)

  .ic
    display: inline-block

A: Всему виной может быть вложенность... Эта проблема и в less
Смысл такой, если в примере такая конструкция

        html, body
           width: 100%;
           height: 100%;
           #wrapper
            width: 100px;
            height: 100px;

То в css при компиляции записывается так

    html, body{
           width: 100%;
           height: 100%;
        }
           html, body #wrapper{
            width: 100px;
            height: 100px;
           }
а когда ты задаешь @media

    @media only screen (max-width: 750px)
            #wrapper
            width: 100px;
            height: 100px;

что бы изменить только wrapper не слушает медиа

надо дописать в медиа и вложенность
@media only screen (max-width: 750px)
    html, body
           #wrapper
            width: 100px;
            height: 100px;

A: Быть может, проблема есть и со вложенностью, как пишет Air, но очевидный косяк - отсутствие and в медиа-запросе. Код должен быть таким:

@media only screen and (max-width: 750px) {
  .ic {
    display: inline-block
  }
}

A: Поправьте синтаксис:
@media only screen (max-width: 750px)
{
  .ic{
    display: inline-block;
  }
}


text:
Q: How to set an image as wallpaper in an ionic app? I have an image gallery application build using ionic, I need the user to be able to set current image as Home screen wallpaper or Lock screen wallpaper or both. How could I achieve this using ionic? Is there a ng-cordova plugin available to set wallpaper?
Any help would be much appreciated.
Thanks

A: Your problem seems like this Phonegap setting wallpaper from www assets? Android
There has a plugin for android set wallpaper, but seems long time no maintain it.
https://github.com/PurpleMADcanada/Wallpaper-PhoneGap-Plugin
ios can't do this, because the sandbox mechanism Programmatically update background wallpaper of iOS 7?


text:
Q: Atom apm show package config information I am currently trying to set up Atom's linter-eslint as per instructions here.
Whilst the tutorial cites a settings page for the linter-eslint I receive no such thing. Perhaps all the config is no longer required but this is my first time setting up a linter in a toolchain so I don't really fully understand everything; I am trying to learn (I am following a tutorial video here where they use vscode instead of Atom)
In this github issue I can see that people are able to print a log which contains Atom lots of helpful information about Atom generally and package settings which are described in the tutorial, but I can't see an option that would provide me this with apm - does anyone know what I am missing here?
Just to evidence my lack of a GUI settings option:
package list

A: To access a package's setting page, follow these steps:

*

*Open your Atom settings

*Click on the Installed Packages tab

*Search for the packate, e.g. linter-eslint

*Click on the Settings button

The programmatic equivalent is atom.workspace.open("atom://config/packages/linter-eslint"), which also works from Atom's console.
Also, the package-settings package lets you open any settings page from the command palette.


text:
Q: How to install and verify asynchronous Google Analytics tracking code? In my property's Tracking Code section I see this message:

Status: Tracking Not Installed Last checked: Oct ...
The Google Analytics tracking code has not been detected on your website's home
  page. For Analytics to function, you or your web administrator must
  add the code to each page of your website.

The tracking code shown to be copy/pasted is this:
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXx', 'example.com');
  ga('send', 'pageview');
</script>

There's a learn more button and when I click it it takes me to here which shows the asynchronous code, which is something like this:
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-Y']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

Is this the current/latest version of the GA code? Why is the dashboard (i.e. the Tracking Code section) is not showing this by default? Is there a way to customize the Google Analytics to show this code in the Tracking Code section, prepared for my property (website)?

A: What you are seeing first is the latest version of Google Analytics known as Universal Analytics. As per Google recommendation , use that for all your new analytics properties. This is identified by the analytics.js library in the tracking code
The second one is an earlier version of Google Analytics based on ga.js library.
Use the first version of tracking code given by GA and follow this tutorial based on analytics.js to debug your code.


text:
Q: How to resize a dynamically allocated array of polymorphic objects? I have a dynamically allocated array of polymorphic objects that I would like to resize without using STL library (vectors, etc). I've tried moving the original to a temporary array, then deleting the original, then setting the original equal to the temporary, like this:
int x = 100;
int y = 150;

Animal **orig = new Animal*[x];
Animal **temp = new Animal*[y];

//allocate orig array
for(int n = 0; n < x; n++)
{
    orig[n] = new Cat();
}

//save to temp
for(int n = 0; n < x; n++)
{
    temp[n] = orig[n];
}

//delete orig array
for(int n = 0; n < x; n++)
{
    delete orig[n];
}
delete[] orig;

//store temp into orig
orig = temp;

However, when I try to access the element for example:
cout << orig[0]->getName();

I get a bad memeory alloc error:
Unhandled exception at at 0x768F4B32 in file.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0033E598.

A: //delete orig array
for(int n = 0; n < x; n++)
{
    delete orig[n];
}

For this particular case, don't do this. You are actually deleting the objects not the array. So all the objects in the temp array are pointing to invalid locations. Simply do delete [] orig to deallocate the original array.

A: You are copying wrong. Instead of copying your temp array is simply pointing to the same location as that of the orig. Now when you delete the orig the temp pointers point to an invalid location.
//save to temp
for(int n = 0; n < x; n++)
{
    //temp[n] = orig[n];
    // Try this instead
    strcpy(temp[n], orig[n]);
}


text:
Q: DocuSign LoginInformation I'm new to DocuSign API. I'm getting "com.docusign.esign.client.ApiException: Error while requesting server, received a non successful HTTP code 404 with response Body: '' "
during execution using demo sandbox. I'm using docusign-java-client.
Please help me in this.

A: Check out the Java examples:

*

*Authorization code grant

*JWT grant


text:
Q: nft config to make a local NATed FTP server public available Everything will be on a isolated network, security is not an issue.
eth0 is connected to the "public" network. Address assigned by DHCP.
eth1 is connected to a "private network" server that provides ssh, telnet, "others" and ftp.
This server will have a fixed IP (192.168.1.2) in this example.
The gateway is running debian buster and Linux kernel 4.19.94
nft is used with NAT
This is my "gateway" nft configuration this far:
table ip my_nat {
    chain my_prerouting { type nat hook prerouting priority 0;
    tcp dport { 2222 } dnat to :22 # 2222 backdoor for ssh to the gateway
    tcp dport { 1-1023 } dnat to 192.168.1.2
  }
  chain my_postrouting {
    type nat hook postrouting priority 100;
    ip daddr 192.168.1.2  masquerade
  }
}

What do I need to add to make FTP work

A: TL;DR
# nft add ct helper ip my_nat ftp-incoming '{ type "ftp" protocol tcp; }'
# nft add chain ip my_nat my_helpers '{ type filter hook prerouting priority 10; }'
# nft add rule ip my_nat my_helpers iif eth0 ip daddr 192.168.1.2 tcp dport 21 ct helper set ftp-incoming
# modprobe nf_nat_ftp

with more details below...
Protocol helper modules for problematic protocols
FTP is an old protocol and is not very firewall-friendly: commands on the FTP command channel (21/TCP) negotiate an ephemeral port to use for the next transfer command. Because of this a stateful firewall has to snoop those commands and replies to temporarily pre-allow the adequate port about to be used.
On Linux this is provided by protocol-specific helper modules which are plugins to conntrack, the Netfilter subsystem tracking connections for NAT and stateful firewalling. With FTP, when a port negotiation (mostly PORT, EPRT, PASV or EPSV) for the next transfer has been seen on the FTP command port the helper adds a short-lived entry in a special conntrack table (the conntrack expectation table) which will wait the next related and expected data connection.
My answer uses the modern "secure" handling as described in this blog about iptables for generalities and in the nftables wiki and man nft for the handling in nftables which differs from iptables.
Secure use of helper and nftables rules
Linux kernel 4.7+ (so including 4.19) is using a secure approach by default: having the (here FTP) helper module loaded won't make it anymore snoop all packets having a TCP source or destination port 21, until specific nftables (or iptables) statements tell it in what (restricted) case it should snoop. This avoids unnecessary CPU usage and allows to change at any time the FTP port(s) to snoop just by changing a few rules (or sets).
The first part is to declare the flows that can trigger the snooping. It's handled differently in nftables than in iptables. Here it's declared using a ct helper stateful object, and filters to activate it must be done after conntrack (while iptables requires actions done before). man nft tells:

Unlike iptables, helper assignment needs to be performed after the
conntrack lookup has completed, for example with the default 0 hook
priority.

nft add ct helper ip my_nat ftp-incoming '{ type "ftp" protocol tcp; }'

nft add chain ip my_nat my_helpers '{ type filter hook prerouting priority 10; }'
nft add rule ip my_nat my_helpers iif eth0 ip daddr 192.168.1.2 tcp dport 21 ct helper set ftp-incoming

I chose the same table, but this could have been created in an other table, as long as the stateful object declaration and the rule referencing it are in the same table.
One can choose less restrictive rules of course. Replacing the last rule by this following rule would have the same effect as the legacy mode:
nft add rule ip my_nat my_helpers tcp dport 21 ct helper set ftp-incoming

For reference only, legacy mode, that shouldn't be used anymore, doesn't require the rules above but just this toggle (and the manual loading of the relevant kernel module):
sysctl -w net.netfilter.nf_conntrack_helper=1

Ensuring nf_nat_ftp is loaded
The kernel module nf_conntrack_ftp is automatically loaded with the dependency created by ct helper ... type "ftp". That's not the case for nf_nat_ftp, yet it is needed to also enable packet mangling in the command port when NAT is done on the data flow ports.
For example to have the module nf_nat_ftp pulled whenever nf_conntrack_ftp is loaded, the file /etc/modprobe.d/local-nat-ftp.conf could be added with this content:
install nf_conntrack_ftp /sbin/modprobe --ignore-install nf_conntrack_ftp; /sbin/modprobe --ignore-install nf_nat_ftp

or instead, simply add for example /etc/modules-load.d/local-nat-ftp.conf with:
nf_nat_ftp

Anyway right now this command should be done to ensure it's loaded:
modprobe nf_nat_ftp

About firewalling
Here's an additional note for firewalling. There can also be firewalling rules with some restrictions instead of allowing any new flow tagged as related by conntrack.
For example, although the FTP helper module handles both passive and active modes, if for some reason one wants to allow only passive mode (with data connection from client to server) and not "active" ftp (data connection from server source port 20 to client) one could use for example these rules in the firewall part of the ruleset, instead of the usual ct state established,related accept:
ct state established accept
ct state related ct helper "ftp" iif eth0 oif eth1 tcp sport 1024-65535 accept
ct state related ct helper "ftp" drop
ct state related accept

Other kind of related flows not related to FTP are kept accepted (or could be further split separately)

Example of handling by the helper
Here (in a simulated environment) are two conntrack lists of events measured on the expectation table and the conntrack table with OP's rules + the additional rules above with an Internet client 203.0.113.101 doing FTP in passive mode with the router's public IP address 192.0.2.2 and using a LIST command after having logged in:
# conntrack -E expect
    [NEW] 300 proto=6 src=203.0.113.101 dst=192.0.2.2 sport=0 dport=37157 mask-src=0.0.0.0 mask-dst=0.0.0.0 sport=0 dport=65535 master-src=203.0.113.101 master-dst=192.0.2.2 sport=50774 dport=21 class=0 helper=ftp
[DESTROY] 300 proto=6 src=203.0.113.101 dst=192.0.2.2 sport=0 dport=37157 mask-src=0.0.0.0 mask-dst=0.0.0.0 sport=0 dport=65535 master-src=203.0.113.101 master-dst=192.0.2.2 sport=50774 dport=21 class=0 helper=ftp

simultaneously:
# conntrack -E
    [NEW] tcp      6 120 SYN_SENT src=203.0.113.101 dst=192.0.2.2 sport=50774 dport=21 [UNREPLIED] src=192.168.1.2 dst=192.168.1.1 sport=21 dport=50774 helper=ftp
 [UPDATE] tcp      6 60 SYN_RECV src=203.0.113.101 dst=192.0.2.2 sport=50774 dport=21 src=192.168.1.2 dst=192.168.1.1 sport=21 dport=50774 helper=ftp
 [UPDATE] tcp      6 432000 ESTABLISHED src=203.0.113.101 dst=192.0.2.2 sport=50774 dport=21 src=192.168.1.2 dst=192.168.1.1 sport=21 dport=50774 [ASSURED] helper=ftp
    [NEW] tcp      6 120 SYN_SENT src=203.0.113.101 dst=192.0.2.2 sport=55835 dport=37157 [UNREPLIED] src=192.168.1.2 dst=192.168.1.1 sport=37157 dport=55835
 [UPDATE] tcp      6 60 SYN_RECV src=203.0.113.101 dst=192.0.2.2 sport=55835 dport=37157 src=192.168.1.2 dst=192.168.1.1 sport=37157 dport=55835
 [UPDATE] tcp      6 432000 ESTABLISHED src=203.0.113.101 dst=192.0.2.2 sport=55835 dport=37157 src=192.168.1.2 dst=192.168.1.1 sport=37157 dport=55835 [ASSURED]
 [UPDATE] tcp      6 120 FIN_WAIT src=203.0.113.101 dst=192.0.2.2 sport=55835 dport=37157 src=192.168.1.2 dst=192.168.1.1 sport=37157 dport=55835 [ASSURED]
 [UPDATE] tcp      6 30 LAST_ACK src=203.0.113.101 dst=192.0.2.2 sport=55835 dport=37157 src=192.168.1.2 dst=192.168.1.1 sport=37157 dport=55835 [ASSURED]
 [UPDATE] tcp      6 120 TIME_WAIT src=203.0.113.101 dst=192.0.2.2 sport=55835 dport=37157 src=192.168.1.2 dst=192.168.1.1 sport=37157 dport=55835 [ASSURED]

The expectation's start proto=6 src=203.0.113.101 dst=192.0.2.2 sport=0 dport=37157 tells that the next TCP connection from 203.0.113.101:* to 192.0.2.2:37157 will be associated (state related) with the FTP connection. Not visible directly, but since the NAT FTP helper module is also loaded, the actual data sent by the server in response to the PASV/EPSV command was intercepted and translated so the client connects to 192.0.2.2 instead of 192.168.1.2 which would have of course failed on the client.
Despite the second flow (second NEW line) having no explicit rule in my_prerouting, it was succesfully DNATed to the server behind the router.

Notes

*

*if the FTP control port is encrypted (AUTH TLS ...), then the helper module can't snoop the negotiated port anymore and this can't work. One have to resort to configuring a reserved range of ports both on the FTP server configuration and the firewall/NAT router, and configure the server so it sends the correct (public) IP address when negotiating instead of its own. And active FTP mode can't be used if the server has no route to Internet (as appears to be the case here).

*nitpicking: the prerouting priority of 10 ensures that even for kernels < 4.18, NAT already happened for new flows (OP chose hook prerouting priority 0 instead of the usual -100 as this rarely matters in nftables), so the use of daddr 192.168.1.2 is possible. If the priority was 0 (or lower than 0), it's perhaps possible (not verified) the rule would see the first packet still unNATed with a public IP destination address, but would catch the following packets of the same flow, since they are handled directly by conntrack at priority -200. Better stay safe and use 10. Actually this is not relevant since kernel 4.18 (see commit reference in this pending patch) where NAT priority is only relevant for comparing between multiple nat chains (and allows mixing NAT in iptables legacy along nftables).

A: After some trial and error I've come up with the following nftables.conf
This works as intended and supports NAT in both directions as well as exporting all but one port on my server to the "public" network. Port 2222 is still used as a "backdoor" to the gateway, to be used if i ever need to access it again :-)
table ip my_nat {
        ct helper ftp-incoming {
                type "ftp" protocol tcp
                l3proto ip
        }

        chain my_prerouting {
                type nat hook prerouting priority 0; policy accept;
                iifname "eth0" tcp dport { 2222 } dnat to :ssh
                iifname "eth0" tcp dport { 1-2221, 2223-65535 } dnat to 192.168.0.2
        }

        chain my_postrouting {
                type nat hook postrouting priority 100; policy accept;
                ip daddr 192.168.0.2 masquerade
                oifname "eth0" masquerade
        }

        chain my_helpers {
                type filter hook prerouting priority 10; policy accept;
                iif "eth0" ip daddr 192.168.0.2 tcp dport ftp ct helper set "ftp-incoming"
        }

}


text:
Q: How to perform an action only if the Mono is empty and throw an error if not empty I'm trying to convert a project to use Spring WebFlux and am running into a problem getting some basic business logic working.  I have a repository layer that is responsible for retrieving / persisting records and a service layer that is responsible for the business rules of the application.  What I want to do (in the service) layer is check if a user already exists for the given username.  If so, I want to respond with an error.  If not, I want to allow the insert to happen.
I call a method on the repository layer that will find a user by username and if not found it will return an empty Mono.  This is working as expected; however, I have tried various combinations of flatMap and (defaultIfEmpty and swithIfEmpty) but am unable to get it to compile / build.
    public Mono<User> insertUser(User user) {
        return userRepository.findByUsername(user.username())
            .flatMap(__ -> Mono.error(new DuplicateResourceException("User already exists with username [" + user.username() + "]")))
            .switchIfEmpty(userRepository.insertUser(user));
    }

The error that I'm getting is that Mono<Object> cannot be converted to Mono<User>, so the swithIfEmpty doesn't seem to reflect the appropriate type and casting doesn't seem to work either.

A: I'm using abstract class that has type parameter E so I couldn't use .cast(E.class). Our solution was
private Mono<E> checkIfStatementExists(E statement) {
    return this.statementService.getByStatementRequestId(statement.getStatementRequestId())
            .flatMap(sr -> Mono.<E>error(new ValidationException("Statement already exists for this request!")))
            .switchIfEmpty(Mono.just(statement));
}

I think I need to dicuss this matter with my co-workers next week.
Edit. We had discussion with co-workers and the updated code is above.

A: Why you are getting this compiler error is because of the following.
flatmap takes what is in your completed Mono and tries to convert it to whatever type it can infer. Mono.error contains a type and this type is of Object.
One way could instead be to move your logic into the flatmap.
// This is just example code using strings instead of repos
public Mono<String> insertUser(String user) {
    return Mono.just(user)
            // Here we map/convert instead based on logic
            .flatMap(__ -> {
                if (__.isEmpty())
                    return Mono.error(new IllegalArgumentException("User already exists with username [" + user + "]"));
                return Mono.just(user);
            }).switchIfEmpty(Mono.just(user));
}

switchIfEmpty is not super good for making logical decisions imho. The documentation states

Fallback to an alternative Mono if this mono is completed
  without data

It's more of a fallback to something else if we don't get anything, so we can keep the flow of data going.
You can also
Mono.empty().doOnNext(o -> {
        throw new IllegalArgumentException("User already exists with username [" + o + "]");
    }).switchIfEmpty(Mono.just("hello")).subscribe(System.out::println);

A: After additional testing, and taking into consideration the responses from my fellow developers, I have landed on the following solution:
    public Mono<User> insertUser(User user) {
        return userRepository.findByUsername(user.username())
            .flatMap(__ -> Mono.error(new DuplicateResourceException("User already exists with username [" + user.username() + "]")))
            .switchIfEmpty(Mono.defer(() -> userRepository.insertUser(user)))
            .cast(User.class);
    }

As Thomas stated, the compiler was getting confused. My assumption is because the flatMap was returning a Mono with an error and the switchIfEmpty was returning a Mono with a User so it reverts to a Mono with an Object (hence the additional .cast operator to get it to compile).
The other addition was to add the Mono.defer in the switchMap. Otherwise, the switchIfEmpty was always firing.
I'm still open to other suggestions / alternatives (since this seems like it would be a fairly common need / pattern).

A: Had the same problem and ended up doing below,
Please Note: This does not require type cast and works in both scenarios i.e,

*

*Throw an error if element already exists in the database.

*Insert element and return Mono otherwise.
  public Mono<UserDTO> insertUser(User user) {
     return this.userRepository.findByUsername(user.getUsername())
             .flatMap(foundUser-> null != foundUser ? Mono
                     .error(new UserAlreadyExistsException(ExceptionsConstants.USER_ALREADY_EXISTS_EXCEPTION))
                     : Mono.just(user))
             .switchIfEmpty(this.userRepository.save(user))
             .map(userCreated -> copyUtils.createUserDTO(userCreated));
  }

A: Instead of using the Mono::cast to change the type of the Mono, this can be solved by specifying the type of the Mono.error using a bit of Java generic magic in the form of Mono.<User>error(...).  This has the additional advantage that you do not need to alter the flow of the Mono pipeline by adding logic to the flatMap method with null handling but never actually receiving a null.
This would look as follows:
public Mono<User> insertUser(User user) {
    return userRepository.findByUsername(user.username())
        .flatMap(__ -> Mono.<User>error(new DuplicateResourceException("User already exists with username [" + user.username() + "]")))
        .switchIfEmpty(userRepository.insertUser(user));
}


text:
Q: Why does the Ubuntu docker base image only take 89 MB? In the Docker in Practice book, it explains that the todoapp that they create is layered on top of the node image, which is layered on top of ubtunu image (see image here). Why is the Ubuntu docker base image shown to take up only 89 MB, when in comparison a production OS install of Ubuntu takes approximately 10 times that much space?

A: If you read the ubuntu Dockerfile, you'll see that it's based on a tarball from https://cloud-images.ubuntu.com/.
If you inspect the images at https://cloud-images.ubuntu.com/minimal/releases/bionic/release/, you'll see that 75MB is typical compressed size.

To explain why this is so -- the minimal packageset is listed at https://packages.ubuntu.com/bionic/ubuntu-minimal. You'll see that it's a very small list -- no GUI, no development tools, no optional servers or services (as the expectation is that those will be installed later).


text:
Q: pandas.Series.str.len not behaving as expected I am trying to work with lists in Pandas cells. Not the best idea, maybe. Still I find that the pandas.Series.str.len method does not work as shown in the documentation.
Here goes my code:
    df3=pd.DataFrame({"comas":
                      [
        "1,2,3",
        "4,5,6,7,8,9",
        "7,8",
        "9,10,11,12"
                      ]
                     }
                    )

    df3["split"]=df3["comas"].str.split()

From there I obtain the following dataframe, as expected:
    comas   split
0   1,2,3   [1,2,3]
1   4,5,6,7,8,9 [4,5,6,7,8,9]
2   7,8 [7,8]
3   9,10,11,12  [9,10,11,12]

Now I want to know the length of each list.
df3["split"].str.len()

and I get
0    1
1    1
2    1
3    1
Name: split, dtype: int64

What I see in the documentation is that
s = pd.Series(['dog',
                '',
                5,
                {'foo' : 'bar'},
                [2, 3, 5, 7],
                ('one', 'two', 'three')])
s
0                  dog
1
2                    5
3       {'foo': 'bar'}
4         [2, 3, 5, 7]
5    (one, two, three)
dtype: object
s.str.len()
0    3.0
1    0.0
2    NaN
3    1.0
4    4.0
5    3.0
dtype: float64

Can somebody explain to me what is the difference between the list item in the fourth element of the example series and my series? I am using pandas version 1.3.3
Thank you in advance!

Edit:
RoseGod is right, I did not include the separator in the split. I was confused because Jupyter shows the elements in the dataframe pretty much the same way regardless if it was actually separated or not
df3.loc[0]

comas                  1,2,3
split                [1,2,3]
split_separator    [1, 2, 3]
Name: 0, dtype: object

It does show the element as a single string if I get a single cell, though:
df3.loc[0,"split"]
['1,2,3']

df3.loc[0,"split_separator"]
['1', '2', '3']

A: In the split you should specify how you want to split:
df3["split"]=df3["comas"].str.split(',')

Then the output will be the shape you want:
df3["split"].str.len()

0    3
1    6
2    2
3    4
Name: split, dtype: int64

If you print the value in the first row after you use the split without specifying the delimiter this is the output:
['1,2,3']

you can see it didn't really split it into a list but just created a list that contains the string value.


text:
Q: Joomla 1.6 Upgrade from 1.5 http://docs.joomla.org/Adding_a_multiple_item_select_list_parameter_type
Thats the documentation for the way to add a custom parameter type to your module and if you look at the bottom round there is this line : Saving parameter values to a database
Please can someone tell me if there is any documentation on how to do this in Joomla 1.6 because I cannot find it anywhere?
I understand completely how this works though, You need to bind your custom options (example: the list selection from a multiple selection input box) to the parent so that it will be able to save the selection to the DB.
Thank you in advance.
EDIT added code
protected function getInput()
    {

        $options = array();
        $attr = '';

        $attr .= ' multiple="multiple"';
        $attr .= ' style="width:220px;height:160px;"';

        // Get the database instance
        $db = JFactory::getDbo();
        // Build the select query
        $query = 'SELECT params FROM jos_modules'
            . ' WHERE module="mod_pmailer_subscription"';
        $db->setQuery($query);
        $params = $db->loadObjectList();

        // Decode the options to get thje api key and url
        $options = json_decode($params[0]->params, true);

        // Create a new API utility class
        $api = new PMailerSubscriptionApiV1_0(
            $options['enterprise_url'],
            $options['pmailer_api_key']
        );

        // Get the lists needed for subscription
        $response = $api->getLists();

        // Make a default entry for the dropdown
        $lists = array('0' => 'Please select a list');

        // Builds the options for the dropdown
        foreach ( $response['data'] as $list )
        {
            $lists[$list['list_id']]['id']    = $list['list_id'];
            $lists[$list['list_id']]['title'] = $list['list_name'];
        }

        // The dropdown output
        return JHTML::_(
            'select.genericlist',
            $lists,
            'jform[params][list_id]',
            trim($attr),
            'id',
            'title',
            $options['list_id']
        );

    }

A: Checkout this, How to convert JParams to JForm
EDIT :
I checked the forum and found that you are using
// Builds the options for the dropdown
foreach ( $response['data'] as $list )
{
   $lists[$list['list_id']] = $list['list_name'];
}

but in JHTML you are passing id and title for text and value field,
Use
    // Builds the options for the dropdown
    foreach ( $response['data'] as $list )
    {
        $lists[$list['list_id']]['id']    = $list['list_id'];
        $lists[$list['list_id']]['title'] = $list['list_name'];
    }


text:
Q: Mute output but still get audio to stereo mix? I'm using Airfoil in conjunction with stereo mix to broadcast my laptops audio to a raspberry pi running shairport, only problem is that the audio is still being played through my laptop speakers.
SO basically I'm looking for a way to somehow mute the local sound while still getting the audio to the stereo mix, is this possible? Hopefully I can do this with just software - also I really dont want to have to buy a Virtual Audio Cable license if possible.
Thanks for any tips.

A: I hunted and hunted for a very long time but in the end couldn't find anything appropriate. Bit the bullet and got a license for Virtual Audio Cable - which does exactly what I wanted it to.


text:
Q: How to find duplicates in a table using Access SQL? I try to use an SQL query in Access but it doesn't work. Why?
SELECT * FROM table
EXCEPT
SELECT DISTINCT name FROM table;

I have a syntax error in FROM statement.

A: MS Access does not support EXCEPT keyword. You can try using the LEFT JOIN like this:
select t1.* from table t1 left join table t2 on t1.name = t2.name

EDIT:
If you want to find the duplicates in your table then you can try this:
SELECT name, COUNT(*)
FROM table
GROUP BY name
HAVING COUNT(*) > 1

You can also refer: Create a Query in Microsoft Access to Find Duplicate Entries in a Table and follow the steps to find the duplicates in your table.

First open the MDB (Microsoft Database) containing the table you want
  to check for duplicates.  Click on the Queries tab and New.

This will open the New Query dialog box.  Highlight Find Duplicates
  Query Wizard then click OK.

Now highlight the table you want to check for duplicate data.  You can
  also choose Queries or both Tables and Queries.  I have never seen a
  use for searching Queries … but perhaps it would come in handy for
  another's situation.  Once you've highlighted the appropriate table
  click Next.

Here we will choose the field or fields within the table we want to
  check for duplicate data.  Try to avoid generalized fields.

Name the Query and hit Finish.  The Query will run right away and pop
  up the results.  Also the Query is saved in the Queries section of
  Access.

Depending upon the selected tables and fields your results will look
  something similar to the shots below which show I have nothing
  duplicated in the first shot and the results of duplicates in the
  other.

A: use HAVING COUNT(name) > 1 clause
SELECT * FROM Table1
WHERE [name] IN
(SELECT name, Count(name)
FROM Table1
GROUP BY name
HAVING COUNT(name)>1)

A: You can use LEFT JOIN or EXISTS
LEFT JOIN
SELECT DISTINCT t1.NAME FROM table1 as t1
LEFT JOIN table2 as t2 on t1.name=t2.name
WHERE t2.name is null
;

NOT EXITS
SELECT T1.NAME FROM table1 as t1 where not exists
(SELECT T2.NAME FROM table2 as t2 where t1.name=t2.name)

A: Whether Access supports except or not is one issue.  The other is that you are not using it properly.  You have select * above the word except and select name below.  That is not valid sql.  If you tried that in SQL Server, your error message would be All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.


text:
Q: Use Spacy to find most similar sentences in doc I'm looking for a solution to use something like most_similar() from Gensim but using Spacy.
I want to find the most similar sentence in a list of sentences using NLP.
I tried to use similarity() from Spacy (e.g. https://spacy.io/api/doc#similarity) one by one in loop, but it takes a very long time.
To go deeper :
I would like to put all these sentences in a graph (like this) to find sentence clusters.
Any idea ?

A: This is a simple, built-in solution you could use:
import spacy

nlp = spacy.load("en_core_web_lg")
text = (
    "Semantic similarity is a metric defined over a set of documents or terms, where the idea of distance between items is based on the likeness of their meaning or semantic content as opposed to lexicographical similarity."
    " These are mathematical tools used to estimate the strength of the semantic relationship between units of language, concepts or instances, through a numerical description obtained according to the comparison of information supporting their meaning or describing their nature."
    " The term semantic similarity is often confused with semantic relatedness."
    " Semantic relatedness includes any relation between two terms, while semantic similarity only includes 'is a' relations."
    " My favorite fruit is apples."
)
doc = nlp(text)
max_similarity = 0.0
most_similar = None, None
for i, sent in enumerate(doc.sents):
    for j, other in enumerate(doc.sents):
        if j <= i:
            continue
        similarity = sent.similarity(other)
        if similarity > max_similarity:
            max_similarity = similarity
            most_similar = sent, other
print("Most similar sentences are:")
print(f"-> '{most_similar[0]}'")
print("and")
print(f"-> '{most_similar[1]}'")
print(f"with a similarity of {max_similarity}")

(text from wikipedia)
It will yield the following output:
Most similar sentences are:
-> 'Semantic similarity is a metric defined over a set of documents or terms, where the idea of distance between items is based on the likeness of their meaning or semantic content as opposed to lexicographical similarity.'
and
-> 'These are mathematical tools used to estimate the strength of the semantic relationship between units of language, concepts or instances, through a numerical description obtained according to the comparison of information supporting their meaning or describing their nature.'
with a similarity of 0.9583859443664551

Note the following information from spacy.io:

To make them compact and fast, spaCy's small pipeline packages (all packages that end in sm) don't ship with word vectors, and only include context-sensitive tensors. This means you can still use the similarity() methods to compare documents, spans and tokens – but the result won't be as good, and individual tokens won't have any vectors assigned. So in order to use real word vectors, you need to download a larger pipeline package:
- python -m spacy download en_core_web_sm
+ python -m spacy download en_core_web_lg

Also see Document similarity in Spacy vs Word2Vec for advice on how to improve the similarity scores.


text:
Q: how to make sure that there is no letter, that his occurrence ist't more than 4 in a string for a login system? I want to know if there is a letter, that is in a string (name) more than 4.
I have the issue, that my example code is not correct, because when you write the name like that: aaaAA
it will say there is no error. Because the letters in the array are like this ("A","a",....).
i have another files for a index, Car Class. I want just to make test, that this function works. This function should find out, whether a letter be repeated more than 4 example:
aaaaa; the function should here say that is not allowed.
aaaAA; the function should here say that is not allowed.
Upper and lower case letters must be treated equally
Can i have some help?
thank you very much for all.

    public function checkLetterOccurence($newMarke)
    {
        //array of the letter
        $letterKette = array('A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n', 'O', 'o', 'P', 'p', 'Q', 'q', 'R', 'r', 'S', 's', 'T', 't', 'U', 'u', 'V', 'v', 'W', 'w', 'X', 'x', 'Y', 'y', 'Z', 'z');

        for ($i = 0; $i < count(  $letterKette); $i++) {

            if (substr_count($newMarke, $letterKette[i]) > 4) {
                echo "there is a letter that is more than 4 written, and that is not allowed.";
                die();
            }
        }

    }

A: You have to make your input all-lowercase and then count occurrence of letters:
<?php

$input = 'aaaAA';

function checkLetterOccurence($input) {
    $input = strtolower($input);
    // Split text to array of letters, e.g. "hello" becomes ["h", "e", "l", "l", "o"]
    $input = str_split($input);

    // Here we will keep map of letters and how much time it appears in word
    $count = [];

    foreach ($input as $letter) {
        // If there is no such letter added yet, we add new one with initial value 0. Next line will add +1 to it
        $count[$letter] ??= 0; // Or if (!isset($count[$letter])) $count[$letter] = 0;
        $count[$letter]++;
    }

    // Filter only those letters that appear more than 4 times in word
    $filteredInput = array_filter($count, fn($c) => $c > 4);

    // If we have +4 same letter in word - write out error message
    if (!empty($filteredInput)) {
        echo "There is a letter that is more than 4 written, and that is not allowed. Wrong letters: " . implode(',', array_keys($filteredInput));
    } else {
        echo "All good";
    }
}

checkLetterOccurence('aaaAA');

Example


text:
Q: CMFCMenuBar generated menu bar, how to use CMenu to dynamically add menu? This code does not get the effect I want, I want to dynamically add a custom menu on the CMFCMenuBar, it is independent
CMenu   m_menuFromPlug;

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
    AddMenu();
}

void CMainFrame::AddMenu()
{
    m_menuFromPlug.CreatePopupMenu();
    CMenu *pMenu = CMenu::FromHandle(m_wndMenuBar.GetDefaultMenu());
    if (NULL != pMenu)
    {
        CString plugMStr = TEXT("Root Menu");
        while (m_menuFromPlug.GetMenuItemCount())
        {
            m_menuFromPlug.DeleteMenu(0, MF_BYPOSITION);
        }

        unsigned int flag = MF_ENABLED | MF_STRING;
        m_menuFromPlug.AppendMenu(flag, 500, TEXT("Item Menu"));

        MENUITEMINFOW menuStru;
        if (pMenu->InsertMenuItem(2, &menuStru, MF_BYPOSITION))
        {
            m_wndMenuBar.CreateFromMenu(pMenu->GetSafeHmenu(), TRUE, TRUE);
        }
    }
}


text:
Q: How do I implement async generators? I have subscribed to a MQ queue. Every time I get a message, I pass it a function that then performs a number of time-consuming I/O actions on it.
The issue is that everything happens serially.
A request comes in, it picks up the request, performs the action by calling the function, and then picks up the next request.
I want to do this asynchronously so that multiple requests can be dealt with in an async manner.
results = []
queue = queue.subscribe(name)
async for message in queue:
    yield my_funcion(message)

The biggest issue is that my_function is slow because it calls external web services and I want my code to process other messages in the meantime.
I tried to implement it above but it doesn't work! I am not sure how to implement async here.
I can't create a task because I don't know how many requests will be received.  It's a MQ which I have subscribed to.  I loop over each message and perform an action.  I don't want for the function to complete before I perform the action on the next message. I want it to happen asynchronously.

A: If I understand your request, what you need is a queue that your request handlers fill, and that you read from from the code that needs to do something with the results.
If you insist on an async iterator, it is straightforward to use a generator to expose the contents of a queue. For example:
def make_asyncgen():
    queue = asyncio.Queue(1)
    async def feed(item):
        await queue.put(item)
    async def exhaust():
        while True:
            item = await queue.get()
            yield item
    return feed, exhaust()

make_asyncgen returns two objects: an async function and an async generator. The two are connected in such a way that, when you call the function with an item, the item gets emitted by the generator. For example:
import random, asyncio

# Emulate a server that takes some time to process each message,
# and then provides a result. Here it takes an async function
# that it will call with the result.
async def serve(server_ident, on_message):
    while True:
        await asyncio.sleep(random.uniform(1, 5))
        await on_message('%s %s' % (server_ident, random.random()))

async def main():
    # create the feed function, and the generator
    feed, get = make_asyncgen()

    # subscribe to serve several requests in parallel
    asyncio.create_task(serve('foo', feed))
    asyncio.create_task(serve('bar', feed))
    asyncio.create_task(serve('baz', feed))

    # process results from all three servers as they arrive
    async for msg in get:
        print('received', msg)

asyncio.run(main())


text:
Q: PyCharm giving error while setting up interpreter: no such option: --python I am trying to create a project in Pycharm and I am getting this error when I use New Environment Using Pipenv, I do think there is no --python options in Pip3, so how do I bypass this in PyCharm and set up my project

A: Pipenv is different from pip, and you'd have to install Pipenv separately, then point Pycharm at it
https://pipenv.kennethreitz.org/en/latest/install/#installing-pipenv
How to setup pipenv in Pycharm is documented here
https://www.jetbrains.com/help/pycharm/pipenv.html
Otherwise, you should chose an option other than Pipenv

A: pip is package-management system for python.
I think what you looking for is to set up a new interpreter/venv
That can be achieved by hitting that button highlighted in the photo

A: this happens when you give the wrong " pipenv.exe " address to pycharm as pipenv executer like the following snapshot.
To create a pipenv interpreter, first you need to install pipenv with following command :
pip install pipenv

then make sure your computer knows where to look for the executer files of pipenv which is the Scripts folder in python directory of your device
if you have pipenv there you are all set.
go to pycharm > settings > interpreter settings , click show more from frop down menu, click plus to add new interpreter and finally choose "pipenv"
IMPORTANT :

*

*set base interpreter to python.exe file from python directory

*set pipenv executable to pipenv.exe file from python directory/Scripts
you are all set to use your pipenv interpreter now :)
quick check list

*

*make sure you add the python folder and also Scripts folder to the path on your system

*make sure you are pointing to pipenv.exe file instead of other files in Scripts folder

pic


text:
Q: Salesforce Field Calculation with Multiple Criteria I am trying to come up with a formula that will give a calculation in the "Offset Field" based on The "Enrollment Cohort City" name.
For some reason the formula is using 100 to minus record count for all rows.
My Current Formula:
IF(Placement__c.Enrollment__c.Cohort_City__c ="Online",RowCount - 100,RowCount - 45)
In the simplest terms I need to have the offset column subtract from the record count based on multiple conditions.
New York needs a formula that will be 45 minus "record count"
Online works fine. 100 minus record count = -89
New York needs a formula that will be 46 minus "record count"

A: Normally I'd use CASE function but looks like it behaves funny in summary level formulas. Either returns just the default clause or complains about type mismatch.
RowCount - CASE(Placement__c.Enrollment__c.Cohort_City__c,
'New York', 46,
'Online', 100,
45)

Try to cheat by making a helper row-level formula.
Here's my standard "Opportunities with Products" report on standard data you can find in Developer Edition, Trailhead playground, scratch orgs (you know, "Burlington Textiles", "University of Arizona", "United Oil & Gas" etc). Grouped by Account billing city (so it should match your situation, opp line item -> opp -> account).
Pretend 1st row says "Online"
[
First I created row level formula called "city offset"
Type = number, 0 decimal places. So that's the CASE I wanted
CASE(ADDRESS1_CITY,'Austin',100,'New York',46,45).
When you group it SF is likely to display SUM of this field, we don't want that. Either don't display the field at all or pick AVG/MIN/MAX. I've went with MAX so my table column's header says "Largest..."

Once you're happy with the row-level formula add your final summary-level calculation. For me it was CDF1:MAX - RowCount, your field names may differ. Make it similar to this:


text:
Q: Thread initialized to null in java public class ThreadState {

    public static void main(String[] args){
            Thread t = new Thread(){
            public void run(){
                       // infinite loop
                       while (true) {
                        try {

                         Thread.sleep(1000);
                        }
                        catch (InterruptedException e) {
                        }

                        System.out.println("thread is running..."+Thread.currentThread().toString());
                       }

            }
        };
        t.start() ;
        t = null ;
        while (true) {
              try {

              Thread.sleep(3000);
              }
              catch (InterruptedException e) {
              }
              System.out.println("thread is running..."+Thread.currentThread().toString());
        }

    }
}

Thread instance t is initialized to null .. still it is able to run and prints its detail on the console . Need an explanation for this

A: t = null; just removes a reference to the Thread instance.
It doesn't affect the thread itself.
In particular, an executing Thread instance will never be GC'd.

A:
Thread instance t is initialized to null

No, the Thread variable is set to have a null value. Variables aren't instances - it's worth making absolutely sure that you understand that.
Changing the value of the variable doesn't affect the existing Thread object at all.

A: You set t to null, that doesn't do anything with the thread itself, it just assigns null to the variable where you stored a reference to the instance.
Maybe this will help:
What if you do
Object t = new Thread() {...}
t.start
Thread t2= (Thread)t;
t="Orange";

Would you expect magic things to happen then as well? What if you passed t to another method instead of storing another reference in t2?
t is just a placeholder for a reference to the thread, assigning something to t has just as much impact on the thread as assigning null to a below has to the number 2.
Integer a = 2;
a=null;

A: @JonSkeet and others have explained well that then you set t = null you are not changing the running Thread at all, you are just changing the variable t.  Once the thread has started, the JVM manages the thread so even if there are no references to it, it will still run and not be GC'd.
Another thing to point out is that, in the loop that follows you are doing a:
System.out.println("thread is running..."+Thread.currentThread().toString());

This is not printing out the status of the thread that you just forked but rather printing out the current thread -- the thread that did the forking.  This is the "main thread" that runs the main() method.  The main thread can finish and the thread that you forked will continue to run -- keeping the JVM from exiting.   Only if the thread that you forked is marked as being a daemon thread will the JVM finish when the main thread finishes.

A: I think Jon is correct i.e. "Changing the value of the variable doesn't affect the existing Thread object at all."
But actual explanation you required is

In programming method that uses static or global memory local to a thread.
  Because normally all threads in a process share the same address space, which is sometimes   undesirable.
  In other words, data in a static or global variable is normally always located at the same memory location, when referred to by threads from the same process. Each thread has its own stack.

Hope the conceptual explanation given is helpful.


text:
Q: Terminator custom commands cause shell to close I have the default terminator profile configured to split the window into four quadrants on launch, this works well.
There is also a "Custom Command" option for each terminal, which I assumed meant something to run in the terminal. However, if I put anything in there, the command executes and the terminal closes (I'm sure it's executing because I've tried echo hi > /tmp/hi, and that file is indeed created with "hi" in it).
How can I get each terminal to execute a command I specify but remain open afterwards?
EDIT: Kubuntu 14.04.1, with the standard terminator distribution in the trusty repo.

A: There an When command exits: option in Preferences → Profiles → Command. If you want to open shell after command executes, append ; bash to custom command (e.g. echo hi > /tmp/hi; bash).

A: @xzfc's comment within his accepted answer helped me find a solution.

Within each "custom command" field, enter
INITIAL_TERMINATOR_WINDOW=1 bash

Then, from within your .bashrc you can check to see if the variable is set, and respond accordingly:
if [ -n "$INITIAL_TERMINATOR_WINDOW" ]; then
  # Do something from an initial window
else
  # Do something different when opening subsequent windows
fi


text:
Q: Joining 2 XML's with document function is very slow I have XML i need to join on the ID
XML input ( 93 Mb )
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <Partner>
      <ID>186561</ID>
   </Partner>
   ...
<root>

XML : fuzzymatched.xml ( 40 Mb )
<?xml version="1.0" standalone="yes"?>
<root>
   <Partner>
    <ID>186561</ID>
    <FUZZYMATCH>71</FUZZYMATCH>
  </Partner>
  ...
<root>

When i join this files with following XSLT , it is very slow. It seems that it opens the big document every time again?! Is there a better solution? or am i doing something wrong.
I use the XSLT engine of Talend Open Studio
XSLT file
<!-- ********************************************* -->
<!-- fuzzymatch_joiner.xsl : -->
<!-- ********************************************* -->
<xsl:stylesheet version="1.1" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />

<xsl:variable name="vPartners" select="document('file:///c:/temp/fuzzymatched.xml')/root" />

<xsl:template match="root">
    <xsl:copy>
          <xsl:apply-templates select="Partner"></xsl:apply-templates>
        </xsl:copy>
</xsl:template>
<!-- ********************************************* -->

<xsl:template match="Partner">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"></xsl:apply-templates>
        <xsl:copy-of select="$vPartners/Partner[ID = current()/ID]/FUZZYMATCH"/>
    </xsl:copy>
</xsl:template>
<!-- ********************************************* -->

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
      </xsl:copy>
</xsl:template>
<!-- ********************************************* -->

 </xsl:stylesheet>

A: Due to the size of your XML file, you need to change the parser set by default (DOM) and use SAX parser instead.
On tFileInputXML component, select the advanced parameters and choose SAX parser (labelled : "low memory consuming" if I remember well).
The xml processing should be much faster.

A: First, you should definitely use a key (<xsl:key> and key()) to index the IDs from fuzzymatched.xml, to speed up ID lookup. That should make a huge difference.
If that's not enough... I don't know much about Talend, but I would try the same transformation using a good optimized XSLT processor such as Saxon, and see how the performance compares. An XSLT processor shouldn't have to re-open the file referenced by document() every time.
Do you have the freedom to use a different processor within Talend?
XSLT 3.0 (still in working draft status) provides support for streaming, which would reduce the memory requirements for the input XML, and could speed things up. Saxon has support for it.
But I think just using key() should speed things up for you a lot.


text:
Q: Prove $\varphi(t_1,\,t_2,\,\lambda)=Ee^{i\lambda\left(\xi_{t_2}-\xi_{t_1}\right)}$ is continuous in $\left(t_1,\,t_2\right)\in \left[0,\,1\right]^2$. Assume $\xi_t$ is a stochastically continuous random process on $\left.[0,\,\infty\right.)$.
Prove $$\varphi(t_1,\,t_2,\,\lambda)=Ee^{i\lambda\left(\xi_{t_2}-\xi_{t_1}\right)}$$ is continuous in $\left(t_1,\,t_2\right)\in \left[0,\,1\right]^2$ where $\lambda\in \mathbb{R}$.

We have
$$
\begin{aligned}
&\left|\varphi\left(t_1,\,t_2,\,\lambda\right)-\varphi\left(t_1^\prime,\,t_2^\prime,\,\lambda\right)\right|\\[.4cm]
=&\left|Ee^{i\lambda\left(\xi_{t_2}-\xi_{t_1}\right)}-Ee^{i\lambda\left(\xi_{t_2^\prime}-\xi_{t_1^\prime}\right)}\right|\\[.4cm]
=&\left|E\left[e^{i\lambda\left(\xi_{t_2^\prime}-\xi_{t_1^\prime}\right)}\left(e^{i\lambda\left[\left(\xi_{t_2}-\xi_{t_2^\prime}\right)-\left(\xi_{t_1}-\xi_{t_1^\prime}\right)\right]}-1\right)\right]\right|\\[.4cm]
\leq&\lambda E\left|\xi_{t_2}-\xi_{t_2^\prime}\right|+\lambda E\left|\xi_{t_1}-\xi_{t_1^\prime}\right|.
\end{aligned}
$$
Since we only have $\xi_{t^\prime}\to_P\xi_{t}\;(t^\prime\to t)$, it does not guarantee the last formula can be as small as possible.
So I want to know how to prove it.


text:
Q: GREF increasing / decreasing in multi-threaded service (aidl) - what does it mean? I have an android activity and a service implemented using aidl. Works like a champ, I have a callback setup to pass some thread notifications back to the UI, and that appears to work fine, with the exception of lots of
GREF has increased to 101, 201,301,401, 501.. etc, and GREF has decreased. I did some searching online and found that it has to do w/ Global References.
08-17 02:31:19.735: DEBUG/dalvikvm(2558): GREF has increased to 301
...
08-17 02:31:25.823: DEBUG/dalvikvm(2558): GREF has increased to 401
...
08-17 02:31:36.772: DEBUG/dalvikvm(2558): GREF has increased to 501
...
08-17 02:31:42.694: DEBUG/dalvikvm(2558): GREF has increased to 601
...
08-17 02:31:48.695: DEBUG/dalvikvm(2558): GREF has increased to 701
...
08-17 02:31:59.883: DEBUG/dalvikvm(2558): GREF has decreased to 599
08-17 02:31:59.912: DEBUG/dalvikvm(2558): GREF has decreased to 499
08-17 02:31:59.912: DEBUG/dalvikvm(2558): GREF has decreased to 399
08-17 02:31:59.912: DEBUG/dalvikvm(2558): GREF has decreased to 299
08-17 02:31:59.912: DEBUG/dalvikvm(2558): GREF has decreased to 199

I did some searching and see that most of the remarks on this are rather old. My concern is that I am implementing my client/service correctly, and wanted to know how I can track down what is causing GREF to increase. Any thoughts / suggestions are welcomed. Thanks!
Basic Program Flow
Client -> Creates Callback
Client -> Starts Service
Service -> Inits & Starts CountDownTimer
Service.CountDownTimer.onFinish() -> DownloadAndParse()
DownloadAndParse() -> initialize new saxRequest(), new Handler for this request.
Service.Handler->beginBroadcast()
Client.CallbackStub -> updateUI()
Client.CallbackStub -> service.startCountDownTimer()

Hopefully this makes sense. I would post code here, but there is so much in so many different files. I figured I would try and put the flow up to see if there is anything glaring... The only thing I can see is maybe re-using the saxRequest() rather than creating a new instance... I will try that now actually, but I would really like to know about the impact of the GREF and the Garbage Collection..

A: These are JNI global references.  If you're not writing native code, you don't have direct control over them.  The log messages appear when CheckJNI is enabled, which is on by default for engineering builds and the emulator.
The messages just mean that native code is telling the VM that it's not allowed to discard some objects.  In essence, global refs are a way for native code to add references to the GC's root set.  Assuming the native code is written correctly, the global refs will be cleared when the native code no longer has need of them.
The only cause for concern would be if the global ref count continued to climb, as that would suggest a global reference leak.  Since the VM can't free the objects, a global ref leak will eventually cause the VM to run out of memory.  To help identify such problems, a cap is placed on the number of global references when CheckJNI is enabled (current limit is 2000).


text:
Q: Build path incomplete only in some workspaces (Android) I have multiple Eclipse (3.52 "Galileo") ) workspaces so that I can keep related projects together in the same workspace.   I switch between them with File > Switch Workspace.
I recently copied a good, working project to a different workspace, did a "File > Import" to import it in its new workspace, but after doing a Clean and Build, got the "The project was not built since its build path is incomplete. Cannot find the class file for java.lang.Object. Fix the build path then try building this project " error.
All my other projects build fine.    I thought the "build path" referred to the search path Java or SDK files, so why would it only fail on one project  ( ...a project that builds fine in a different workspace, at that)?
I've tried restarting eclipse, switching back and forth between workspaces, doing another clean and build, but no luck.   Any ideas?   Thanks in advance.

A: I think Bill LaPrise might be right in most cases, but not in mine. What I eventually had to do was go into the folder where I have all my projects and delete the .metadata for Eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone)
After it was deleted I just imported the project again, and it worked.
This was on Eclipse 4.2.0 Juno, if you're wondering.

A: This may be a little late to help you, but in case others are looking, here's how I fixed it:
Right click on your project and select 'Properties'. Then select 'Java Build Path', and the Library tab. Look for a JVM. If one is not there (broken link from your copied project), click 'Add Library' and add the default JVM. If a VM is there, select it and hit 'Edit' and reselect the default JVM. This should reestablish that link and fix the problem. Hope this helps.

A: For those encountering this error while using Maven:

*

*Right click on the project, Build Path -> Configure Build Path...

*Select the libraries tab. If Maven dependencies is not in the list,
you have identified the problem.

*Close the dialog.

*Right click on the project, Maven -> Disable Maven Nature

*Right click on the project, Configure -> Convert to Maven Project.

A: Right click on the project, Maven->Update Project
Will Solve the Problem

A: Close Eclipse and run the below command from the terminal:
$ mvn clean eclipse:clean eclipse:eclipse

A: Right click on the project in the Eclipse 'Package Explorer'. Then from the drop down menu find 'Android Tools'. From the sub menu select 'Fix Project Properties'. It works wonders.

A: restart eclipse works on me. I am on Indigo.

A: In my case this issue happens after I install ADT manually by downloading .zip instead install from ADT site.
I solve the issue by right click on project -> Java Build Path. You'll see Android XXX, Android Dependencies, Android Private Libraries, Expand and click on Native library location (None), click edit button on right side then add path to ADT folder on eclipse on Location Path. Restart eclipse to complete


text:
Q: How to Use SQL on saving ConversationState and UserState Bot Framework v4 I'm currently migrating my bot framework v3 to v4.
Is there any way to store the Bot State on SQL database?
I've seen documentation on Bot State here:
https://learn.microsoft.com/da-dk/azure/bot-service/migration/net-migration-quickreference?view=azure-bot-service-4.0&viewFallbackFrom=azure-bot-service-3.0
But it can only saves on CosmoDB or Azure Storage. No available documentation on bot framework v4 about saving State in SQL
In my bot framework v3 I have this code which saves Bot State to SQL database:
var store = new SqlBotDataStore(ConfigurationManager.ConnectionStrings["statedb"].ConnectionString);
        Conversation.UpdateContainer(
           builder =>
           {
               builder.Register(c => store)
                    .Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore)
                    .AsSelf()
                    .SingleInstance();

               builder.Register(c => new CachingBotDataStore(store,
                          CachingBotDataStoreConsistencyPolicy
                          .ETagBasedConsistency))
                          .As<IBotDataStore<BotData>>()
                          .AsSelf()
                          .InstancePerLifetimeScope();

               builder.RegisterModule(new ReflectionSurrogateModule());

               builder.RegisterModule<GlobalMessageHandlersBotModule>();
           });

I expect that bot framework v4 has similar functions

A: The Bot Framework Community has provided EntityFramework storage for Bot Builder V4.  The source code can be found here and the library is available as a nuget package Bot.Builder.Community.Storage.EntityFramework
It is used the same way as other V4 IStorage providers:
var entityFrameworkStorage = new EntityFrameworkStorage(Config["SqlConnectionString"]);
services.AddSingleton<IStorage>(dataStore);
services.AddSingleton<UserState>();
services.AddSingleton<ConversationState>();

More information can be found here:
https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-concept-state
https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-howto-v4-state


text:
Q: Android Market Billing System There is issue with android market.
I'm in country where I am not allowed to get funds from android market.
There is solution for that:
App is free and distributed via android market, but goods for software will be sold via some payment processor located on a web site.
Is this legal solution?

A: See section 3.3 of the Market developer distribution agreement: http://www.android.com/us/developer-distribution-agreement.html (The selector to see the version of the agreement for your country is in the upper right corner of the page.)


text:
Q: Integrating the function $ \frac{e^{ipz}}{(\cos z)^{a}} \frac{1}{z- \xi}$ on the complex plane In a paper titled General Theorems in Contour Integration with Some Applications, G.H. Hardy states the following:

Let us integrate
$$ (i) \ \int \frac{e^{ipz}}{(\cos z)^{a}} \frac{\mathrm dz}{z- \xi} \, , $$
$$ (ii) \ \int \frac{e^{ipz}}{(\sin z)^{a}} \frac{\mathrm dz}{z- \xi} \, , $$
round contours $K'$. For the present we suppose $\xi$ not real, and $a <1 ,0 < p + a$; $a$ may be negative. We begin with $(i)$, taking that
value of $(\cos z)^{a}$ which is real at the origin.
As $z$ moves around any one of the points $ \left( n+\frac{1}{2} \right) \pi$, the subject of
integration acquires a factor $e^{ ia \pi}$; and so the contribution
of $\Xi$ is, in the limit,
$$ \sum_{n=-\infty}^{\infty} \int^{(n+\frac{1}{2})\pi}_{(n-\frac{1}{2}) \pi} \frac{e^{i(na \pi + p x)} }{|\cos x |^{a}} \frac{\mathrm dx}{x-\xi} \, ,$$
or
$$\sum_{n=-\infty}^{\infty} \int_{-\frac{\pi}{2}}^{\frac{\pi}{2}} \frac{e^{ipu}}{(\cos u)^{a}} \frac{e^{i n \pi(p+a)}}{u+n \pi - \xi} \, \mathrm du.$$

The contour $K'$ is a closed semicircle in the upper half-plane, and $\Xi$ is the part of the contour that lies just above the real axis.
Since $$ \frac{1}{(\cos z)^{a}} = \frac{e^{-ia \arg (\cos z)}}{|\cos z |^{a}} \, ,$$  Hardy seems to be saying that $\arg (\cos z) = - n \pi$ on $\Xi$ if $\Re(z) \in  \Big( \left(n-\frac{1}{2}\right) \pi, \left(n+ \frac{1}{2} \right)\pi \Big)$.
How exactly is $\log (\cos z)$ being defined here?

A: The author seems to be using branch cuts along the real axis where $|x|\ge\pi/2$. With this branch cut, $\log(\cos(z))$ would be defined by integrating $-\tan(z)$ from $z=0$ (where $\log(\cos(0))=0$). Then
$$
\cos(z)^a=e^{a\log(\cos(z))}
$$
As the point on $\Xi$ passes $\left(n+\tfrac12\right)\pi$, $\log(\cos(z))$ decreases by $\pi i$ (since $-\tan(z)$ has residue $1$ and the contour by passes in a clockwise semi-circle).
$\hspace{3cm}$
Thus, along $\Xi$,
$$
\cos(z)^a=
\begin{array}{}
|\cos(z)|^ae^{-ian\pi}&\text{if }\mathrm{Re}(z)\in\left[\left(n-\tfrac12\right)\pi,\left(n+\tfrac12\right)\pi\right]
\end{array}
$$


text:
Q: Unhandled rejection SequelizeConnectionError - Sequelize MYSQL I am stuck with this error for close 2 days yet could not find a solution to solve this.
I am currently using Sequelize version "^4.37.10" and mysql2 version "^1.5.3". Previously it was working fine until 2 days ago I got hit with this error.
I am not connecting it to a local database but a database from heroku, so I believe the following method which I found online does not really solve my issue:
update user set authentication_string=password(''), plugin='mysql_native_password' where user='root';

Error log:
Unhandled rejection SequelizeConnectionError: Client does not support authentication protocol requested by server; consider upgrading MySQL client
    debuggability.js:868
        at Utils.Promise.tap.then.catch.err (c:\Users\User\Desktop\nodejstest\testmysql\webapp\node_modules\sequelize\lib\dialects\mysql\connection-manager.js:149:19)
        at tryCatcher (c:\Users\User\Desktop\nodejstest\testmysql\webapp\node_modules\bluebird\js\release\util.js:16:23)
        at Promise._settlePromiseFromHandler (c:\Users\User\Desktop\nodejstest\testmysql\webapp\node_modules\bluebird\js\release\promise.js:512:31)
        at Promise._settlePromise (c:\Users\User\Desktop\nodejstest\testmysql\webapp\node_modules\bluebird\js\release\promise.js:569:18)

Did I accidentally deleted some files or what ? How can I solve this ?  I have also tried removing mysql2 and sequelize modules and reinstall but still did not work. Even after deployment to Heroku, this error still exists. Appreciate your help.


text:
Q: How to create metro tiles in JQuery Mobile I'm creating a app in JQuery Mobile, and the home page is metro style. How do I show metro UI? Thanks.

A: You can have a look at this blog. He has listed some awesome themes for jquery mobile.
http://www.gajotres.net

Just search the blog entries.


text:
Q: Problem with SQL query,highest amount of something Hi i have this problem where i need to do this:
-For each trainer who has given only Yoga lessons, show the name, the surname, and the city of the gym where he has given the highest number of lessons.
From this table:
TRAINER (SSN*, NameT, Surname, City)
GYM (CodG*, NameG, Address, City)
SPECIALTY (CodS*, NameS, Description)
LESSON (SSN*, CodG*, Date*, CodS, ParticipantsNumber)
Asterisks are the primary keys. what i have done for now is this:
SELECT T.Name,T.Surname,G.City
FROM TRAINER AS T,LESSON AS L,SPECIALTY AS S,GYM AS G
WHERE T.SSN=L.SSN AND S.CodS=L.CodS AND G.CodG=L.CodG
AND T.SSN NOT IN(/*SSN of instructor who have given at least one lesson other than Yoga*/
                    SELECT T1.SSN
                    FROM TRAINER AS T1,LESSON AS L1,SPECIALTY AS S1
                    WHERE T1.SSN=L1.SSN AND S1.CodS=L1.CodS AND S1.NameS<>'Yoga')

What I really can't do is the part of the gym with the highest amount of lessons, since from what i understood MAX(COUNT *) is not doable, maybe this could be done with correlations between queries but i don't see how.
Any help would be much aprecciated,thanks in advance!
P.S i mainly use APEX ORACLE

A: For each person/gym combination, you can use a aggregation to count the classes and use conditional aggregation to count if any were not yoga; then, avoiding querying the tables twice, you can use analytic functions to rank the gyms and total the number of non-yoga lessons; and finally, in the outer query, can filter for only those highest-ranked lessons where there were no non-yoga lessons:
SELECT namet, surname, city
FROM   (
  SELECT l.ssn,
         MAX(namet) AS namet,
         MAX(surname) AS surname,
         g.codg,
         MAX(city) AS city,
         SUM(COUNT(CASE WHEN s.NameS  <> 'Yoga' THEN 1 END))
           OVER (PARTITION BY l.ssn)
           AS num_other_lessons,
         RANK() OVER (PARTITION BY l.ssn ORDER BY COUNT(*) DESC) AS gym_rank
  FROM   lesson l
         INNER JOIN trainer t   ON (l.ssn = t.ssn)
         INNER JOIN gym g       ON (l.codg = g.codg)
         INNER JOIN specialty s ON (l.cods = s.cods)
  GROUP BY
         l.ssn,
         g.codg
)
WHERE  num_other_lessons = 0
AND    gym_rank = 1

Which, for the sample data:
CREATE TABLE TRAINER (SSN PRIMARY KEY, NameT, Surname) AS
SELECT 1, 'Alice', 'Abbot' FROM DUAL UNION ALL
SELECT 2, 'Betty', 'Baron' FROM DUAL UNION ALL
SELECT 3, 'Carol', 'Count' FROM DUAL;

CREATE TABLE GYM (CodG PRIMARY KEY, NameG, City) AS
SELECT 10, 'GymA', 'Adelaide' FROM DUAL UNION ALL
SELECT 11, 'GymB', 'Berlin'   FROM DUAL UNION ALL
SELECT 12, 'GymC', 'Caracas'  FROM DUAL UNION ALL
SELECT 13, 'GymD', 'Dubai'    FROM DUAL;

CREATE TABLE SPECIALTY (CodS PRIMARY KEY, NameS, Description) AS
SELECT 20, 'Yoga',      'Descr1' FROM DUAL UNION ALL
SELECT 21, 'Not Yoga',  'Descr2' FROM DUAL;

CREATE TABLE LESSON (SSN, CodG, "DATE", CodS, ParticipantsNumber,
  PRIMARY KEY (SSN, CodG, "DATE")
) AS
SELECT 1, 10, DATE '1970-01-01' + LEVEL - 1, 20, 1 FROM DUAL CONNECT BY LEVEL <= 4 UNION ALL
SELECT 1, 11, DATE '1970-01-01' + LEVEL - 1, 20, 1 FROM DUAL CONNECT BY LEVEL <= 3 UNION ALL
SELECT 2, 10, DATE '1970-01-01' + LEVEL - 1, 20, 1 FROM DUAL CONNECT BY LEVEL <= 2 UNION ALL
SELECT 2, 12, DATE '1970-01-01' + LEVEL - 1, 21, 1 FROM DUAL CONNECT BY LEVEL <= 1 UNION ALL
SELECT 3, 10, DATE '1970-01-01' + LEVEL - 1, 20, 1 FROM DUAL CONNECT BY LEVEL <= 1 UNION ALL
SELECT 3, 13, DATE '1970-01-01' + LEVEL - 1, 20, 1 FROM DUAL CONNECT BY LEVEL <= 3;

Outputs:

NAMET
SURNAME
CITY

Alice
Abbot
Adelaide

Carol
Count
Dubai

db<>fiddle here

A: I would do something like this:
select t.namet, t.surname, g.city
from   (
  select ssn, min(codg) keep (dense_rank last order by cnt) as codg
  from   (
    select ssn, codg, count(*) as cnt
    from   lesson
    where  ssn in (
             select ssn
             from   trainer
             where  ssn not in (
               select l.ssn
               from   lesson l join specialty s on l.cods = s.cods
               where  s.names <> 'Yoga'
             )
           )
    group  by ssn, codg
  )
  group  by ssn
) sq
       join trainer t on t.ssn  = sq.ssn
       join gym     g on g.codg = sq.codg
;

The heavy lifting is done in the subquery sq - finding the ssn of trainers who only teach Yoga, then for each such teacher counting lessons at each gym and selecting only the gym with the highest number of lessons (the gym with the lowest code among the highest-count gyms, in case of ties). Note the aggregate function last used in the select list: min(codg) keep (dense_rank LAST order by cnt) This is a very useful aggregate function that many programmers apparently never learn about.
Then the rest is a trivial join to the trainers and gyms tables.
Note - while I didn't use the with clause (perhaps they didn't teach it yet), I still chose to use modern, ANSI join syntax, rather than what they seem to teach you. You may want to ask your instructors: (1) why they are using the old Oracle join syntax, which even Oracle themselves recommend against; and (2) check the column name DATE in your last table. That is a reserved keyword; it can't be used as a column name. Your instructor should know better.

A: Start by adding count(1) as num_times to the original query , then use row_number() to find out the rank, then filter out only those with _rank=1
with data as (
SELECT T.Name,T.Surname,G.City, count(1) as num_times
FROM TRAINER AS T,LESSON AS L,SPECIALTY AS S,GYM AS G
WHERE T.SSN=L.SSN AND S.CodS=L.CodS AND G.CodG=L.CodG
AND T.SSN NOT IN(/*SSN of instructor who have given at least one lesson other than Yoga*/
                    SELECT T1.SSN
                    FROM TRAINER AS T1,LESSON AS L1,SPECIALTY AS S1
                    WHERE T1.SSN=L1.SSN AND S1.CodS=L1.CodS AND S1.NameS<>'Yoga'),
first_pass as (
group by T.Name,T.Surname,G.City)
select
*, row_number() over (partition by name, surname order by num_times desc) as _rank
)
select * from first_pass where _rank = 1


text:
Q: Import SQLAlchemy into my project Environment:

*

*Python 2.7.5

*SQLAlchemy 0.9.6

What I've done:
I want to include the SQLAlchemy source into my project for different reasons. The main reason is to avoid any virtual environments for my users later.
Okay my structure looks like this:
$ tree . -L 2
myapp
├── libs
│   ├── ...
│   └── sqlalchemy
├── myapp
│   └── ...
└── MyApp.py

Okay I add the libs path to the system path.
### MyApp.py
# ...
BASE_DIR = os.path.dirname(__file__)
LIBRARY_DIR = os.path.join(BASE_DIR, 'libs')
sys.path.append(LIBRARY_DIR)
# ...

When I now try to import from libs.sqlalchemy.orm
from libs.sqlalchemy.orm import relationship

I get an error
Traceback (most recent call last):
  File "/.../myapp/MyApp.py", line 13, in <module>
    from libs.sqlalchemy.orm import relationship
  File "/.../myapp/libs/sqlalchemy/orm/__init__.py", line 69, in <module>
    from . import strategies as _strategies
  File "/.../myapp/libs/sqlalchemy/orm/strategies.py", line 301, in <module>
    @properties.RelationshipProperty.strategy_for(lazy="noload")
AttributeError: 'module' object has no attribute 'RelationshipProperty'

This is where the traceback points to
### ./libs/sqlalchemy/orm/strategies.py
@log.class_logger
@properties.RelationshipProperty.strategy_for(lazy="noload") # <- here
@properties.RelationshipProperty.strategy_for(lazy=None)
class NoLoader(AbstractRelationshipLoader):
    # ...

Actual question:
What do I have missed / done wrong?
I've downloaded the tar.gz from here and copied the lib/sqlalchemy folder to my lib path

A: Just unpackig tar file is not going to work for alchemy, because it has native libraries that need to be compiled, so you can
sudo pip install alchemy or
untar your tar.gz and run "python setup.py install"

This is what "pip install" is doing:
Installing collected packages: sqlalchemy
  Running setup.py install for sqlalchemy
    building 'sqlalchemy.cprocessors' extension
    /usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -arch i386 -g -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c lib/sqlalchemy/cextension/processors.c -o build/temp.macosx-10.3-fat-2.7/lib/sqlalchemy/cextension/processors.o
    /usr/bin/clang -bundle -undefined dynamic_lookup -arch i386 -g build/temp.macosx-10.3-fat-2.7/lib/sqlalchemy/cextension/processors.o -o build/lib.macosx-10.3-fat-2.7/sqlalchemy/cprocessors.so
    building 'sqlalchemy.cresultproxy' extension
    /usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -arch i386 -g -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c lib/sqlalchemy/cextension/resultproxy.c -o build/temp.macosx-10.3-fat-2.7/lib/sqlalchemy/cextension/resultproxy.o
    /usr/bin/clang -bundle -undefined dynamic_lookup -arch i386 -g build/temp.macosx-10.3-fat-2.7/lib/sqlalchemy/cextension/resultproxy.o -o build/lib.macosx-10.3-fat-2.7/sqlalchemy/cresultproxy.so
    building 'sqlalchemy.cutils' extension
    /usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -arch i386 -g -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c lib/sqlalchemy/cextension/utils.c -o build/temp.macosx-10.3-fat-2.7/lib/sqlalchemy/cextension/utils.o
    /usr/bin/clang -bundle -undefined dynamic_lookup -arch i386 -g build/temp.macosx-10.3-fat-2.7/lib/sqlalchemy/cextension/utils.o -o build/lib.macosx-10.3-fat-2.7/sqlalchemy/cutils.so


text:
Q: render only the content on a page that is currently visible I have a web page that displays a list of testimonials along with an  tag beside each entry.
It looks like this:

  Name

  Testimonial

  Subject

  Joe Blow

  I had a great stay...

...

Basically this can serve up to 100 entries at once and it freezes up the browser very often - particularly because I probably haven't totally optimized all the imgae file sizes and some of them are more than 1MB.
What I would like to find out is how I can make it so the  tag doesn't render into the browser until the end-user scrolls and it becomes visible in their viewport.

This would save a lot of cost on my server and also not freeze up all my user's browsers.
Anybody have any ideas?

A: You could bind events to the img tags that are triggered when they are being displayed in viewport. You could use this solution to do this: jquery trigger function when element is in viewport
So when the event is triggered you just have to use .setAttribute to set the src attribute of the img tag.

A: What you are trying to accomplish is called Lazy Loading, and i believe there are several tools or js libraries for this on the internet.
Now, for the drawback of this functionality, i would say that being on a mobile phone, the internet is not fast, and at first the user might have some issue viewing the pictures, as they will be downloading.
But this is up to you.
Hope this helps.
Links:
Lazy Loading css-tricks.com
jQuery Unveil
jQuery Lazy Load


text:
Q: Make all windows open in the center of the screen on Kubuntu I've looked everywhere in the window management settings, and I can't find a setting to change the window placement setting like there is in Compiz Config Settings Manager. I want all of the windows to open in the center of the display that has the mouse on it, not the one that has the selected window. (I usually have 2 displays connected)

A: In Kubuntu you can choose the placement of opening windows under
System Settings>Workspaces>Window Mangement>Window Behavior>Advanced-tab> Placement