text:
Q: Using own handler for Jquery Oembed I'm trying to use my own function (never liked $(document).ready()) to dynamically load  an embed from an URL.
I'm trying like this:
function video(donde,url) {
    $("#"+donde).oembed(url);
    return false;
}

And an example of use would be:

  [my title]

       [my description]

Which jumps:
b.type is not a function
[Interrumpir en este error] b.ready);var j=false;try{j=E.frameElem...ow(j))return false;if(j.constructor&&

Onclick vía firebug :(
Any idea what I'm missing? The error source file is jquery.min.js :S

A: You're not missing anything, you found a bug in the oembed plugin. Nice find, maybe you have a future career in quality assurance :)
Looks like both oembed and jQuery want to use .type but jQuery is ending up with oembed's string .type where it wants its own function .type.
The oembed plugin works fine with jQuery-1.3.2 but breaks as of jQuery-1.4.3.
You can pull a functional version of the oembed plugin from this jsfiddle: http://jsfiddle.net/ambiguous/ZVhUn/1/
This problem has been reported several times but the oembed author doesn't seem to be listening. Here's a fixed version of the plugin if you want it:
(function($) {
    $.fn.oembed = function(url, options, callback) {

        options = $.extend(true, $.fn.oembed.defaults, options);

        return this.each(function() {

            var container = $(this),
                resourceURL = (url != null) ? url : container.attr("href"),
                provider;

            if (!callback) callback = function(container, oembed) {
                 $.fn.oembed.insertCode(container, options.embedMethod, oembed);
            };

            if (resourceURL != null) {
                provider = getOEmbedProvider(resourceURL);

                if (provider != null) {
                    provider.params = getNormalizedParams(options[provider.name]) || {};
                    provider.maxWidth = options.maxWidth;
                    provider.maxHeight = options.maxHeight;
                    provider.embedCode(container, resourceURL, callback);
                    return;
                }
            }

            callback(container, null);
        });
    };

    // Plugin defaults
    $.fn.oembed.defaults = {
        maxWidth: null,
        maxHeight: null,
        embedMethod: "replace" // "auto", "append", "fill"
    };

    $.fn.oembed.insertCode = function(container, embedMethod, oembed) {
        if (oembed == null)
            return;
        switch(embedMethod)
        {
            case "auto":
                if (container.attr("href") != null) {
                    $.fn.oembed.insertCode(container, "append", oembed);
                }
                else {
                    $.fn.oembed.insertCode(container, "replace", oembed);
                };
                break;
            case "replace":
                container.replaceWith(oembed.code);
                break;
            case "fill":
                container.html(oembed.code);
                break;
            case "append":
                var oembedContainer = container.next();
                if (oembedContainer == null || !oembedContainer.hasClass("oembed-container")) {
                    oembedContainer = container
                        .after('

')
                        .next(".oembed-container");
                    if (oembed != null && oembed.provider_name != null)
                        oembedContainer.toggleClass("oembed-container-" + oembed.provider_name);
                }
                oembedContainer.html(oembed.code);
                break;
        }
    };

    $.fn.oembed.getPhotoCode = function(url, data) {
        var alt = data.title ? data.title : '';
        alt += data.author_name ? ' - ' + data.author_name : '';
        alt += data.provider_name ? ' - ' +data.provider_name : '';
        var code = '

';
        if (data.html)
            code += "
" + data.html + "
";
        return code;
    };

    $.fn.oembed.getVideoCode = function(url, data) {
        var code = data.html;
        return code;
    };

    $.fn.oembed.getRichCode = function(url, data) {
        var code = data.html;
        return code;
    };

    $.fn.oembed.getGenericCode = function(url, data) {
        var title = (data.title != null) ? data.title : url,
            code = '' + title + '';
        if (data.html)
            code += "
" + data.html + "
";
        return code;
    };

    $.fn.oembed.isAvailable = function(url) {
        var provider = getOEmbedProvider(url);
        return (provider != null);
    };

    /* Private Methods */
    function getOEmbedProvider(url) {
        for (var i = 0; i < providers.length; i++) {
            if (providers[i].matches(url))
                return providers[i];
        }
        return null;
    }

    function getNormalizedParams(params) {
        if (params == null)
            return null;
        var normalizedParams = {};
        for (var key in params) {
            if (key != null)
                normalizedParams[key.toLowerCase()] = params[key];
        }
        return normalizedParams;
    }

    var providers = [
        new OEmbedProvider("fivemin", "5min.com"),
        new OEmbedProvider("amazon", "amazon.com"),
        new OEmbedProvider("flickr", "flickr", "http://flickr.com/services/oembed", "jsoncallback"),
        new OEmbedProvider("googlevideo", "video.google."),
        new OEmbedProvider("hulu", "hulu.com"),
        new OEmbedProvider("imdb", "imdb.com"),
        new OEmbedProvider("metacafe", "metacafe.com"),
        new OEmbedProvider("qik", "qik.com"),
        new OEmbedProvider("revision3", "revision3.com"),
        new OEmbedProvider("slideshare", "slideshare.net"),
        new OEmbedProvider("twitpic", "twitpic.com"),
        new OEmbedProvider("viddler", "viddler.com"),
        new OEmbedProvider("vimeo", "vimeo.com", "http://vimeo.com/api/oembed.json"),
        new OEmbedProvider("wikipedia", "wikipedia.org"),
        new OEmbedProvider("wordpress", "wordpress.com"),
        new OEmbedProvider("youtube", "youtube.com"),
        new OEmbedProvider("vids.myspace.com", "vids.myspace.com", "http://vids.myspace.com/index.cfm?fuseaction=oembed"),
        new OEmbedProvider("screenr", "screenr.com", "http://screenr.com/api/oembed.json")
    ];

    function OEmbedProvider(name, urlPattern, oEmbedUrl, callbackparameter) {
        this.name = name;
        this.urlPattern = urlPattern;
        this.oEmbedUrl = (oEmbedUrl != null) ? oEmbedUrl : "http://oohembed.com/oohembed/";
        this.callbackparameter = (callbackparameter != null) ? callbackparameter : "callback";
        this.maxWidth = 500;
        this.maxHeight = 400;

        this.matches = function(externalUrl) {
            // TODO: Convert to Regex
            return externalUrl.indexOf(this.urlPattern) >= 0;
        };

        this.getRequestUrl = function(externalUrl) {

            var url = this.oEmbedUrl;

            if (url.indexOf("?") <= 0)
                url = url + "?";
            else
                url = url + "&";

            var qs = "";

            if (this.maxWidth != null && this.params["maxwidth"] == null)
                this.params["maxwidth"] = this.maxWidth;

            if (this.maxHeight != null && this.params["maxheight"] == null)
                this.params["maxheight"] = this.maxHeight;

            for (var i in this.params) {
                // We don't want them to jack everything up by changing the callback parameter
                if (i == this.callbackparameter)
                  continue;

                // allows the options to be set to null, don't send null values to the server as parameters
                if (this.params[i] != null)
                    qs += "&" + escape(i) + "=" + this.params[i];
            }

            url += "format=json&url=" + escape(externalUrl) +
                    qs +
                    "&" + this.callbackparameter + "=?";

            return url;
        };

        this.embedCode = function(container, externalUrl, callback) {

            var request = this.getRequestUrl(externalUrl);

            $.getJSON(request, function(data) {

                var code, type = data.type;
                var oembed = $.extend({ }, data);

                switch (type) {
                    case "photo":
                        oembed.code = $.fn.oembed.getPhotoCode(externalUrl, data);
                        break;
                    case "video":
                        oembed.code = $.fn.oembed.getVideoCode(externalUrl, data);
                        break;
                    case "rich":
                        oembed.code = $.fn.oembed.getRichCode(externalUrl, data);
                        break;
                    default:
                        oembed.code = $.fn.oembed.getGenericCode(externalUrl, data);
                        break;
                }

                callback(container, oembed);
            });
        };
    }
})(jQuery);

The only change is that I replaced var oembed = $.extend(data); with var oembed = $.extend({ }, data); in this.embedCode at the bottom of the file.


text:
Q: how to draw non-uniform colorbar in matplotlib Tried the midnorm and listed colormap, but do not know how to turn the front 0-20 into uniform multi-color (the picture shows the abbreviation, please do not mind), do not know how to draw the effect of the picture! ! Help

A: In this case it makes sense to use a BoundaryNorm and a ListedColormap. Define the N+1 bounaries for the N colors of the colormap and use spacing="proportional" in the colorbar call.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm, ListedColormap

cmap = ListedColormap(["black", "darkred", "crimson", "salmon", "navy", "violet", "yellow"])
bounds = [0,1,2,3,4,10,20,30]
norm = BoundaryNorm(bounds, cmap.N)

fig, ax = plt.subplots()
sc = ax.scatter(*np.random.rand(2,100), c=np.random.rand(100)*30, cmap=cmap, norm=norm)
fig.colorbar(sc, orientation="horizontal", spacing="proportional")

plt.show()

A: I think you should use
MyCmap=colors.LinearSegmentedColormap.from_list("", list(zip(lvals,cvals)))

as in this solution (even if it is for a logarithmic scale there). Look at the end of the accepted answer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to adjust the order of file sorting? I am trying to evalute my Lab data, what are represtned into TXT files then plot the conntents of data.
      dataDirectory = 'files location  ';
      allFilesDir = dir(fullfile(dataDirectory , '*.txt'));
      allFN = {allFilesDir.name};

      result = [];

      for n = 1:length(allFN)
      measNr(n) = str2double(regexprep(allFN{n},'**.txt',''));

      myFN = (fullfile(dataDirectory, allFN{n}));
      auxv =try1(myFN);
      result(n,:) = mean(auxv.data);
      end

This code is workin but into wrong order arrangemnt the TXT files (0,1,11,12,13,14 .....)
which give me wrong plot data. I used
       plot(measNr,resultMG(1:35,2),'x');

but i read that i can use sort_nat in this way but it did not work for me .
       % [~, order] = sort_nat({result});
       % result = result(order);

and I got this error messge
       :??? Undefined function or method 'sort_nat' for input arguments of type
       'cell'.:

any suggestion???

A: As the error message clearly suggests, sort_nat is not a builtin function.
It is a function available on the file exchange:
http://www.mathworks.com/matlabcentral/fileexchange/10959-sortnat-natural-order-sort


text:
Q: How to write a trigger handler with trigger new I am having some trouble to translate my trigger to a trigger handler how do I deal with the  for(Invoice__c record:Trigger.new) part?
Trigger:
trigger UpdateAutoNumber on Invoice__c (before insert) {
    // Provide default values if settings do not exist.
    InvoiceCounter__c  settings = new InvoiceCounter__c (name='Invoice__c',Amsterdam__c =0,London__c =0, Los_Angeles__c  =0, New_York__c =0, Shanghai__c =0, Tokyo__c=0);
    // Try and load the custom settings.
    for(InvoiceCounter__c  setting:[select id, name , Amsterdam__c, London__c, Los_Angeles__c, New_York__c, Shanghai__c, Tokyo__c  from InvoiceCounter__c  where name='Invoice__c'])
        settings = setting;
    // Loop through the records in the trigger.
    for(Invoice__c record:Trigger.new) {
        if(record.Department__c == 'Amsterdam') {
            record.Invoice_number__c   = 'Amsterdam-' + String.valueOf(settings.Amsterdam__c ++);
        }
        if(record.Department__c == 'London') { record.Invoice_number__c  = 'London-' + String.valueOf(settings.London__c ++);
                                             }
        if(record.Department__c == 'Los Angeles') { record.Invoice_number__c  = 'Los Angeles-' + String.valueOf(settings.Los_Angeles__c ++);
                                                  }
        if(record.Department__c == 'New York') {
            record.Invoice_number__c  = 'New York-' + String.valueOf(settings.New_York__c ++);
        }
        if(record.Department__c == 'Shanghai') {
            record.Invoice_number__c  = 'Shanghai-' + String.valueOf(settings.Shanghai__c ++);
        }
        if(record.Department__c == 'Tokyo') {
            record.Invoice_number__c  = 'Tokyo-' + String.valueOf(settings.Tokyo__c ++);
        }
    }
    upsert settings;
}

My Trigger & Handler
trigger UpdateAutoNumber on Invoice__c (before insert) {

    UpdateAutonumberHandler handler = new UpdateAutonumberHandler();

    if(Trigger.isInsert){
        handler.OnBeforeInsert(Invoice__c record Trigger.new);
    }

}

public class UpdateAutonumberHandler {

    public static void OnBeforeInsert(List<Invoice__c> record){
     // Provide default values if settings do not exist.
    InvoiceCounter__c  settings = new InvoiceCounter__c (name='Invoice__c',Amsterdam__c =0,London__c =0, Los_Angeles__c  =0, New_York__c =0, Shanghai__c =0, Tokyo__c=0);
    // Try and load the custom settings.
    for(InvoiceCounter__c  setting:[select id, name , Amsterdam__c, London__c, Los_Angeles__c, New_York__c, Shanghai__c, Tokyo__c  from InvoiceCounter__c  where name='Invoice__c'])
        settings = setting;
    // Loop through the records in the trigger.

        if(record.Department__c == 'Amsterdam') {
            record.Invoice_number__c   = 'Amsterdam-' + String.valueOf(settings.Amsterdam__c ++);
        }
        if(record.Department__c == 'London') { record.Invoice_number__c  = 'London-' + String.valueOf(settings.London__c ++);
                                             }
        if(record.Department__c == 'Los Angeles') { record.Invoice_number__c  = 'Los Angeles-' + String.valueOf(settings.Los_Angeles__c ++);
                                                  }
        if(record.Department__c == 'New York') {
            record.Invoice_number__c  = 'New York-' + String.valueOf(settings.New_York__c ++);
        }
        if(record.Department__c == 'Shanghai') {
            record.Invoice_number__c  = 'Shanghai-' + String.valueOf(settings.Shanghai__c ++);
        }
        if(record.Department__c == 'Tokyo') {
            record.Invoice_number__c  = 'Tokyo-' + String.valueOf(settings.Tokyo__c ++);
        }

    upsert settings;

}

A: You don't need to specify the type or name of parameters when calling methods in Apex.
This:
handler.OnBeforeInsert(Invoice__c record Trigger.new);

Should be:
handler.OnBeforeInsert(Trigger.new);

Trigger.new is a list of Invoice__c records, i.e. it is of the type List<Invoice__c> which is what your method expects for the record parameter:
public static void OnBeforeInsert(List<Invoice__c> record){

which, while we're at it, should probably be called records since it's a collection, not a singular Invoice__c.


text:
Q: How to block installation of other application using device administrator app in android How to block installation of other application using device administrator app in android. How can we code it to restrict the installation of the application using device administration application?
please help me out.

A: As far as I know for android version up to ICS (<= 3.2) Your app (device admin) cannot block installation of another apps. You can only handle the even that new app was installed/uninstalled.

A: I guess you should create a receiver for this action  android.app.action.ACTION_INSTALL_PACKAGE check if the package is the one you want to block also follow the instructions from the Android page on How to create Device Admin Applications


text:
Q: Most efficient way to redirect several TLD's sharing a common root to one primary domain using htaccess I'm using the following code (repeated) to redirect 6 additional TLDs to one primary TLD. is there a more efficient way to achieve the same result?
RewriteEngine on
RewriteCond %{HTTP_HOST} !^(www\.)?mydomain\.com$ [NC]
RewriteRule .?$ http://www.mydomain.com%{REQUEST_URI} [R=301,L]

A: RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.domain\.org$ [NC]
RewriteRule ^(.*)$ http://www.domain.org$1 [R=301,L]

This redirects any domain which is not .org to .org

A: If there are a lot of domains, you may want to look at RewriteMap which will allow you to create external maps, but this would need to be in your server/vhost config, won't work in an .htaccess file. Other than that, this is the usual way to do this.


text:
Q: Do I need to add all HttpClients? If I use _httpClientFactory.CreateClient() in a singleton (no name for the client, I set it up when I use it)
Should I add/specify an empty services.AddHttpClient(); at startup or is that not necessary?

A: You should only specify empty services.AddHttpClient(); on startup. You could pass it name parameter if you want to configure "specific" HttpClient that you will later call by name (for example add base address or headers). Otherwise IHttpClientFactory will give you not configured one (like calling new HttpClient())
For example:
services.AddHttpClient("MyApiClient").ConfigureHttpClient(client =>
{
    client.BaseAddress = new Uri(configuration["MyApiUrl"]);
});

and later calling factory like:
_httpClientFactory.CreateClient("MyApiClient");

will give you HttpClient with configured base address.

A: The services.AddHttpClient(); in your startup class is used to configure an IHttpClientFactory instance,
which is then used to create and manage named HttpClient instances.
If you are creating an instance of HttpClient directly with _httpClientFactory.CreateClient(), without specifying a named client,
what i suggest is you don't need to add the services.AddHttpClient(); line in the Startup class.
FACT:
This line is necessary only if you plan to use the IHttpClientFactory to create named HttpClient instances.
for More visit: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-7.0


text:
Q: Change the screen in a button in TabBar I have two main screens:

*

*FIRST (with Bottom Bar contains 3 tabs)

*SECOND (standard new screen)

How to make clicking the button in BottomTabBar opens a new screen?
By default, the buttons in Bottom Bar open a new tab. I would like one button to open a whole new screen
Just like it is on the screen

Screen code with Tab (3 elements):
function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator tabBarOptions={{
        showLabel: true,
        style: {
          backgroundColor: 'transparent',
          position: 'absolute',
          borderTopWidth: 0,
          elevation: 0,
        }
      }}>
        <Tab.Screen name="Home" component={Home}/>
        <Tab.Screen name="Second" component={Second}/>
        <Tab.Screen name="Other" component={Other} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

A: You may try this:
<Tab.Screen
        options={({navigation}) => ({
            tabBarButton: props =>
                <TouchableOpacity {...props} onPress={() => navigation.navigate('YourScreen')} />
        })}
        name="Second" component={Second}
/>

You can navigate to new screen if that screen is not included in your bottom tab :)
You can find more in here: https://reactnavigation.org/docs/bottom-tab-navigator#tabbarbutton
Hope that help :)


text:
Q: boost::any test code compiles with Sun CC but not g++ The following noddy test code:
#include <iostream>
#include <list>
#include <boost/any.hpp>
#include <boost/foreach.hpp>
#include <typeinfo.h>

using boost::any_cast;
using std::cout;
using std::cerr;
typedef std::list<boost::any> many;

template <typename T>
inline bool is_any(const boost::any& op)
{
  return (op.type() == typeid(T));
}

int main()
{
  many theStrangeList;
  theStrangeList.push_back("Can you really...");
  theStrangeList.push_back(std::string ("do random types in 1 container?"));
  theStrangeList.push_back(6.359);
  theStrangeList.push_back(7);

  BOOST_FOREACH(boost::any a, theStrangeList)
    {
      try
        {
          if (is_any<const char*>(a))
            {
              cout << any_cast<const char*>(a) << '\n';
            }
          else if (is_any<std::string>(a))
            {
              cout << any_cast<std::string>(a) << '\n';
            }
          else if (is_any<double>(a))
            {
              cout << "double = " << any_cast<double>(a) << '\n';
            }

        }
      catch (const boost::bad_any_cast& e)
        {
          cerr << e.what();
          cerr << "\n";
        }
    }

  return 0;
}

Compiles and works fine using Sun's CC compiler and default settings.
However when using g++  I get the following :
$ g++ -I$BOOST_ROOT -o myany myany.cpp
myany.cpp:5:22: typeinfo.h: No such file or directory
/ilx/boost_1_41_0/boost/any.hpp: In constructor `boost::any::holder<ValueType>::holder(const ValueType&) [with ValueType = char[18]]':
/ilx/boost_1_41_0/boost/any.hpp:47:   instantiated from `boost::any::any(const ValueType&) [with ValueType = char[18]]'
myany.cpp:21:   instantiated from here
/ilx/boost_1_41_0/boost/any.hpp:122: error: ISO C++ forbids assignment of arrays

This is g++ version 3.4.3, so it might be different on a 4.x version, I'll try it later. Is this the reason why there isn't a 'is_any' template included with boost any, or is it a compiler bug?
I get the same result if I remove the template, as you would expect with an inlined function.
(related question)

A: For the first error try
#include <typeinfo>

not
#include <typeinfo.h>

A: Seems I only answered the second part of the question, so here I go with the first part as well:
Is this the reason why there isn't a 'is_any' template included with boost any?
There are no actual need to is_any, do the following instead:
if (const std::string* s = boost::any_cast<std::string>(&a))
{
   std::cout << "string = " << *s << '\n';
}
else if (const double* d = boost::any_cast<double>(&a))
{
   std::cout << "double = " << *d << '\n';
}

But this isn't extensible, prefer using boost::variant instead.
Is it a compiler bug?
It is a compiler bug in Sun CC. gcc is correct, the type of "Can you really..." is char[18], which doesn't satisfy the requirements of boost::any:

*

*A ValueType is CopyConstructible.

*A ValueType is optionally Assignable. The strong exception-safety guarantee is required for all forms of assignment.

*The destructor for a ValueType upholds the no-throw exception-safety guarantee.


text:
Q: Протокол регистрации на сервере телефонии sip Я не могу понять как авторизоваться на сервере sip. В описании написано, что надо отправить тестовый запрос REGISTER, и на него придёт ответ с тем, что нет логина с паролем, но что самое важное, так это придет nonce. Я в rfc не нашел описание, какой надо запрос отправлять для сервера, и в интернете нет описания. даже на хабре нет. никто не знаю как будто. я много уже что перепробовал и так и не понял, что надо в запросе отправить, чтобы пришел nonce, чтобы я мог сделать запрос нормальный. я начал делать свою библиотеку, потому что так и не понял как использовать чужие. вот что я отправляю на сервер и что приходит.
->REGISTER sip:sip.zadarma.com SIP/2.0
Via: SIP/2.0/TCP 160104@sip.zadarma.com:5060;branch=Z8dna3DHbNFo
Authorization: Digest username="160104", realm="sip.zadarma.com", uri="sip:160104@sip.zadarma.com"
CSeq: 1826 REGISTER

<-202:SIP/2.0 400 Missing Required Header in Request
Via: SIP/2.0/TCP 160104@sip.zadarma.com:5060;branch=Z8dna3DHbNFo;received=89.221.20.15
CSeq: 1826 REGISTER
Server: Zadarma server
Content-Length: 0


text:
Q: libreoffice base create a list filtered by another list's value I have a table of provinces and a table of cities with ProvienceID. In a form, I want to create a list of cities filtered by selected value of provience list.
How can I do that?
I can create both lists but Cities list shows all cities from all provinces but i want to show only cities from the province that I have selected in Provinces list.
I have another table "Users" with "CityID" and "ProvinceID" that my form edits it and I need to save selected values of Province and City Lists in it, not only show it in the form.

A: Create two example tables named "Provinces" and "Cities".
ProvinceID  Name
~~~~~~~~~~  ~~~~
0           South
1           North
2           Large Midwest
3           Southeast
4           West

CityID  Name              ProvinceID
~~~~~~  ~~~~              ~~~~~~~~~~
0       Big City          2
1       Very Big City     2
2       Rural Village     1
3       Mountain Heights  0
4       Coastal Plains    4
5       Metropolis        2

Create a query called "ProvinceNames":
SELECT "Name" AS "Province"
FROM "Provinces"
ORDER BY "Province" ASC

Create a query called "Province of City":
SELECT "Provinces"."Name" AS "Province", "Cities"."Name" AS "City"
FROM "Cities", "Provinces" WHERE "Cities"."ProvinceID" = "Provinces"."ProvinceID"
ORDER BY "Province" ASC, "City" ASC

In the form, create a table control based on the query "ProvinceNames".
Using the Form Navigator (or the Form Wizard), create a subform for query "Province of City".

Right-click on subform and choose Properties.  Under Data tab:

*

*Link master fields "Province"

*Link slave fields "Province"

Create a table control for the subform as well.  Now, the cities shown in the subform control depend on the province selected in the main form control.

EDIT:
Here is an example using a filter table to store the current value of the list box.  Create two more tables named "Users" and "FilterCriteria".
UserID  Name     ProvinceID  CityID
~~~~~~  ~~~~~~~  ~~~~~~~~~~  ~~~~~~
0       Person1  1           2
1       Person2  2           0

RecordID  ProvinceID  CityID
~~~~~~~~  ~~~~~~~~~~  ~~~~~~
the only  0           0

We'll also need two Basic macros which can be stored in the document or in My Macros.  Go to Tools -> Macros -> Organize Macros -> LibreOffice Basic.
Sub ReadProvince (oEvent as Object)
    forms = ThisComponent.getDrawPage().getForms()
    mainForm = forms.getByName("MainForm")
    cityForm = forms.getByName("CityForm")
    listboxProvince = mainForm.getByName("listboxProvince")
    listboxCity = cityForm.getByName("listboxCity")
    selectedItemID = listboxProvince.SelectedValue
    If IsEmpty(selectedItemID) Then
        selectedItemID = 0
    End If
    conn = mainForm.ActiveConnection
    stmt = conn.createStatement()
    strSQL = "UPDATE ""FilterCriteria"" SET ""ProvinceID"" = " & selectedItemID & _
             "WHERE ""RecordID"" = 'the only'"
    stmt.executeUpdate(strSQL)
    listboxCity.refresh()
    lCityCol = mainForm.findColumn("CityID")
    currentCityID = mainForm.getInt(lCityCol)
    cityForm.updateInt(cityForm.findColumn("CityID"), currentCityID)
    listboxCity.refresh()
End Sub

Sub CityChanged (oEvent as Object)
    listboxCity = oEvent.Source.Model
    cityForm = listboxCity.getParent()
    mainForm = cityForm.getParent().getByName("MainForm")
    lCityCol = mainForm.findColumn("CityID")
    selectedItemID = listboxCity.SelectedValue
    If IsEmpty(selectedItemID) Then
        selectedItemID = 0
    End If
    mainForm.updateInt(lCityCol, selectedItemID)
End Sub

Now we need to set up the form like this.  In this example, I used two top-level forms instead of a subform.  ProvinceID and CityID text boxes are not required but may be helpful in case something goes wrong.

To start creating this form, use the form wizard to create a new form and add all fields from the Users table.
Now, in the Form Navigator, create a form called "CityForm".  Content type is SQL command, and Content is:
SELECT "RecordID", "ProvinceID", "CityID" FROM "FilterCriteria"
WHERE "RecordID" = 'the only'

Next, create the "listboxProvince" list box under MainForm.  Data Field is "ProvinceID", and List content is the following Sql.
SELECT "Name", "ProvinceID" FROM "Provinces" ORDER BY "Name" ASC

Finally, create the "listboxCity" list box under CityForm.  Data Field is "CityID", and List content is the following Sql.
SELECT "Name", "CityID" FROM "Cities" WHERE "ProvinceID" = (
    SELECT "ProvinceID" FROM "FilterCriteria"
    WHERE "RecordID" = 'the only')

Macros are linked under the Events tab of each control.

*

*Assign "After record change" of the MainForm to ReadProvince().

*Assign "Changed" of listboxProvince to ReadProvince().

*Assign "Changed" of listboxCity control to CityChanged().

The result allows us to select the Province to filter the list of Cities.  Provinces and Cities that are selected are saved in the Users table.

There is another approach which may be better that I have not had time to explore.  Instead of the "FilterCriteria" table, apply a filter to the Cities list.  The relevant code in ReadProvince() would look something like this.
cityForm.Filter = "ProvinceID=" & selectedItemID
cityForm.ApplyFilter = True
cityForm.reload()
cityForm.absolute(0)

Whatever approach is taken, a complete solution requires complex macro programming.  To make it easier, you may decide to use a simpler solution that is not as powerful.  For more information, there is a tutorial at https://forum.openoffice.org/en/forum/viewtopic.php?t=46470.
EDIT 2
A solution that requires fewer queries is at https://ask.libreoffice.org/en/question/143186/how-to-use-user-selected-value-from-combobox1-in-combobox2-select-statement/?answer=143231#post-id-143231.  The second list box is based on a list of values instead of an SQL query.


text:
Q: Messaging systems reliability I understand that every messaging platform (rabbitmq, activemq)  provides some mechanism that guarantees message delivery between the server (rabbitmq) and the consumers, so if a consumer is down, the message will still be in a queue and redelivered. But what happens in case the messaging platform is down and the client (producer of the message) could  not deliver the message to the platform (Rabbitmq)?  In that case, a retry method to redeliver the message is needed, but I'm not sure if I have to implement it myself, or clients libraries have this option , is it declared as a parameter in the connection/channel creation? is it platform specific? Also, protocols like AMQP specifies this?   I heard also from Spring Retry as a option.

A: A spring-retry RetryTemplate can be wired directly into Spring AMQP's RabbitTemplate.
Kafka has retry capability built into the Producer (see the retries property).
For JMS, you can wrap the JmsTemplate into a RetryTemplate.execute() method.
The retry policy, back-off etc is all configurable.


text:
Q: Is there a specific standard error for an individual residual? On page 97 of Introduction to Statistical Learning book, there is a paragraph on studentized residuals within the context of looking for outliers.

But in practice, it can be difficult to decide how large a residual
  needs to be before we consider the point to be an outlier. To address
  this problem, instead of plotting the residuals, we can plot the
  studentized residuals, computed by dividing each residual ei by its estimated standard error.

This gist of this makes sense, I understand that we are looking for residuals that are more than 2-3 deviations away from the mean.
What confused me was use of the word "its"

in each residual ei by its estimated standard error

This implies there is a standard error for each residual ei as opposed to a standard error for all of the residuals as a group. Have I misread or misunderstood this?
When calculating studentized residuals am I dividing each residual by the regression RSE or some other denominator?

A: Yes, at least for linear regression, so I will answer for that case. The model is then
$$
    Y=X\beta+\epsilon
$$
in matrix form, where $Y$ is $n\times 1$, $X$ is $n\times p$, $\beta$ is $p\times 1$ and the error term $\epsilon$ is $n\times 1$. We assume the errors $\epsilon_i$ are iid with variance $\sigma^2$ (and expectation zero).
Then the least squares estimator is $\hat{\beta}=(X^T X)^{-1}X^T Y$ and the predicted values is $\hat{Y}= X\hat{\beta}=X (X^TX)^{-1} X^T Y= H Y$ where $H= X (X^TX)^{-1} X^T$ is the hat matrix. The residual vector $r= Y-\hat{Y}=(I-H)Y$
has expectation zero and variance matrix $\text{Var}(r)= (I-H) \sigma^2 I (I-H)  = \sigma^2 (I-H)$ so the standard error of residual component $i$ is
$$
  \text{se}(r_i) = \sigma \sqrt{1-h_i}
$$
and we can show that $ 0\le h_i \le 1$.  $h_i$ is often seen as a measure of the influence or leverage of observation $i$, so we can see that the most influential observations have residuals with lesser standard error.


text:
Q: Get the absolute path of a file on the class path Setup

*

*Pasted is modified version of an Oracle example

*While the program's running, if you now make a new file or directory directory inside of the path directory, you'll see that the path displayed is incorrect

*For example, when I run it, it shows the absolute path of a newly-created file in the path directory as /home/hoagy/test/new_file, when the actual path to the file is /home/hoagy/test/path/new_file
Question

*

*How do I get the proper absolute path?

Code
package path.question;

import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
import static java.nio.file.LinkOption.*;
import java.nio.file.attribute.*;
import java.io.*;
import java.util.*;

public class WatchDir {

    private final WatchService watcher;
    private final Map<WatchKey,Path> keys;

    @SuppressWarnings("unchecked")
    static <T> WatchEvent<T> cast(WatchEvent<?> event) {
        return (WatchEvent<T>)event;
    }

    private void register(Path dir) throws IOException {
        WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        keys.put(key, dir);
    }

    WatchDir(Path dir) throws IOException {
        this.watcher = FileSystems.getDefault().newWatchService();
        this.keys = new HashMap<WatchKey,Path>();
        register(dir);
    }

    void processEvents() {
        for (;;) {

            WatchKey key;
            try { key = watcher.take(); }
            catch (InterruptedException x) { return; }

            Path dir = keys.get(key);
            if (dir == null) {
                continue;
            }

            for (WatchEvent<?> event: key.pollEvents()) {
                WatchEvent.Kind kind = event.kind();

                if (kind == OVERFLOW) { continue; }

                WatchEvent<Path> ev = cast(event);
                Path name = ev.context();
                Path child = dir.resolve(name);

                System.out.println("Full path: " + name.toAbsolutePath().toString());
            }

            key.reset();
        }
    }

    public static void main(String[] args) throws IOException {
        Path dir = Paths.get("./path");
        new WatchDir(dir).processEvents();
    }
}

A: Replace :
 //prints the "absolute path" of the name of the file
 System.out.println("Full path: " + name.toAbsolutePath().toString());

With
 //prints the "absolute path" of the "child"
 System.out.println("child " + child.toAbsolutePath().toString());


text:
Q: Isset Variable Is Not Being Echoed Onto Page - PHP I have a form that is going to submit a search query with PHP via a MySQL database. The form action attribute is set to another page, namely search.php. I want to store the search term in a variable, $searchQuery, but when I try and echo that variable out in the HTML, it doesn't show any value and I'm not getting any errors?
This is the first time I've built a search form in PHP, but I don't understand why this variable isn't being echoed?
The echo "test string"; line is being outputted as expected.
OUTPUT - search.php page

<?php
if(isset($_POST['search-submit'])) {

    $searchQuery = $_POST['search-submit'];

    if (isset($searchQuery)) {
        echo $searchQuery;
        echo "test string";
    }
}
?>

FORM in the header of every page
<form action="search.php" method="POST">
    Enter Search
    <input type="text" name="search" id="search">
    <button type="submit" name="search-submit" id="search-submit">Search</button>
</form>

A: if you are demanding value from your button it should be
<button type="submit" name="search-submit" value="add value here" id="search-submit">Search</button>

but if you are demanding value from your input text it should be
$_POST['search'] "search" which is your input text name not $_POST['search-submit'] "search-submit"which is your button name


text:
Q: Converting class-based JS useState array to TypeScript Hook problem I've been working with React / TypeScript for a few days and am teaching myself by doing a small project. As part of that I am currently converting some class based code into hooks.
I have the following (JS) class based code that I don't know how to convert to use in a hook with TypeScript:
this.setState({
  data: [
    ...this.state.data,
    {
      chx: chx,
      type: type,
      bin: bin,
      ascii: ascii,
    },
  ],
});

In my hook based equivalent I know that I would use setData(); for a simple state. But, how do I convert the example above? My attempt (below) is clearly wrong, as I'm getting the error: Type '{ chx: unknown; type: string; bin: string; ascii: string; }' is not assignable to type 'never'. But I'm stuck for what I should do next to try and resolve this:
setData([
  ...data,
  {
    chx: chx,
    type: type,
    bin: bin,
    ascii: ascii,
  }
])

Update
I got this working by changing my useState declaration from:
const [ data, setData ] = useState([]);

to
const [ data, setData ] = useState<any>([]); //{type: read/write/notify/error, bin: 8 int binary, ascii: ASCII Value}

However, I realise this just defeats the object of using TypeScript. So, my next move based on @tomleb3 answer was to create an interface for data like so:
const [ data, setData ] = useState<DataType>([]); //{type: read/write/notify/error, bin: 8 int binary, ascii: ASCII Value}

  interface DataType{
    chx: any,
    bin: string,
    type: string,
    ascii: string
  }

but this gives an error:

Argument of type 'never[]' is not assignable to parameter of type
'DataType | (() => DataType)'.   Type 'never[]' is not assignable to
type '() => DataType'.
Type 'never[]' provides no match for the signature '(): DataType'.

I don't know how to progress from here as removing the [] useState declaration then pushes the error down to wherever I use a setData() call with the following error:

Argument of type 'any[]' is not assignable to parameter of type
'SetStateAction<DataType | undefined>'.   Type 'any[]' is not
assignable to type '(prevState: DataType | undefined) => DataType |
undefined'.

A: The error you are receiving is a Typescript error, not a React error.
Your code is perfectly fine, but when working with Typescript we need to type our states just as well as everything else.
Which can look like this for example:
interface State {
   key1: string,
   key2: number,
   key3: boolean,
}

function myComponent() {
   const [state, setState] = useState<State>({
      key1: 'test',
      key2: 42,
      key3: false,
   })
}

This allows Typescript to know the structure of your state and thus enabling it to apply the relevant type guards and restrictions.


text:
Q: Connect another jabber to Gmail chat I have a jabber account except Gmail. Is there any way to connect it to Gmail chat?

A: No, you'll need a Jabber client like Psi

A: Sure, Jabber is federated, like email.  You should just be able to add any @gmail.com users to your roster (buddy list) and talk with them -- the Jabber provider used doesn't matter, unless they're really backwards and don't have federation set up.


text:
Q: Cannot instantiate class: com.sun.enterprise.naming.SerialInitContextFactory I have created a simple Enterprise Application in Netbeans, which works as expected inside Netbeans.  The Enterprise Application Client contains the following code:
package clienttest2;

import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import test.TestEJBRemote;

/**
 *
 * @author
 */
public class Main {
private TestEJBRemote testejb;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws NamingException {
        Properties props = new Properties();
        props = new Properties();
        props.setProperty("java.naming.factory.initial",
            "com.sun.enterprise.naming.SerialInitContextFactory");
        props.setProperty("java.naming.factory.url.pkgs",
            "com.sun.enterprise.naming");
        props.setProperty("java.naming.factory.state",
            "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
        props.setProperty("org.omg.CORBA.ORBInitialHost", "computer");
        props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
        InitialContext ctx = new InitialContext(props);
        TestEJBRemote t = (TestEJBRemote) ctx.lookup("java:global/EJBTest/EJBTest-ejb/TestEJB");
        System.out.println(t.getName("Ian"));

        //Context ctx = null;
        //ctx=new InitialContext();
        //TestEJBRemote t = (TestEJBRemote) ctx.lookup("java:global/EJBTest/EJBTest-ejb/TestEJB");
        //System.out.println(t.getName("Ian"));
    }

}

I have tried the following:
java -jar ClientTest.jar

The error I get is: Cannot instantiate class: com.sun.enterprise.naming.SerialInitContextFactory
I have a few questions:
I have  JRE 1.8 installed on my PC.  Does this mean that I can run all types of Java apps i.e. Java EE and Java SE?

A: Simply speaking: your code contains quite a list of class names that will all be loaded using reflection. Surprise: all of them need to be in your classpath.
Most likely, your Netbeans project setup lists all the required JARs (probably as they belong to the set of JARs coming with your Java installation).
But when you call java on the command line, you more or less start with a classpath that only contains the "core" java JARs.
In other words: you have to identify those JARs that contain the classes your code lists; and then you have to provide them within your "class path setup" when invoking java on the command line.

A: Maybe a duplicate How to setup JNDI for Glassfish 3.1.2 for a stand-alone client?
We can suppose that Glassfish and NetBean share some libs for Java EE.
Anyway you can use http://jarscan.com to scan your netbean directory to find the jar that contains the class you need. And add it to you java command line.


text:
Q: How to link external libraries in Android I'm pretty new to Android (to be precise 1 day), so please bear with the explanation,:)
The requirement is to port the existing code (C & C++) which is working on iOS to Android.
Almost everything went well, except 'libxml2'. The code is dependent on this. And as one of the suggestions got from this very forum, I got the source code of 'libxml2 and compiled it for Android. But when trying to create a Shared library of it, its not able to resolve the external dependencies. Its throwing an error "undefined reference to 'ucnv_close', 'ucnv_open',...", for almost every function dependent on "ucnv_*".
I think "ucnv_*" comes as "icu4c" external library. I tried to compile this too, but in vain. This is throwing errors "'dynamic_cast' not permitted with -fno-rtti" and "cannot use typeid with -fno-rtti". I'm totally clue less here (don't exactly know on enabling / disabling the flag "-fno-rtti" and also its significance), and also don't prefer to hack around a well written code.
So, can anyone please explain on how to link (shared & static) / integrate the external libraries specially "libxml2" (also "icu4c" if required) with C/C++ code,.??? (I saw explanations on *.jar, but couldn't get how it'll fit here)
Any information to resolve / understand the problem I'm facing will be really helpful,..!!!
Thanks for reading,..


text:
Q: Error "uninitialized constant Rails::Engine (NameError)" I am trying to join a Rails project. This project uses rails 2.3.8 and Ruby 1.8.7 so I am using RVM. I am also using gem v1.3.7
When I fire up the server, everything is ok. But then, when I try to access it through my browser, it crashes and I get the following trace:
/Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:440:in `load_missing_constant': uninitialized constant Rails::Engine (NameError)
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:80:in `const_missing'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/devise_invitable-0.3.6/lib/devise_invitable/rails.rb:2
        from /Users/ca/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
        from /Users/ca/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:156:in `require'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:521:in `new_constants_in'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:156:in `require'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/devise_invitable-0.3.6/lib/devise_invitable.rb:16
        from /Users/ca/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
        from /Users/ca/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:156:in `require'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:521:in `new_constants_in'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:156:in `require'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.3.8/lib/rails/gem_dependency.rb:215:in `load'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.3.8/lib/initializer.rb:307:in `load_gems'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.3.8/lib/initializer.rb:307:in `each'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.3.8/lib/initializer.rb:307:in `load_gems'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.3.8/lib/initializer.rb:169:in `process'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.3.8/lib/initializer.rb:113:in `send'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.3.8/lib/initializer.rb:113:in `run'
        from /Users/ca/Documents/Project/Sources/Project-test/config/environment.rb:9
        from /Users/ca/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
        from /Users/ca/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:156:in `require'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:521:in `new_constants_in'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:156:in `require'
        from /Users/ca/.rvm/gems/ruby-1.8.7-p334/gems/rails-2.3.8/lib/commands/server.rb:84
        from /Users/ca/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
        from /Users/ca/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
        from ./script/server:3

Here are my installed gems:
actionmailer (2.3.8)
actionpack (2.3.8)
activemodel (3.0.5)
activerecord (2.3.8)
activeresource (2.3.8)
activesupport (3.0.5, 2.3.8)
addressable (2.2.4)
arel (2.0.9)
aws (2.4.4)
aws-s3 (0.6.2)
bcrypt-ruby (2.1.4)
builder (3.0.0, 2.1.2)
client_side_validations (2.9.9)
crack (0.1.8)
daemons (1.1.0)
dalli (1.0.2)
delayed_job (2.0.3)
devise (1.1.7)
devise_invitable (0.3.6)
faraday (0.5.7, 0.4.6)
fb_graph (1.5.3)
googlecharts (1.6.1)
http_connection (1.4.0)
httparty (0.7.4)
i18n (0.5.0)
json (1.5.1, 1.4.3)
mime-types (1.16)
multi_json (0.0.5)
multipart-post (1.1.0)
net-ldap (0.1.1)
nokogiri (1.4.4)
oa-basic (0.1.5)
oa-core (0.1.5)
oa-enterprise (0.1.5)
oa-oauth (0.1.5)
oa-openid (0.1.5)
oauth (0.4.4)
oauth2 (0.1.1, 0.0.13)
omniauth (0.1.5)
paperclip (2.3.8)
pyu-ruby-sasl (0.0.3.2)
rack (1.1.1)
rack-openid (1.1.2)
rails (2.3.8)
rake (0.8.7)
RedCloth (4.2.7)
rest-client (1.6.1)
ruby-openid (2.1.8)
ruby-openid-apps-discovery (1.2.0)
rubygems-update (1.3.7)
rubyntlm (0.1.1)
tzinfo (0.3.24)
uuidtools (2.1.2)
validates_timeliness (2.3.0)
validation_reflection (0.3.7)
validation_reflection-active_model (0.3.1)
warden (1.0.3)
will_paginate (2.3.15)
xml-simple (1.0.14)

Where does the problem come from?
Thank you very much for your help!

A: Your version of the DeviseInvitable is too new for Rails 2.3.

DeviseInvitable currently only support Rails 3, if you want to use it with Rails 2.3 you must install version 0.2.3

As is Devise 1.1

Support for Rails 2.3.x can be found by installing Devise 1.0.x from the v1.0 branch.

Run
gem uninstall devise devise_invitable
gem install devise --version 1.0.10
gem install devise_invitable --version 0.2.3


text:
Q: How to configure Spring to take a data from socket bytestream? I'm trying to configure Spring on the server side to open a socket, listen for connections and take the incoming stream (converting to String).
But I cannot find any working examples on how to just create such an incoming tcp connection. This is what I have (taken from an incomplete example):
<int-ip:tcp-connection-factory id="cfServer"
    type="server"
    port="8080"
    using-nio="true"
    single-use="true" />

<int-ip:tcp-inbound-channel-adapter id="inboundServer"
    channel="loop"
    connection-factory="server"/>

<int:channel id="loop"/>

Well, but how do I continue? How can I acutally bind these adapters to a backing class? And what do these classes have to look like?

A: Subscribe something to the loop channel, e.g. a <service-activator/>.
See the tcp-client-server sample


text:
Q: How to publish to artifactory multimodule proj using gradle and spring-boot I am using gradle 2.7
I am trying to publish one of my sub-modules into artifactory:
part of my sub modules being upload to snapshort and part of them into release.
   apply plugin: 'java'
    apply plugin: 'idea'
    apply plugin: 'maven'
    apply plugin: 'maven-publish'

// Since spring-boot does not allow us to configure fat jar name...
task buildForCloud(type: Copy, dependsOn: [clean, build]) {
    from jar.archivePath
    into jar.destinationDir
    rename {
        'com.company.myapp-all.jar'
    }
}

//this module being uploaded into release and as soon as I added this //part I am getting errors
publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java
            artifact sourceJar {
                classifier "sources"
            }
        }
    }
}

buildForCloud.mustRunAfter(clean)

running this way:
./gradlew clean buildForCloud publishMavenJavaPublicationToMaven2Repository

the error:
* What went wrong:
Execution failed for task ':server:publishMavenJavaPublicationToMaven2Repository'.
> Failed to publish publication 'mavenJava' to repository 'maven2'
   > Unable to initialize POM pom-default.xml: Failed to validate POM for project com.mycompany.app:server at /Users/mycomp/IdeaProjects/user-service/server/build/publications/mavenJava/pom-default.xml

Any idea?
Added the gradle log request:
Executing task ':server:sourceJar' (up-to-date check took 0.005 secs) due to:
  Output file /Users/comp/IdeaProjects/user-service/server/build/libs/server-1.1-SNAPSHOT-sources.jar has changed.
  Output file /Users/comp/IdeaProjects/user-service/server/build/libs/server-1.1-SNAPSHOT-sources.jar has been removed.
:server:sourceJar (Thread[main,5,main]) completed. Took 0.025 secs.
:server:publishMavenJavaPublicationToMaven2Repository (Thread[main,5,main]) started.
:server:publishMavenJavaPublicationToMaven2Repository
Executing task ':server:publishMavenJavaPublicationToMaven2Repository' (up-to-date check took 0.0 secs) due to:
  Task has not declared any outputs.
Publishing to repository org.gradle.api.internal.artifacts.repositories.DefaultMavenArtifactRepository_Decorated@3c888166
[ant:null] An error has occurred while processing the Maven artifact tasks.
 Diagnosis:

Unable to initialize POM pom-default.xml: Failed to validate POM for project com.mycompany.userservice:server at /Users/comp/IdeaProjects/user-service/server/build/publications/mavenJava/pom-default.xml

:server:publishMavenJavaPublicationToMaven2Repository FAILED
:server:publishMavenJavaPublicationToMaven2Repository (Thread[main,5,main]) completed. Took 0.029 secs.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':server:publishMavenJavaPublicationToMaven2Repository'.
> Failed to publish publication 'mavenJava' to repository 'maven2'
   > Unable to initialize POM pom-default.xml: Failed to validate POM for project com.mycompany.userservice:server at /Users/comp/IdeaProjects/user-service/server/build/publications/mavenJava/pom-default.xml

* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output.

BUILD FAILED

Total time: 52.274 secs
Stopped 0 compiler daemon(s).
comps-MacBook-Pro-2:user-service comp$ ./gradlew clean buildForCloud -x test publishMavenJavaPublicationToMaven2Repository -i -


text:
Q: JVM process resident set size "equals" max heap size, not current heap size After a few reading about jvm memory (here, here, here, others I forgot...), I am expecting the resident set size of my java process to be roughly equal to the current heap space capacity. That's not what the numbers are saying, it seems to be roughly equal to the max heap space capacity:
Resident set size:
# echo 0 $(cat /proc/1/smaps  | grep Rss | awk '{print $2}' | sed 's#^#+#') | bc
11507912

# ps -C java -O rss | gawk '{ count ++; sum += $2 }; END {count --; print "Number of processes =",count; print "Memory usage per process =",sum/1024/count, "MB"; print "Total memory usage =", sum/1024, "MB" ;};'
Number of processes = 1
Memory usage per process = 11237.8 MB
Total memory usage = 11237.8 MB

Java heap
# jmap -heap 1
Attaching to process ID 1, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 24.55-b03

using thread-local object allocation.
Garbage-First (G1) GC with 18 thread(s)

Heap Configuration:
MinHeapFreeRatio = 10
MaxHeapFreeRatio = 20
MaxHeapSize      = 10737418240 (10240.0MB)
NewSize          = 1363144 (1.2999954223632812MB)
MaxNewSize       = 17592186044415 MB
OldSize          = 5452592 (5.1999969482421875MB)
NewRatio         = 2
SurvivorRatio    = 8
PermSize         = 20971520 (20.0MB)
MaxPermSize      = 85983232 (82.0MB)
G1HeapRegionSize = 2097152 (2.0MB)

Heap Usage:
G1 Heap:
regions  = 2560
capacity = 5368709120 (5120.0MB)
used     = 1672045416 (1594.586769104004MB)
free     = 3696663704 (3525.413230895996MB)
31.144272834062576% used
G1 Young Generation:
Eden Space:
regions  = 627
capacity = 3279945728 (3128.0MB)
used     = 1314914304 (1254.0MB)
free     = 1965031424 (1874.0MB)
40.089514066496164% used
Survivor Space:
regions  = 49
capacity = 102760448 (98.0MB)
used     = 102760448 (98.0MB)
free     = 0 (0.0MB)
100.0% used
G1 Old Generation:
regions  = 147
capacity = 1986002944 (1894.0MB)
used     = 252273512 (240.5867691040039MB)
free     = 1733729432 (1653.413230895996MB)
12.702574926293766% used
Perm Generation:
capacity = 39845888 (38.0MB)
used     = 38884120 (37.082786560058594MB)
free     = 961768 (0.9172134399414062MB)
97.58628042120682% used

14654 interned Strings occupying 2188928 bytes.

*

*Are my expectations wrong? What should I expect?

*I need the heap space to be able to grow during spikes (to avoid very slow Full GC), but I would like to have the resident set size as low as possible the rest of the time, to benefit the other processes running on the server. Is there a better way to achieve that?

Linux 3.13.0-32-generic x86_64
java version "1.7.0_55"
Running in Docker version 1.1.2

Java is running elasticsearch 1.2.0:
/usr/bin/java -Xms5g -Xmx10g -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=20 -Xss256k -Djava.awt.headless=true -XX:+UseG1GC -XX:MaxGCPauseMillis=350 -XX:InitiatingHeapOccupancyPercent=45 -XX:+AggressiveOpts -XX:+UseCompressedOops -XX:-OmitStackTraceInFastThrow -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintClassHistogram -XX:+PrintTenuringDistribution -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCApplicationConcurrentTime -Xloggc:/opt/elasticsearch/logs/gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/opt elasticsearch/logs/heapdump.hprof -XX:ErrorFile=/opt/elasticsearch/logs/hs_err.log -Des.logger.port=99999 -Des.logger.host=999.999.999.999 -Delasticsearch -Des.foreground=yes -Des.path.home=/opt/elasticsearch -cp :/opt/elasticsearch/lib/elasticsearch-1.2.0.jar:/opt/elasticsearch/lib/*:/opt/elasticsearch/lib/sigar/* org.elasticsearch.bootstrap.Elasticsearch

There actually are 5 elasticsearch nodes, each in a different docker container. All have about the same memory usage.
Some stats about the index:
size: 9.71Gi (19.4Gi)
docs: 3,925,398 (4,052,694)


text:
Q: How can I make sure that only one of two fields is filled out (ListItem)? I have custom SharePoint list with several fields. Two of the fields are TargetPage and ExternalURL. At the moment the user is allowed to fill out both of them if he want to, and I want to deny that. How can I "validate" the form before it's submitted so that the user is only allowed to fill out one field at a time?

A: A simple solution is to just validate the fields on submit by adding a validation rule in the list settings.

*

*Go to List Settings

*Open Validation settings under the General Settings area

In the formula add your formula, I think it will be like this in your scenario:

=OR(IF(ISBLANK(TargetPage),NOT(ISBLANK(ExternalURL))),IF(ISBLANK(ExternalURL),NOT(ISBLANK(TargetPage))))

And add a user message in the list input field.
Or you could do this easy with InfoPath form, or some javascript to hide fields if there is text in one of them. I'm sure there is lots of approaches. But the solution i posted is an out of the box solution if that's a criteria for you.


text:
Q: Changing the name of the terms in ggally::ggcoef Given the following example
iris_fat <- iris %>% mutate(is_fat = factor(ifelse(Sepal.Width * Petal.Width > 6 ,"fat", "not_fat")))
reg <- lm(Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + is_fat, data = iris_fat)
  GGally::ggcoef(reg)

How can I change the name of the term is_fatnot_fat to something else.

A: My bad on the earlier comment, didn't read it carefully.
ggcoef creates a list, just like the other ggplot functions.  The first element, data, is a dataframe in which term maps to the y-axis.  If you're curious, try str(test_plot$data) or examine it in RStudio
test_plot <- ggcoef(reg)
test_plot$data$term <- c("(Intercept)", "is_fat", "Petal.Length", "Petal.Width", "Sepal.Width")


text:
Q: Como selecionar um blob do banco de dados e transformar em bitmap? Estou com o seguinte erro no meu projeto, eu seleciono uma imagem da galeria transformo ela em byte cadastro no banco, porem no momento de carregar ela pra imageView ela não aparece e não da erro na aplicação, eu não estou mexendo na parte do código de tirar foto mas se alguém tiver algum código melhor pois esse a imagem perde a qualidade, agradeço a ajuda.
public class Main extends AppCompatActivity {

    private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
    private Button btnSelect;
    private Button btnCamera;
    private Button btnSave;
    private ImageView ivImage;
    private String Chave;
    banco db = new banco(this);
    SQLiteDatabase banco;
    String local;
    byte[] imagem;

    Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ivImage = (ImageView) findViewById(R.id.ivImage);
        btnSelect = (Button) findViewById(R.id.btnSelect);
        btnCamera = (Button) findViewById(R.id.btnCamera);
        btnSave = (Button) findViewById(R.id.btnSalvar);

        btnSelect.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Chave = "Selecionar";
                galleryIntent();

            }
        });

        btnCamera.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Chave = "Camera";
                cameraIntent();

            }
        });

        btnSave.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                banco = db.getReadableDatabase();
                banco.execSQL("insert into tabela (imagem) values('"+imagem+"')");
                Toast.makeText(Main.this, imagem+" Imagem salva!", Toast.LENGTH_SHORT).show();
                banco.close();

            }
        });

        carregar();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if(Chave.equals("Camera"))
                        cameraIntent();
                    else if(Chave.equals("Selecionar"))
                        galleryIntent();
                }
                break;
        }
    }

    private void galleryIntent()
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
    }

    private void cameraIntent()
    {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_FILE)
                onSelectFromGalleryResult(data);
            else if (requestCode == REQUEST_CAMERA)
                onCaptureImageResult(data);
        }

    }

    private void onCaptureImageResult(Intent data) {
        bitmap = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

        File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");

        local = destination.getName();

        FileOutputStream fo;
        try {
            destination.createNewFile();
            fo = new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        ivImage.setImageBitmap(bitmap);

    }

    @SuppressWarnings("deprecation")
    private void onSelectFromGalleryResult(Intent data) {

        bitmap = null;
        if (data != null) {
            try {

                bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        ivImage.setImageBitmap(bitmap);

        Bitmap bitmap2 = ((BitmapDrawable)ivImage.getDrawable()).getBitmap();
        ByteArrayOutputStream saida = new ByteArrayOutputStream();
        bitmap2.compress(Bitmap.CompressFormat.PNG,100,saida);
        imagem = saida.toByteArray();

        Toast.makeText(Main.this, imagem.toString(), Toast.LENGTH_SHORT).show();
    }

    public void carregar() {

        banco = db.getReadableDatabase();

        Cursor cur = banco.rawQuery("select * from tabela", null);

        cur.moveToFirst();

        if(cur.isAfterLast()== false) {

            cur.moveToLast();

            byte[] image = cur.getBlob(cur.getColumnIndex("imagem"));

            if (image != null) {
                Bitmap bmp = BitmapFactory.decodeByteArray(image, 0, image.length);
                ivImage.setImageBitmap(bmp);
            }
        }

    }

}

A: Sua imagem certamente é muito grande para ser desenha na surface de um bitmap, pois estoura o tamanho máximo permitido para a memória de textura do Android. Se você usar o Android Monitor dentro do Android Studio verá um monte de aviso do tipo "Bitmap too large to be uploaded into a texture". Você precisa fazer downsampling da mesma. Evite manipular bitmaps diretamente, use uma biblioteca para isso. É muito mais complicado lidar com bitmaps no android do que se imagina. Muito mesmo!
Nota: Em casos de pouca memória de sistema restante, as operações leitura do arquivo para um array de bytes em memória pode falhar. Em situações extremas de pouca memória, nem mesmo usar uma biblioteca com o Glide pode evitar que esses erros ocorram, mas o Glide lida graciosamente com os mesmos, mais uma vantagem de usar uma biblioteca como essa.
Por isso estude a biblioteca Glide do Google, que faz todo o trabalho para você de ler a imagem em uma thread em background (evitando travar a interface do usuário) e ainda considera rotações de orientação da tela (que lhe dariam uma exceção de NullReferenceException), e ainda implementa um cache de imagens para melhorar a performance da aplicação.
Instale o Glide adicionando a seguinte linha no seu Gradle:
dependencies {
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.android.support:support-v4:19.1.0'
}

Uma vez instalado o glide modifique sua rotina de exibição para:
public void carregar() {

    banco = db.getReadableDatabase();

    Cursor cur = banco.rawQuery("select * from tabela", null);

    cur.moveToFirst();

    if(cur.isAfterLast()== false) {

        cur.moveToLast();

        byte[] image = cur.getBlob(cur.getColumnIndex("imagem"));

        if (image != null) {

            Glide.with(this)
                .load(image)
                .asBitmap()
                .into(ivImage);

        }
    }

Nota: Percebi um erro na sua implementação da captura da imagem pela câmera. Você está pegando apenas a miniatura da imagem capturada. Esse é um erro/pegadinha comum de quem começa a trabalhar com a câmera no Android. Tenho uma resposta exatamente sobre isso que você pode ver aqui: Trabalhando com a câmera ou galeria

A: Segue um exemplo básico de como manipular as imagens no Sqlite:
ADICIONAR IMAGEM:
public void add( byte[] image) throws SQLiteException{
    ContentValues cv = new  ContentValues();
    cv.put(KEY_IMAGE,   image);
    database.insert( DB_TABLE, null, cv );
}

Para carregar a imagem use o método getBlob :
byte[] image = cursor.getBlob(1);


text:
Q: Awake from sleep event on the iPhone? Is there any way to detect if the iPhone wakes up from sleep while you're app is running? Eg: your app is running, the user locks the screen (or the screen auto locks) and some time later the user unlocks the screen and up pops your app. Is there some way to get an event at that point or detect it somehow?
I've tried searching the Google and this forum, but I can't seem to find anything about it.

A: Stick these in you AppDelegate.m file:
-(void) applicationWillResignActive:(UIApplication *)application {

     NSLog(@"Asleep");
}

-(void) applicationDidBecomeActive:(UIApplication *)application {

     NSLog(@"Awake");
}

@Kevin - Nothing wrong with your answer - thanks by the way. Just thought I'd save the next person a Google search.

A: See applicationDidBecomeActive: on UIApplicationDelegate.


text:
Q: Why do I get in_use_customer_managed_encryption_keys quota exceeds quota limits creating Vertex AI endpoint with CMEK? When attempting to create a Vertex AI endpoint with CMEK, I get:

Failed to create endpoint...The following quota metrics exceed quota limits: aiplatform.googleapis.com/in_use_customer_managed_encryption_keys'
Status: 429 Error code: 429

On the Console, under "IAM and admin", "Quotas", the limit for quota "In use customer managed encryption keys per region" for the region corresponding to my endpoint, is listed as 1 and current usage as 0. Perhaps the current usage must be less than the limit?
I requested a raise in that quota limit and in the description asked whether a limit >1 was required to create a single CMEK endpoint, however the response did not address this question but rather just asked for payment to increase the quota.

A: Yes, it appears that the current usage must be less than the limit i.e. a limit of 1 does not allow any usage.
I successfully applied for a quota increase to raise the limit to 2 and was subsequently able to create the endpoint with the CMEK key.


text:
Q: Inserting cipher text into mysql using python So i have a program which will encrypt a string using AES and generate cipher which in bytes[].
I wish to store this cipher as it is in mysql database.
I found we could use VARBINARY data type in mysql to do so.
In what ways we could achieve so.
Here is my try to do so :
import ast
import mysql.connector
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

def encrypt(key, msg):
    iv = get_random_bytes(16)
    cipher = AES.new(key, AES.MODE_CFB, iv)
    ciphertext = cipher.encrypt(msg)    # Use the right method here
    db = iv + ciphertext
    print(db)
    cursor.executemany(sql_para_query,db)
    print(cursor.fetchone())
    connection.commit()
    return iv + ciphertext

def decrypt(key, ciphertext):
    iv = ciphertext[:16]
    ciphertext = ciphertext[16:]
    cipher = AES.new(key, AES.MODE_CFB, iv)
    msg = cipher.decrypt(ciphertext)
    return msg.decode("utf-8")

if __name__ == "__main__":
    connection = mysql.connector.connect(host = "localhost", database = "test_db", user = "sann", password = "userpass",use_pure=True)
    cursor = connection.cursor(prepared = True)
    sql_para_query = """insert into test1 values(UNHEX(%s)) """
    ed = input("(e)ncrypt or (d)ecrypt: ")
    key = str(1234567899876543)
    if ed == "e":
        msg = input("message: ")
        s= encrypt(key, msg)
        print("Encrypted message: ", s)
        file = open("e_tmp","wb+")
        file.write(s)
        print(type(s))

    elif ed == "d":
        #smsg = input("encrypted message: ")
        #file = open("e_tmp","rb")
        #smsg = file.read()
        #print(type(smsg))
        sql_para_query = """select * from test1"""
        cursor.execute(sql_para_query)
        row = cursor.fetchone()
        print(row)
        #smsg = str(smsg)
        #msg = ast.literal_eval(smsg)
        #print(msg)
        #print(type(msg))
        #s=decrypt(key, msg)
        #print("Decrypted message: ", s)
        #print(type(s))

Error I'm getting :

Traceback (most recent call last):   File
  "/home/mr_pool/.local/lib/python3.6/site-packages/mysql/connector/cursor.py",
  line 1233, in executemany
      self.execute(operation, params)   File "/home/mr_pool/.local/lib/python3.6/site-packages/mysql/connector/cursor.py",
  line 1207, in execute
      elif len(self._prepared['parameters']) != len(params): TypeError: object of type 'int' has no len()
During handling of the above exception, another exception occurred:
Traceback (most recent call last):   File "tmp1.py", line 36, in

      s= encrypt(key, msg)   File "tmp1.py", line 14, in encrypt
      cursor.executemany(sql_para_query,db)   File "/home/mr_pool/.local/lib/python3.6/site-packages/mysql/connector/cursor.py",
  line 1239, in executemany
      "Failed executing the operation; {error}".format(error=err)) mysql.connector.errors.InterfaceError: Failed executing the operation;
  object of type 'int' has no len()

Any other alternatives are also welcome.
My ultimate goal is to store the encrypted text in database.

A: I reproduced your error, but it seems there are more errors in your code.
The key as well as the message are strings, therefore I got this error:
TypeError: Object type <class 'str'> cannot be passed to C code

Which I fixed by encoding them in utf-8:
# line 38:
key = str(1234567899876543).encode("utf8")
# .... line 41:
s= encrypt(key, msg.encode("utf8"))

The UNHEX function in your SQL Query is not needed because we are entering the data as VARBINARY. You can change your statement to:
"""insert into test1 values(%s) """

The function executemany() can be replaced by execute() because you are only entering one statement. However I will write the solution for using both, execute or executemany.
insert with execute():
From the documentation:

cursor.execute(operation, params=None, multi=False)
iterator = cursor.execute(operation, params=None, multi=True)
This method executes the given database operation (query or command). The parameters found in the tuple or dictionary params are bound to the variables in the operation. Specify variables using %s or %(name)s parameter style (that is, using format or pyformat style). execute() returns an iterator if multi is True.
  https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

So we need just to build a tuple with your parameters by changing the cursor.execute line to:
cursor.execute(sql_para_query, (db, ))

insert with executemany():
From the documentation:

cursor.executemany(operation, seq_of_params)
  This method prepares a database operation (query or command) and executes it against all parameter sequences or mappings found in the sequence seq_of_params.
  https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html

Therefore we need to build a sequence with values you'd like to insert. In your case just one value:
 cursor.executemany(sql_para_query, [(db, )])

To insert multiple values, you can add as many tuples into your sequence as you want.
full code:
import ast
import mysql.connector
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

def encrypt(key, msg):
    iv = get_random_bytes(16)
    cipher = AES.new(key, AES.MODE_CFB, iv)
    ciphertext = cipher.encrypt(msg)    # Use the right method here
    db = iv + ciphertext
    cursor.execute(sql_para_query, (db, ))
    connection.commit()
    return iv + ciphertext

def decrypt(key, ciphertext):
    iv = ciphertext[:16]
    ciphertext = ciphertext[16:]
    cipher = AES.new(key, AES.MODE_CFB, iv)
    msg = cipher.decrypt(ciphertext)
    return msg.decode("utf-8")

if __name__ == "__main__":
    connection = mysql.connector.connect(host = "localhost", database = "test_db", user = "sann", password = "userpass",use_pure=True)
    cursor = connection.cursor(prepared = True)
    sql_para_query = """insert into test1 values(%s) """
    ed = input("(e)ncrypt or (d)ecrypt: ")
    key = str(1234567899876543).encode("utf8")
    if ed == "e":
        msg = input("message: ")
        s= encrypt(key, msg.encode("utf8"))
        print("Encrypted message: ", s)
        file = open("e_tmp","wb+")
        file.write(s)
        print(type(s))

    elif ed == "d":
        sql_para_query = """select * from test1"""
        cursor.execute(sql_para_query)
        row = cursor.fetchone()
        msg = row[0] # row is a tuple, therefore get first element of it
        print("Unencrypted message: ", msg)
        s=decrypt(key, msg)
        print("Decrypted message: ", s)

output:
#encrypt:
(e)ncrypt or (d)ecrypt: e
message: this is my test message !!
Encrypted message:  b"\x8f\xdd\xe6f\xb1\x8e\xb51\xc1'\x9d\xbf\xb5\xe1\xc7\x87\x99\x0e\xd4\xb2\x06;g\x85\xc4\xc1\xd2\x07\xb5\xc53x\xb9\xbc\x03+\xa2\x95\r4\xd1*"
<class 'bytes'>
#decrypt:
(e)ncrypt or (d)ecrypt: d
Unencrypted message:  bytearray(b"\x8f\xdd\xe6f\xb1\x8e\xb51\xc1\'\x9d\xbf\xb5\xe1\xc7\x87\x99\x0e\xd4\xb2\x06;g\x85\xc4\xc1\xd2\x07\xb5\xc53x\xb9\xbc\x03+\xa2\x95\r4\xd1*")
Decrypted message:  this is my test message !!


text:
Q: nginx: Why is previous stable version showing after installing from sources? I'm working to install nginx version 1.17.7 from sources. I am using a vanilla instance running Ubuntu 18.04 that does not have nginx installed. Why do I see version 1.14.0 installed? I would expect to see version 1.17.7.
nginx -V;
nginx version: nginx/1.14.0 (Ubuntu)
built with OpenSSL 1.1.1  11 Sep 2018
TLS SNI support enabled
configure arguments: --with-cc-opt='-g -O2 -fdebug-prefix-map=/build/nginx-DUghaW/nginx-1.14.0=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Wdate-time -D_FORTIFY_SOURCE=2' --with-ld-opt='-Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -fPIC' --prefix=/usr/share/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/run/nginx.pid --modules-path=/usr/lib/nginx/modules --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-debug --with-pcre-jit --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_v2_module --with-http_dav_module --with-http_slice_module --with-threads --with-http_addition_module --with-http_geoip_module=dynamic --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module=dynamic --with-http_sub_module --with-http_xslt_module=dynamic --with-stream=dynamic --with-stream_ssl_module --with-mail=dynamic --with-mail_ssl_module

The commands I run are:
# Get the latest version of nginx.
$ wget https://nginx.org/download/nginx-1.17.7.tar.gz

# Extract
$ tar -zxvf nginx-1.17.7.tar.gz;

# Configure
$ cd nginx-1.17.7;
$ ./configure --prefix=/etc/nginx --sbin-path=/usr/bin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --with-pcre --pid-path=/var/run/nginx.pid --with-http_ssl_module --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --with-http_v2_module --user=www --group=www

# Make and install
$ make;
$ sudo make install;

# Verify the install worked.
$ ls -l /etc/nginx;
$ nginx -V;


text:
Q: Problems compiling in clojure with Counterclockwise Hi am totally new to clojure, and have just installed clojure and CounterClockwise.
 I have created a new clojure project named "myproject". Entering (foo "test") gives : "test Hello, World!" just as expected. When I select the "myproject" in the navigator, and run as Java compilation -> Compile clojure.lang, I get following error:

ERROR: Must set system property clojure.compile.path to the location
  for compiled .class files. This directory must also be on your
  CLASSPATH.

What does this mean? How do I fix this?

A: It's generally recommended that you create your projects with the Clojure build tool leiningen (aka "lein"), and use that to create the projects and manage the dependencies etc. counterclockwise detects lein projects automatically. Lein will create a file called project.clj that defines things like compile and source paths as well as the the main class.

A: It seems like the eclipse builtin jar creation tool has some problems.
CCW recommends to install a plugin for eclipse to create a fat jar: http://fjep.sourceforge.net/
CCW documentation: http://doc.ccw-ide.org/documentation.html#_create_a_fat_executable_jar_with_all_dependencies_packaged_into
I still want to emphasize on using leiningen. Whatever you will do later, it is easy to integrate leiningen into your build process, it is independent of the IDE you use and also OS independent.
There are a lot more advantages you get with leiningen (existing plugins, templates, community support, ...).


text:
Q: What does it mean Read IOMeter Bootup? I am hoping I have posted a question to a right area in stack exchange.
Anyways, I am buying a SSD and I came across in benchmark results, some labels that read:
"Read IOMeter Bootup" and "Read IOMeter IOMix"
I am wondering what does it mean? And how much does that influence in reading small size files, as this is mostly the area I am going to be using my SSD?
For example on pages:
http://www.ssdreview.com/review/compare/samsung-serie-840-evo-250gb-25-inch-ext0ab0q/
http://www.ssdreview.com/review/compare/kingston-hyperx-3k-240gb-25-inch-503abbf0/

A: IOMeter is a benchmarking program. Try taking a look at their user manual as they can probably describe their features of Bootup and IOMix better than I can.
http://www.iometer.org/doc/documents.html


text:
Q: How to get following output in SQL Server 2008? SELECT A.Name AS ArlnName
    ,RD.RD_Slab
    ,IsNull(RD.RD_Publ_Rate, 0) AS RD_Publ_Rate
FROM RateHead RH
LEFT OUTER JOIN RateDetl RD ON RH.RH_LocCode = RD.RD_LocCode
    AND RH.RH_DocNo = RD.RD_DocNo
INNER JOIN AirlineMast A ON RH.RH_Airline = A.Code
INNER JOIN AirlineLocation AL ON RH.RH_LocCode = AL.LocCode
    AND RH.RH_Airline = AL.Code
    AND IsNull(AL.RatesAvailable, '') = 'Y'
LEFT OUTER JOIN CommodityMast CM ON CM.Code = RH.RH_SubCommodity
WHERE 1 = 1
    AND RH.RH_LocCode = 'BOM'
    AND IsNull(AL.RatesAvailable, '') = 'Y'
    AND RH.RH_DocNo IN (
        21038
        ,20708
        ,19886
        ,7876
        ,21146
        ,21009
        ,21121
        ,20921
        ,21195
        ,21210
        ,20925
        ,21182
        ,21143
        ,21191
        ,20857
        ,21082
        ,20481
        ,20533
        ,20314
        ,20387
        ,21173
        ,21198
        ,20635
        ,20657
        ,20099
        ,21192
        ,20928
        ,20590
        ,21066
        ,20862
        ,20985
        ,21128
        ,20897
        ,21211
        )
    AND RD.RD_Destn IN ('DXB')
ORDER BY RH.RH_WEF DESC
    ,RH.RH_DocNo DESC

Somehow I got this output using the above Query.

   AirLineName         Slab(Value)  Public_Rate
------------------------------------------------
    Aeroflot Cargo      -45.00      263.00
    Aeroflot Cargo      45.00       219.00
    Aeroflot Cargo      100.00      184.00
    Aeroflot Cargo      300.00      176.00
    Aeroflot Cargo      500.00      150.00
    Aeroflot Cargo      1000.00     130.00

    Air Arabia Cargo    -45.00      140.00
    Air Arabia Cargo    45.00       130.00
    Air Arabia Cargo    100.00      95.00
    Air Arabia Cargo    250.00      85.00
    Air Arabia Cargo    500.00      70.00

After this, I want Output this like this. Here (if slab value is minus then it will come on Normal Column name(Public_Rate value) and if slab in plus then.
It will pick the value from Public_Rate it goes to different category like +20 +45 +100 +250 +300 +500 +1000 depends on Public_Rate column value... )
AirLineName         Normal    +20   +45   +100    +250   +300   +500  +1000
----------------------------------------------------------------------------------
Aeroflot Cargo      263.00          219    184            176    150   130

Air Arabia Cargo    140             130     95      85            70

I don't have any idea or Logic how to write this query....Thank you!!

A: You can try this below logic considering your output as input data-
DEMO HERE
SELECT AirLineName,
SUM(CASE WHEN Slab_Value = -45 THEN Public_Rate ELSE 0 END) 'Normal',
SUM(CASE WHEN Slab_Value>= 20 AND Slab_Value < 45 THEN Public_Rate ELSE 0 END) '+20',
SUM(CASE WHEN Slab_Value>= 45 AND Slab_Value < 100 THEN Public_Rate ELSE 0 END) '+45',
SUM(CASE WHEN Slab_Value>= 100 AND Slab_Value < 250 THEN Public_Rate ELSE 0 END) '+100',
SUM(CASE WHEN Slab_Value>= 250 AND Slab_Value < 300 THEN Public_Rate ELSE 0 END) '+250',
SUM(CASE WHEN Slab_Value>= 300 AND Slab_Value < 1000 THEN Public_Rate ELSE 0 END) '+300',
SUM(CASE WHEN Slab_Value>= 1000 THEN Public_Rate ELSE 0 END) '+1000'
FROM your_output
GROUP BY AirLineName


text:
Q: Best practice for dealing with objects declared in scope of multiple namespaces So for whatever reason if you have some object declared within several nested namespaces, and you need to use it in a function outside of those namespaces, what is the best practice for dealing with the excess noise?
Is it acceptable to refactor something like:
void doWidgetThings
{
    NamespaceA::NamespaceB::NamespaceC::Widget widget1;
    NamespaceA::NamespaceB::NamespaceC::Widget widget2;
    //...
}

To:
void doWidgetThings
{
    typedef NamespaceA::NamespaceB::NamespaceC::Widget  Widget;

    Widget widget1;
    Widget widget2;
    //...
}

Or is there a better way?

A: The using keyword is more idiomatic to C++, although typedef is completely fine. The typedef keyword is left for backwards compatibility and can't alias template types, thus using was introduced on C++11 standard. So, if you ever need to alias a template type, your code could benefit from consistency by using using.
You can rewrite your example like so
void doWidgetThings()
{
    using NamespaceA::NamespaceB::NamespaceC::Widget;
    Widget widget1;
    Widget widget2;
    //...
}

If you want to rename the Widget type to avoid any name collision, you can write
void doWidgetThings()
{
    using MyWidget = NamespaceA::NamespaceB::NamespaceC::Widget;
    MyWidget widget1;
    MyWidget widget2;
    //...
}

And if you happen to have a template parameter, you can also parameterize it like so:
void doWidgetThings()
{
    template <class A> using MyWidget = NamespaceA::NamespaceB::NamespaceC::Widget<A>;
    MyWidget<int> widget1;
    MyWidget<int> widget2;
    //...
}


text:
Q: How to embed matplotlib funcAnimation object within PyQT GUI I am trying to figure out how to embed a Matplotlib animation (using funcAnimation) within a PyQT GUI. There is surprisingly little that I could find on the web...this link was basically it, and it was difficult to follow:
Can I use Animation with Matplotlib widget for pyqt4?
The following code is a very simple animation using Matplotlib. It is just a circle moving across the screen, and it works fine:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib import animation

fig,ax = plt.subplots()
ax.set_aspect('equal','box')
circle = Circle((0,0), 1.0)
ax.add_artist(circle)
ax.set_xlim([0,10])
ax.set_ylim([-2,2])

def animate(i):
    circle.center=(i,0)
    return circle,

anim = animation.FuncAnimation(fig,animate,frames=10,interval=100,repeat=False,blit=True)

plt.show()

The following is my attempt at embedding this animation within a PyQT GUI. (I believe I have prevented the reference to the animation object from being garbage collected by calling it self.anim):
import sys
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib import animation

class Window(QtGui.QDialog): #or QtGui.QWidget ???

    def __init__(self):
        super(Window, self).__init__()
        self.fig = plt.figure()
        self.canvas = FigureCanvas(self.fig)
        self.button = QtGui.QPushButton('Animate')
        self.button.clicked.connect(self.animate)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def animate(self):
        self.ax = self.fig.add_subplot(111)  # create an axis
        self.ax.hold(False)  # discards the old graph
        self.circle = Circle((0,0), 1.0)
        self.ax.add_artist(self.circle)
        self.ax.set_xlim([0,10])
        self.ax.set_ylim([-2,2])

        self.anim = animation.FuncAnimation(self.fig,self.animate_loop,frames=10,interval=100,repeat=False,blit=False)
        plt.show()

    def animate_loop(self,i):
        self.circle.center=(i,0)
        return self.circle,

w = Window()
w.show()

Running this code brings up the GUI, but when I click the "Animate" button, nothing happens at all. There is not even an error message given in the console. Any insight would be much appreciated!


text:
Q: columns need to separate based on value and group on them Name     Address    City        State    Id        IdType
---------------------------------------------------------
XYZ      123 Rd     New York    NY       123D      Code1
XYZ      123 Rd     New York    NY       56A45     Code2
XYZ      123 Rd     New York    NY       D45256    Code3
XYZ      123 Rd     New York    NY       345TT     Code2
ZZZ      456 St     Richmond    VA       1564      Code2
ABC      879 Rd     Tampa       FL       5687AB    Code1
ABC      879 Rd     Tampa       FL       546YYY    Code3

Result:
Name    Address    City        State    code1     code2    code2_II    Code3
XYZ     123 Rd     New York    NY       123D      56A45    345TT       D45256
ZZZ     456 St     Richmond    VA                 1564
ABC     879 Rd     Tampa       FL       5687AB                         546YYY

Appreciate any help.
attached screenshot

A: Use conditional aggregation:
SELECT
    Name,
    Address,
    City,
    State,
    MAX(CASE WHEN IdType = 'Code1' THEN Id END) AS Code1,
    MAX(CASE WHEN IdType = 'Code2' THEN Id END) AS Code2,
    CASE
        WHEN MAX(CASE WHEN IdType = 'Code2' THEN Id END)
            <> MIN(CASE WHEN IdType = 'Code2' THEN Id END)
        THEN MIN(CASE WHEN IdType = 'Code2' THEN Id END)
    END AS Code2_II,
    MAX(CASE WHEN IdType = 'Code3' THEN Id END) AS Code3
FROM mytable
GROUP BY
    Name,
    Address,
    City,
    State

The MIN/MAX trick on Code2 allows the query to deal with two different values of Code2.


text:
Q: Yup mapping schema to element like choices[] (react and formik) I have a form that has an collection of checkboxes where the name is: choices[]. I have a PHP backend and the name of the checkboxes cant change. I'm trying to build the Yup schema to create a validation rule where one of the choices has to be picked.
My current solution is to have an onchange the updates a hidden field with a value. This value is what is validated against. But that cant be right.
Any idea? I've tried, but this isnt working. I cant seem to find a good example of this on the web so i've decided to ask here.
choices[]: Yup.boolean().required('error we need to pick one')

EDIT to add in some code:
import React, { ChangeEvent, useState, useEffect } from 'react'

import Checkbox from ...
import CheckboxProps from ...
import CheckboxGroup from ...
import Label from ...

export interface CheckboxGroupChoicesProps {
  setFieldValue?: any
}

/**
 *
 * @param props
 */
const CheckboxGroupChoices: React.FunctionComponent<
  CheckboxGroupChoicesProps
> = props => {
  /**
   * State management for the checked counter, we use this in a hidden field for validation purposes
   */
  const [checkedCounter, setCheckedCounter] = useState(0)
  const [initialLoad, setInitialLoad] = useState(1)
  const hiddenFieldName = 'cbxSFVal'

  /**
   * Enable validation on this checkbox field
   *
   * This is a required field, as such we need to ensure that at least one of the
   * checkboxes has been selected. By incrementing the <hidden> field we ensure
   * that we have an idea on how many of the checkboxes have been selected. We
   * then use this within the validation.tsx to do some stuff.
   *
   * @param e: ChangeEvent
   */
  function validateCheckboxRequired(e: ChangeEvent) {
    if ((e.currentTarget as HTMLInputElement).checked) {
      setCheckedCounter(checkedCounter + 1)
    } else {
      setCheckedCounter(checkedCounter - 1)
    }
  }

  /**
   * Handle the state change for checkedCounter.
   * setFieldValue is from formik and we can use it to update the hidden field
   * that we use for validation.
   */
  useEffect(() => {
    if (initialLoad != 1) {
      props.setFieldValue(hiddenFieldName, checkedCounter)
    } else {
      setInitialLoad(0)
    }
  }, [checkedCounter])

  /**
   * Create an array of checkboxes that will be sent to the Checkboxgroup molecule.
   *
   * @return Array<ChecboxProps>
   */
  const getCheckboxes: any = () => {
    const checkboxes: Array<React.ReactElement<CheckboxProps>> = []
    const options = ['Car', 'Van', 'Bike']

    options.forEach((option, key) => {
      checkboxes.push(
        <Checkbox
          label={option}
          value={option}
          disabled={false}
          name={'choices[]'}
          key={`choices-${key}`}
          handleOnClick={(e: ChangeEvent) => validateCheckboxRequired(e)}
        />
      )
    })

    return checkboxes
  }

  return (
    <>
      Pick choices
      <CheckboxGroup columns={3}>{getCheckboxes()}</CheckboxGroup>
      <input type={'hidden'} name={hiddenFieldName} />
    </>
  )
}

export default CheckboxGroupChoices

My component essentiall renders the following html:

<checkbox name='choices[]' value='car'> Car

<checkbox name='choices[]' value='van'> Car

<checkbox name='choices[]' value='bike'> Car

I use formik for my validation using a validation schema like so:
<Formik
    enableReinitialize
    initialValues={postingForm.initialValues}
    validationSchema={postingForm.validationSchema}
>
{form => (
  <Form> ....</Form>
)}
</Formik>

On submit i want to validate that at least one of my choices has been checked. My current component will +1 and -1 the value of a hidden field based on checked status for a checkbox. This is validated using:
cbxSFVal: Yup.number().min(1, required_message),
But i'm sure there must be an easier way to validate the checkboxes.

A: You need to set the property name with quotes.
const schema = Yup.object().shape({
  "choices[]": Yup.boolean().required('error we need to pick one')
});

Also, make sure you are accessing the property the correct way.
// Syntax Error
obj.choices[]

// Correct Way
obj["choices[]"]

Edit:
What you can do is have an array with the state of each checkbox so if you have 3 options, it would be an array of length 3 with false and you update the value to true when clicked.
This way, you can validate that one of the checkboxes are true with
"choices[]": Yup.array().oneOf(['true']).required('error we need to pick one')


text:
Q: Obtain the contents of a div tag that doesn't have a class attribute using python I tried to obtain the text inside a
 tag but was not able. I am trying to obtain the this text:
MsiExec.exe /X{42435041-332D-5350-00A7-A758B70C0F00}

This tag is not enclosed inside any div class.

Uninstaller: MsiExec.exe /X{42435041-332D-5350-00A7-A758B70C0F00}

Can somebody pls tell me how it is to done using python?
I am using BeautifulSoup to scrap the page.

A: Is this the entire contents of the scraped page?  If so, try this:
from bs4 import BeautifulSoup
soup = BeautifulSoup('
Uninstaller: MsiExec.exe /X{42435041-332D-5350-00A7-A758B70C0F00}
', 'html.parser')
print soup.div.text

Uninstaller: MsiExec.exe /X{42435041-332D-5350-00A7-A758B70C0F00}

If your scraped page contains other divs, this may not work.


text:
Q: Get different alert box on each iframe click

<!DOCTYPE html>

  <title>three.js css3d - youtube</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

I am firing a javascript function whenever an iframe is clicked. But that javascript alert is loading with page itself and not when iframe is clicked. Iframe is embedded on three.js scene. Can anybody tell me what is wrong with my code.


text:
Q: Morph multiple gateways into warp gates simultaneously I've seen a number of higher-level players select a number of gateways and morph them all simultaneously into warp gates. How do you do that? If I press the "G" button, it just starts one of them warping. Can they be set to all morph simultaneously, or are my eyes just playing tricks on me?

A: There's no way to do them all automatically. You just repeatedly press G really fast, or hold it down and let the keyboard auto repeat. (I'm assuming most pro StarCraft II players have a fairly low key repeat delay.)


text:
Q: Preserve files/directories for rpm upgrade in .spec file(rpmbuild) I wrote a .spec file on RHEL and I am building RPM using rpmbuild. I need ideas on how to handle the situation below.
My RPM creates an empty logs directory when it installs first time within the installation folder like below
 /opt/MyInstallation-1.0.0-1/some executables
 /opt/MyInstallation-1.0.0-1/lib/carries shared objects(.so files)
 /opt/MyInstallation-1.0.0-1/config/carries some XML and custom configuration files(.xml, etc)
 /opt/MyInstallation-1.0.0-1/log--->This is where application writes logs

When my RPM upgrades MyInstallation-1.0.0-1, to MyInstallation-1.0.0-2 for example, I get everything right as I wanted.
But, my question is how to preserve log files written in MyInstallation-1.0.0-1? Or to precisely copy the log directory to MyInstallation-1.0.0-2.

A: I believe if you tag the directory as %config, it is expected that the user will have files in there, so it will leave it alone.

A: I found a solution or workaround to this by hit and trial method :)
I am using rpmbuild version 4.8.0 on RHEL 6.3 x86_64. I believe it will work on other distros as well.
If you install with one name only like "MyInstallation" rather than "MyInstallation-version number-RPM Build Number" and create "logs directory as a standard directory(no additional flags on it)[See Original Question for scenario] Whenever you upgrade, you normally don't touch logs directory. RPM will leave its contents as it is. All you have to do is to ensure that you keep the line below in the install section.
%install
install --directory $RPM_BUILD_ROOT%{_prefix}/%{name}/log
Here, prefix and name are macros. That has to do nothing with underlying concept.
Regarding config files, the following is a very precise table that will help you guarding your config files. Again, this rule can't be applied on logs our applications create.
http://www-uxsup.csx.cam.ac.uk/~jw35/docs/rpm_config.html
Thanks & Regards.