text:
Q: How to insert record url into email template? I have email template of type 'Case'. Is there any way to add URL in body text of related case?
How can I get record URL in plugin?
Thanx.

A: In Emails and Dialogs you can add hyperlink in visual designer.
Here is the video about inserting an url Part 3: CRM 2011 Business Process Tips & Tricks (RichardKnudson)
Maybe you can create a workflow where you create an email and add a link into it.
In email body the link markup looks like that:
<hyperlink>
   <name>Link name</name>
   <value>Link URL</value>
</hyperlink>

In plugins I compose an url from several parts, server part + organization part + link to edit form of the entity.
Link to oppotunity for example:
1. ServerUrl = "http://192.168.0.1"
2. OrgName = "TestOrg"
3. OpportunityGuid = "96a63042-13d4-40b3-a4db-c024ffb64979"

var Link = String.Format("{0}/{1}/userdefined/edit.aspx?etc=3&id=%257b{2}%257d", ServerUrl, OrgName, OpportunityGuid);

If it's OnPremises You can get ServerURL from the registry.
RegistryKey regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM");
string serverUrl = regKey.GetValue("ServerUrl").ToString().Replace("/MSCRMServices", "");
serverUrl = serverUrl.Replace("/MSCRMServices", "");


text:
Q: Error in file(file, "rt") : cannot open the connection in r even after setting right path loading required library
install.packages("tidyverse")
install.packages("dplyr")
library("tidyverse")
library("dplyr")

vector for file names
files<- list.files(path = "C:/Users/91932/Downloads/archive (2)/Fitabase Data 4.12.16-5.12.16",pattern =".csv")

concat directory to file names
files<-str_c("C:/Users/91932/Downloads/archive (2)/Fitabase Data 4.12.16-5.12.16",files)

applying function to each element of vector

> map_df(.x = files, .f = read.csv,)

in above function map_df() i am getting  an error in file (file,"rt"), even after using setwd() to set path and checking using getwd() paths seems to be correct for .csv file .
why this error occurred? how to avoid such errors?

A: The error is because the path is wrong: you forgot the trailing slash in the path prefix in str_c. However, rather than using str_c, you can instruct list.files to give you full paths from the get-go:
files <- list.files(
    path = "C:/Users/91932/Downloads/archive (2)/Fitabase Data 4.12.16-5.12.16",
    pattern = ".csv",
    full.names = TRUE
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Instance variables in layout I am fairly new to rails so I apologize if I am using the wrong terminology.
I have a model Menuitem that I would like to display the contents of in a layout. How does one go about passing an instance variable into a layout?
I was looking for a layout helper of some sort but I was unable to find anything. I was also looking at defining the instance variable in the application controller to access it in the layout, would this work? If so what is the best way to go about doing it?
Thanks!

A: Two things I would note. First, you probably don't want to be doing this query every time you render any page in your application. You definitely want to cache your MenuItems.  Second, it might be helpful to put a convenience method on MenuItems class to cache this value. So, if I define a method
def MenuItem.all_for_menu
  @@all_for_menu ||= MenuItem.find(:all)  #returns value if exists, or initializes it
end

I can call MenuItem.all_for_menu in my layout and get all the menu items. When ever you add a new one or edit one, you'd have to invalidate that.
Another caching approach would be to put the data in a partial and cache that fragment using the standard caching call:
<% cache(:controller => "menu_items",
         :action => "list",
         :action_suffix => "all_menu_items") do %>
  <%= render :partial => "menu", :collection => MenuItem.all_for_menu %>
<% end %>

You can then expire that fragment by calling:
expire_fragment(:controller => "menu_items", :action => "list", :action_suffix => "all_menu_items")

A: The usual way of passing variables up from the view into the parent layout is to use the content_for method. (This answer is a copy + paste from a similar answer I posted at this question)
The normal view content gets rendered automatically into the yield call without an argument in the layout. But you can also put other placeholder content in by using yield with a symbol argument, and specifying that content from the view with content_for.
app/views/layouts/posts_layout.html.erb

    <title>My awesome site</title>

      <%= yield(:menu_items) %>

    <%= yield %>

app/views/posts/index.html.erb
<%= content_for :menu_items, some_helper_to_generate_menu %>

Here is you page content

A: Any instance variables defined in the controllers are auto-magically available in your views. If you are expecting an instance variable in your layout for all actions, you may want to consider defining the instance variable in a before_filter or encapsulating it in a controller method and using helper_method to make it accessible in your views.

A: It really depends on what you want to do with the model. I'll just guess, and you tell me what you need different to understand better how to do this. This code would work only if your MenuItem model has a field named name.
In the controller:
# Use whatever action you are currently displaying
def index
  @menu_items = MenuItem.all
end

In the index.html.erb view file:

<% @menu_items.each do |menu_item| %>
   <%= h menu_item.name %>
<% end %>

Obviously if this was a real menu, there would be hyperlinks there too :)

A: items_controller.rb (or something)
def show
   @menu_item = MenuItem.find(params[:id])
end

In the view show.html.erb:
<%= @menu_item.name %>


text:
Q: How to install php 5.6 on Ubuntu 20.04 beta have recently installed 20.04 beta on my Laptop. I need to install php 5.6. I have googled a lot regarding it, but all are suggesting to install Via Ondrej Suri PPA. I have done that but it is giving error that 'unable to locate package php5.6'. I have checked their repository and found that they have support for 19.10 version but not for 20.04.
I have tried to find other methods but unable to find any. I am a noob on linux.
Please suggest an alternate way. I badly need this.

A: Docker is your friend.
Alternatively you could use phpbrew.
After some time it might be that someone releases pre-built packages for PHP 5.6 but apparently that's not yet (and may never be, so don't count on it).

A: You need to configure repository on your system.
sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php

Then update repo
sudo apt update

Once the update complete, you can install any version from 5.6 to 7.4
sudo apt install -y php5.6

Or
sudo apt install -y php7.4


text:
Q: Chrome Apps. jQuery.Templates analogs I use jQuery.Template in my chrome app, but few days ago Chrome has updated Chrome Browser and Chrome Web Store and now i can't use manifest_version:1 if I want publish my extension in Web Store. Installation apps from Desktop has been disabled too. So i MUST use manifest_version:2, but there are some troubles with script-src 'unsafe-eval' which were used in jQuery.Templates.
So unsafe-eval is disallowed for script-src directive.
Any suggestions of which JavaScript template engine can be used?
What i need from template engine:

*

*No any new Function() or eval() usage.

*Simple data access like in jQuery.Templates: ${my_variable}

*Inline logic as: {{if a==b}} ... {{else b == c}} ... {{/if}}

*May be setting values to variables, but not necessarily: ${my_variable = 123, ''}

*It must be like a plugin (not framework, i wont to rewrite my app).

Note: No, i wont use sandboxed pages, i think it's very ugly solution.
Upd: thanks for answer. I've choosed Handlebars.js as a main template engine

A: I just needed a template system and looked for something that will work with manifest version 2 and found this....
http://code.google.com/p/json-template/wiki/Reference
...no where in its code does it use eval.  Unfortunately I'm finding it a little hard figuring how to use it to its full extent and only just started looking at it myself, so my following comments may not be entirely true.
I don't use JQuery so cant really compare, but I think it will do what you want, mostly.
It doesn't do the inline code with script tags like jquery, but that pretty easy to do.  I wrote this pretty quickly to allow me to use inline templates.....
jsontemplate.inlineSCRIPT = function(source,templateoptions) {
    var templates = source.querySelectorAll('script[type="text/json-template"]');
    for (var i = 0; i < templates.length; i++) {

        var template = templates[i];

        var options = JSON.parse(template.getAttribute('options'));

        if (!options.object) continue;

        var sourceObjectBits = options.object.split('.');

        var sourceObject = window[sourceObjectBits[0]];

        for (var i = 1; i < sourceObjectBits.length; i++) {
            if (!sourceObject[sourceObjectBits[i]]) break;
            sourceObject = sourceObject[sourceObjectBits[i]];
        }

        if (i != sourceObjectBits.length) continue;

        var target;
        if (options.target) {
            options.target == 'self' ? target = template : target = document.querySelector(options.target);
        } else {
            target = template;
        }

        if (!target) continue;

        if (options.innerOuter) {
            options.innerOuter == 'inner' ? target.innerHTML = jsontemplate.expand(template.innerHTML, sourceObject,templateoptions) : target.outerHTML = jsontemplate.expand(template.innerHTML, sourceObject,templateoptions);
        } else {
            target.outerHTML = jsontemplate.expand(template.innerHTML, sourceObject,templateoptions);
        }
    }
}

....and then in my html I can have...

The templates got some conditionals but their pretty basic, like if variable = true then do this.  But I couldn't find anything for if variable equals variable do this.  You could add them using a custom predicate, but I haven't figured how to add one with arguments without altering the source for jsontemplate.... I'm sure you could, I just haven't figured how to yet.   If you do add a predicate you should be able to the conditions you want but the syntax in the template doesn't look great.  I added an if equals and the source for the template looks like this....
{.if equals test title}
  test equaled title
{.end}

...which means, if the variable test's value equals the value for title then do this block, you could then use the or block and more ifs for else's.  I cant tell you how to add one without modding the source for jsontemplate, but here's how to do it that way....
After the function function _Pluralize(value, unused_context, args) { line 76 add another function, like....
// Are two variables equal, gotta add the error checking
function _Mine(value, context, args) {
  var s, p;
  switch (args.length) {
    case 0:
      s = value;
      break;
    case 1:
       s = context.get(args[0]);
      break;
    case 2:
      s = context.get(args[0])==context.get(args[1]);
      break;
    default:
      // Should have been checked at compile time
      throw {
        name: 'EvaluationError', message: 'pluralize got too many args'
      };
  }
  return s;
}

..then in the compile function function _Compile(template_str, options) { look for the line var default_predicates = PrefixRegistry([ (right under the function declaration) and add yours, like....
  // default predicates with arguments
  var default_predicates = PrefixRegistry([
    {name: 'equals', func: _Mine},
    {name: 'test', func: _TestAttribute}
      ]);

...Im sure you could use a predicate to set a variable as well, but haven't tried that.
Anyways, definitely worth having a look at.

A: Big thanks for your detailed answer but i found more elegant solution for me: Handlebars.js.

*

*Handlebars.js official site

*Handlebars.js source code
It has precompilation engine for templates and doesn't use eval() if using precompiled templates. It has very simple inline logic (I just can check that variable true or false) but it's very fast. =) You should try it for comparison. One moment: it uses NodeJS for precompilation. If you don't need it then just use Handlebars.compile().
Note: with manifest_version: 2 you MUST use precompilation. If you try to use Handlebars.compile() you'll get error about CSP violation.
If you have installed NodeJS you may try its precompilation engine using npm install handlebars -g. -g allows you to use handlebars in any project of your FS. You may need sudo this command. Next reload your terminal and cd to folder which consists of template files.
You need to migrate them to Handlebars.js syntax and add .handlebars extension for each file.
Then run handlebars path/to/templates/*.handlebars -f js/templates.js
If you load this js file after Handlebars.js you should found compiled templates here:
Handlebars.templates[your_template_file_name]

For example:
my_template.handlebars

{{testing_template}}

main.js
// example with RequreJS
require(["handlebars", "templates"], function(){
    var template = Handlebars.templates.my_template,
        rendered = template({
            "testing_template" : "some text right here"
        });

    console.log(rendered);
});

In console you'll see this:
> "
some text right here
"

Handlebars.js supports simple {{#if}} and {{#unless}} blocks as well as {{#each}} loops and custom helpers. Very powerful as i think.

A: I did some research on this and for me the quickest way was to just to write some custom functions that replace the functionality of jQuery Template.


text:
Q: In binary logistic regression, must the binary Y be interpreted as the dependent variable? If I have a binary variable, say sex, and I want to test whether multiple other variables are associated with it.  To do this, I run a logistic regression of the form
\begin{equation}
logit(probability(sex = male)) = \beta X1 + \beta X2 ... +  \beta Xk
\end{equation}
Once I do this, I calculate the pseudo R-squared, and it is 0.45 meaning that the regression explained 45% of the variance in sex.
My question is, is it also fair/correct to interpret this as sex explained 45% of the variance in the regressors?
Likewise, if the odds ratio for X1 is 2.0, can one claim that being male increased the odds of X1 occurring by 100%?
Basically, can the equal sign in the regression equation truly be treated as an equal sign (i.e., bi-directional equivalence) if I have no claim to directionality?

A: You do have a claim to directionality, it is just implicit.
A more explicit statement of the logistic model is:
$$ y \mid x \sim \text{Bernoulli}(p = logit^{-1}(\beta_0 + \beta_1 x_1 + \beta x_2 ... +  \beta x_k)) $$
Here, $\sim$ means "is distributed as".
You are making a distributional statement about $y$ conditional on $x$, and conditioning is not symmetric.  Because of the conditional, the $x$'s are not considered random by the model, so $y$ cannot be thought of as explaining variance in the $x$'s (at least from the point of view of the model).


text:
Q: no uniquely matching class member found for a template instanciation I have a class with a templated function. The function is specialized/instanciated so it can be defined in the cpp. Doxygen gives me an error about the template instanciation.
For example, my .h:
namespace LP
{
    namespace LF
    {
        class FileReader
        {
        public:
            template <class T> void Read( T *aValue );
            size_t Read( uint8_t *aBuffer, size_t aSizeToRead );
        };
    }
}

And my cpp:
/// Valid doxygen function doc
template<class T>
void
LP::LF::FileReader::Read( T *aValue )
{
    Read( reinterpret_cast<uint8_t *>( aValue ), sizeof( T ) );
}

//Template specialisation so it can be defined in the cpp file
template void LP::LF::FileReader::Read<uint8_t>( uint8_t * );
template void LP::LF::FileReader::Read<uint16_t>( uint16_t * );
template void LP::LF::FileReader::Read<uint32_t>( uint32_t * );

I got this error for all 3 lines of specialization:
warning: no uniquely matching class member found for
  template void LP::LF::FileReader::Read< uint8_t >(uint8_t *)
Possible candidates:
  'template < T >
  void LP::LF::FileReader::Read(T *aValue)' at line 48 of file FileReader.h
  size_t LP::LF::FileReader::Read(uint8_t *aBuffer, size_t aSizeToRead)' at line 49 of file FileReader.h

If I rename one of the Read functions, it fixes the error, but I would prefer not to do it.
The specialization dont need to be documented, the generic function is already documented
doxygen 1.8.13
Thanks
EDIT: changed title to instanciation from specialization

A: Didnt find a correct syntax, but a kind of workaround:
/// \relates LP::LF::FileReader
template void LP::LF::FileReader::Read<uint8_t>( uint8_t * );

Not sure why, but it silences the warning


text:
Q: socket.recv() in a Django application is not working properly As stated in the subject, socket.recv() in python, used in a django application is not working as expected. When I do the following commands in IDLE/ipython prompt, all data is received from the server:
import socket
s = socket.socket()
s.connect((host,port))
s.setblocking(0)
s.send("<some commands">)
data = ""
while True:
    try:
        new=s.recv(256)
        if not new: break
        data+=new
    except:
        break

After breaking from the while loop, data variable has all the received data.
Now when I put this into the views.py of my Django application like this:
s = _sendQuery(host, port)
data = s._receiveAll(s)

def _sendQuery(host, port):
    sock = None
    try:
        sock = socket.socket()
        sock.connect((host, port))
        sock.setblocking(0)
        sock.send("<some commands>")
    finally:
        return sock

def _receiveAll(sock):
    data = ""
    while True:
        try:
            temp = sock.recv(256)
            if not temp: break
            data+=temp
        except Exception, ex:
            data+=ex
    return data.strip()

Now when I call the app via browser, it returns the exception message:

[Errno 11] Resource temporarily unavailable

which tells me that during the first call to sock.recv(256), it has encountered an exception already (related to the sock.setblocking(0)), which is why the value of the variable data is the exception message only.
Anyone has an idea how to fix this? I'm quite stuck here.
Thanks in advance!

A: I found a solution to this, and I'm sharing it in case someone will find it useful. In the _receiveAll function, I modified this code from this:
if not temp: break

to this:
if len(temp) < 256:
    data+=temp
    break

I also removed the s.setblocking(0).
Hope this helps.


text:
Q: IIS asks for login/pass when accessed using hostname but not when 'localhost' is used. Why? I have setup IIS on my xp machine and have setup a default homepage (that comes with the IIS installed). It is a help page I think.
when I access the page with http : // localhost it works fine (IE/Chrome or FF) but when I access it using http://hostname it prompts for a loging/password and works when I enter my domain id and password on the intranet.
I have ensured that "anonymous access" is enabled in the properties window of the default site and "websites" node.
I searched stack overflow for similar queries but some indicate I need to change the IE/FF settings to allow "integrated security" etc and some suggest to look at the "log file".
I don't want to change the IE setting and there is nothing unusual in the log file of the IIS Server.
Can anybody help me figure out why this is happening?
thank you sb

A: You need to add http://<hostname> in Internet Explorer,  "Security for local intranet".
Steps:- Go to IE --> Tools --> Internet Options --> Security --> Local intranet --> Sites and add http://<hostname>
where <hostname> is the name of the computer that is hosting IIS.

A: *

*Go to IIS Manager

*Go to the Properties of the website

*Go to "Directory setting" and then Edit

*Check "Integrated Windows Authentication"


text:
Q: How to read xml file in java How to read XML file in java.
Below is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<LivescoreData>
  <Sport SportId="1">
    <Name language="en">Soccer</Name>
    <Name language="se">Fotboll</Name>
    <Category CategoryId="34">
      <Name language="en">Australia</Name>
      <Name language="se">Australien</Name>
      <Tournament TournamentId="144">
        <Name language="en">Hyundai A-League</Name>
        <Name language="se">Hyundai A-League</Name>
        <Match MatchId="4616735">
          <MatchDate>2011-01-05T07:30:00</MatchDate>
          <Team1 TeamId="1029369">
            <Name language="en">Wellington Phoenix FC</Name>
            <Name language="se">Wellington</Name>
          </Team1>
          <Team2 TeamId="529088">
            <Name language="en">Melbourne Victory</Name>
            <Name language="se">Melbourne Victory</Name>
          </Team2>
          <Status Code="100">
            <Name language="en">Ended</Name>
            <Name language="se">Avslutad</Name>
          </Status>
          <Winner>1</Winner>
          <Scores>
            <Score type="Current">
              <Team1>2</Team1>
              <Team2>0</Team2>
            </Score>
          </Scores>
          <Goals></Goals>
          <Cards></Cards>
          <Substitutions></Substitutions>
          <Lineups></Lineups>
        </Match>
      </Tournament>
    </Category>
    <Category CategoryId="1">
      <Name language="en">England</Name>
      <Name language="se">England</Name>
      <Tournament TournamentId="1">
        <Name language="en">Premier League</Name>
        <Name language="se">Premier League</Name>
        <Match MatchId="4601857">
          <MatchDate>2011-01-04T21:00:00</MatchDate>
          <Team1 TeamId="5431228">
            <Name language="en">Blackpool FC</Name>
            <Name language="se">Blackpool FC</Name>
          </Team1>
          <Team2 TeamId="23960">
            <Name language="en">Birmingham City</Name>
            <Name language="se">Birmingham City</Name>
          </Team2>
          <Status Code="100">
            <Name language="en">Ended</Name>
            <Name language="se">Avslutad</Name>
          </Status>
          <Winner>1</Winner>
          <Scores>
            <Score type="Current">
              <Team1>5</Team1>
              <Team2>1</Team2>
            </Score>
          </Scores>
          <Goals></Goals>
          <Cards></Cards>
          <Substitutions></Substitutions>
          <Lineups></Lineups>
        </Match>
        <Match MatchId="4601859">
          <MatchDate>2011-01-04T21:00:00</MatchDate>
          <Team1 TeamId="26511">
            <Name language="en">Fulham FC</Name>
            <Name language="se">Fulham FC</Name>
          </Team1>
          <Team2 TeamId="94356">
            <Name language="en">West Bromwich Albion</Name>
            <Name language="se">West Bromwich Albion</Name>
          </Team2>
          <Status Code="100">
            <Name language="en">Ended</Name>
            <Name language="se">Avslutad</Name>
          </Status>
          <Winner>1</Winner>
          <Scores>
            <Score type="Current">
              <Team1>4</Team1>
              <Team2>1</Team2>
            </Score>
          </Scores>
          <Goals></Goals>
          <Cards></Cards>
          <Substitutions></Substitutions>
          <Lineups></Lineups>
        </Match>
      </Tournament>
    </Category>
  </Sport>
</LivescoreData>

Below is the code:IT print the first value of XML Soccer and not able to print the next one.
nodeLst = doc.getElementsByTagName("Sport");
for (int i = 0; i < nodeLst.getLength(); i++) {

    Node myNode = nodeLst.item(i);

    if (myNode.getNodeType() == Node.ELEMENT_NODE) {

       Element Sport = (Element) myNode;
       NodeList Name= Sport
        .getElementsByTagName("Name");
       Element NameElement = (Element) Name.item(0);
       NodeList Namevalue = NameElement.getChildNodes();
       System.out.println("Name : "
    + ((Node) Namevalue.item(0)).getNodeValue()+"|");

    //This gives me null value
       NodeList Category = Sport
       .getElementsByTagName("Category");
       Element CategoryName= (Element) Category
       .item(0);
       NodeList Categoryvalue = CategoryName
       .getChildNodes();
       System.out.println("Category: "
       + ((Node) Categoryvalue.item(0))
       .getNodeValue());
   }
}

Am able to read only the first data Soccer.The second one just give null value.
I need my result as:
Soccer | Australia | Hyundai A-League | Wellington Phoenix FC - Melbourne Victory : 2 - 0
Soccer | England | Premier League | Blackpool FC - Birmingham City : 5 - 1
Soccer | England | Premier League | Fulham FC - West Bromwich Albion : 4 - 1

A: Since you haven't really said what you want to do with said XML file, the best I can do is direct you to this guide:
http://tutorials.jenkov.com/java-xml/dom.html

A: You could use JAXP for parsing the XML

A: It's much better/easier NOT to do this in Java, but to do it in XSLT or XQuery code which you can invoke from your Java application.


text:
Q: Dominant speaker not working properly | Twilio In Laravel I have already implemented the Twilio dominant Speaker related code the code in bellow .
In my code problem is in dominantSpeakerChanged function  when any user added in room ,unmute or mute the audio and mute unmute video then i am getting the response. But not getting any response when some one is talking.
when any user talk during the call at that time function is not called, i need when any user speak in call then give indication who is speaking like bellow image.
Image Link -
https://github.com/Soumojit1995/Issue/blob/main/Google_Meet_QA.max-2000x2000.jpg
Code -
                    var connectOptions = {
                        name: roomName,
                        // logLevel: 'debug',
                        _useTwilioConnection: true,
                        audio: { name: 'microphone' },
                        video: { name: 'camera' },
                        dominantSpeaker: true
                    };

                    if (previewTracks) {
                        connectOptions.tracks = previewTracks;
                    }

                    // Join the Room with the token from the server and the
                    // LocalParticipant's Tracks.
                    Video.connect(data.token, connectOptions).then(roomJoined, function(error) {
                    });

After call Video.connect function call roomJoined function in this function use dominantSpeakerChanged function.

// Successfully connected!
function roomJoined(room) {
room.on('dominantSpeakerChanged', participant => {
        console.log('The new dominant speaker in the Room is:', participant);
    });
}


text:
Q: Debian cannot see wireless network My WiFi connection just disappeared. I cannot find any network by GUI, but:
$ iw wlan0 scan

shows nearby networks. Also restarting NetworkManager by few ways (service ... restart or systemctl stop NetworkManager.service and then disable, enable, start) didn't help.
Using Dell E7440, Debian stretch.
Any ideas?
EDIT #1
result of ip link:
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: eth0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast state DOWN mode DEFAULT group default qlen 1000
    link/ether ec:f4:bb:62:af:80 brd ff:ff:ff:ff:ff:ff
3: wwp0s20u7c2i12: <BROADCAST,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN mode DEFAULT group default qlen 1000
    link/ether fe:16:26:8b:16:c1 brd ff:ff:ff:ff:ff:ff
4: wlan0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc mq state DOWN mode DEFAULT group default qlen 1000
    link/ether 5a:62:db:85:8e:84 brd ff:ff:ff:ff:ff:ff

in /etc/modprobe.d/ there is no iwlwifi.conf file, but just modsetting.conf. (Somebody posted a comment about that but now I can't see it...) I had to add those lines to that:
options iwlwifi 11n_disable=1 swcrypto=1

I made a backup of modesetting.conf and made iwlwifi.conf with that commands. Didn't help.
EDIT #2
The command:
$ nmcli dev status

gives me:
DEVICE   TYPE     STATE        CONNECTION
eth0     ethernet connected    eth0
cdc-wdm1 gsm      disconnected --
wlan0    wifi     unavailable  --
lo       loopback unmanaged    --


text:
Q: Error when trying to remove a gwidget using delete I have a problem when trying to use the delete method in gWidgets
require('gWidgets')
options(guiToolkit = "RGtk2")
win <- gWidgets::gwindow("trial", name="main",parent=c(0,0),width=400,height=100)
group<- gWidgets::ggroup(horizontal=TRUE)
gWidgets::add(win,group,expand=FALSE)
frame<-gframe("frame to remove")
add(group,frame)
delete(group,frame)

This code returns the following error.
Error in unclass(x) : cannot unclass an external pointer

gWidgets: Version: 0.0-54, RGtk2 :Version: 2.20.33, R win64
This problem is new in 2.4.0, could anyone give me a tip on how to solve that ?

A: I got the same issue. I re-installed RGtk2 :Version: 2.20.31 and everything is ok.


text:
Q: What is a way I can measure a performance difference before and after implementing state_machine gem? I'm almost finished implementing pluginaweek's state_machine gem and I'd like to try and measure something before I implement it so I can remeasure afterwards and see a difference. Right now there's a ton of condition logic in the views to deem whether or not an object is in certain state.
My first guess was to look at the load time of that main view, in my server log.

A: There's a variety of performance testing tools you can use.  The simplest is probably Apache's "ab" and on the more complex/flexible end is Apache Jmeter.
The process is simple:

*

*Choose a particular page or set of pages you'd like to measure performance on.

*Use the tools to hit your app and collect baseline data.

*Make changes to your app and rerun your test suite.

*Look at the data and see if there are meaningful improvements.  If so, keep your changes.  If not, remove them.

*Repeat until you're satisfied or have given up.  :)

This is obviously a very broad overview, but that's the gist.  The important thing is to use a consistent metric and a consistent set of test conditions.  E.g. the same command-line options for 'ab' or the same test plan for jmeter.
PS - Realistically, I wouldn't expect a big win from the changes you're describing.  The real win is likely in code readability and maintainability.


text:
Q: Synchronising SQL Server Compact database to work with an online database in C#? I am creating a desktop application and the users would like to view information from the application online, on a website that I would create.
The problem is my application is using SQL Server Compact as the database. I really need help on how to create a web service that can get data from the local desktop application. The users (aka admin of the app) should also be able to make changes from the website that would affect the app. They also want to see information such as inventory, contact, etc from the app on the website.
I have created the desktop app but have no clue on creating the web app / service or synchronizing the local database to the online one.

A: First of all, do you really need to have a local database and to keep it in sync with the online one? As far as I understood, you'll develop both of them so you'll have the control. Therefore the first logical step I see here is to create a REST API [1,2,3] and provide end-points both to read and write from your online database. For instance, if you want to build a simple API to register and login users, it should have at these end-points (operations):

*

*POST /users/register

*GET /users/:id

*PUT /users/:id

*POST /users/login

*DELETE /users/logout

So you can register a new user, see the data in his profile and be able to update it and, of course, log-in and log-out.
Now both your online and desktop applications can be clients of the API. You can add, edit and remove products in one of them and the changes will appear in the other one as well. Of course I am making some assumptions here (no need to have real-time updates, desktop client can have a always on connection, the size of the response payloads are not huge, etc).
If you need to have a local database anyway, you can have a field updatedAt in the tables you want to be in sync so the desktop application can query the API only to get the changes produced after a given date, decreasing the payload of the API response (and the bandwidth used, if that matters). Anyway, I think this step is an optimization to the real problem, so you might only think in all of this (having a local DB, keeping track of the changes and syncing...) after you thought carefully about the API and the clients first. Answering the following questions probably can help you to take a conscious decision:

*

*How many users will you have concurrently?

*How many items (DB records) will you have in the system?

If the answer is less than 100 users and a thousand of records, you probably should not worry about synchronization. However we can only help you with more information about the requirements of the system.
References:

*

*http://www.restapitutorial.com/

*https://github.com/interagent/http-api-design

*http://mattgemmell.com/api-design/
Best regards and a happy new year,
João


text:
Q: RuntimeError: The size of tensor a (549) must match the size of tensor b (512) at non-singleton dimension 1 GLUE_TASKS = ["cola", "mnli", "mnli-mm", "mrpc", "qnli", "qqp", "rte", "sst2", "stsb", "wnli"]

#useful in preprocessing, this sets what each task does.
task_to_keys = {
    "cola": ("sentence", None),
    "mnli": ("premise", "hypothesis"),
    "mnli-mm": ("premise", "hypothesis"),
    "mrpc": ("sentence1", "sentence2"),
    "qnli": ("question", "sentence"),
    "qqp": ("question1", "question2"),
    "rte": ("sentence1", "sentence2"),
    "sst2": ("sentence", None),
    "stsb": ("sentence1", "sentence2"),
    "wnli": ("sentence1", "sentence2"),
}

def set_module_grad_status(module, flag=False):
    if isinstance(module, list):
        for m in module:
            set_module_grad_status(m, flag)
    else:
        for p in module.parameters():
            p.requires_grad = flag

def compute_metrics(eval_pred):
    predictions, labels = eval_pred
    if task != "stsb":
        predictions = np.argmax(predictions, axis=1)
    else:
        predictions = predictions[:, 0]
    return metric.compute(predictions=predictions, references=labels)

#setting some model parameters
task = "qnli"
sentence1_key, sentence2_key = task_to_keys[task]
# model_checkpoint = "test-glue/basemodel"

num_labels = 3 if task.startswith("mnli") else 1 if task=="stsb" else 2

metric_name = "pearson" if task == "stsb" else "matthews_correlation" if task == "cola" else "accuracy"
validation_key = "validation_mismatched" if task == "mnli-mm" else "validation_matched" if task == "mnli" else "validation"

model_checkpoint = "google/mobilebert-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint, use_fast=True)
model = AutoModelForSequenceClassification.from_pretrained(model_checkpoint, num_labels=num_labels)
model = model.to(device)

args = TrainingArguments(
    "test-glue",
    evaluation_strategy = "epoch",
    learning_rate=2e-5,
    per_device_train_batch_size=batch_size,
    per_device_eval_batch_size=batch_size,
    num_train_epochs=epochs,
    weight_decay=0.01,
    save_steps=0
    # load_best_model_at_end=True,
    # metric_for_best_model=metric_name,
)

#load dataset
actual_task = "mnli" if task == "mnli-mm" else task #some error checking..
dataset = load_dataset("glue", actual_task)
metric = load_metric('glue', actual_task)

# tokenizer = AutoTokenizer.from_pretrained(model_checkpoint, use_fast=True)
def preprocess_function(examples):
    if sentence2_key is None:
        return tokenizer(examples[sentence1_key], truncation=True)
    return tokenizer(examples[sentence1_key], examples[sentence2_key], truncation=True)
encoded_dataset = dataset.map(preprocess_function, batched=True)

trainer = Trainer(
    model,
    args,
    train_dataset=encoded_dataset["train"],
    eval_dataset=encoded_dataset[validation_key],
    tokenizer=tokenizer,
    compute_metrics=compute_metrics
)
trainer.train()

I not quite sure why I am getting the error "RuntimeError: The size of tensor a (549) must match the size of tensor b (512) at non-singleton dimension 1" at the like "trainer.train()". Like isn't the each sample supposed to be consistently size of 512. This only happens with MobileBERT model and not on DistilBERT model. The code that I am using is mostly based on  the huggingface colab tutorial https://colab.research.google.com/github/huggingface/notebooks/blob/master/examples/text_classification.ipynb#scrollTo=7k8ge1L1IrJk


text:
Q: How to create a new column from a dictionary that its values are keys for sets? This is a subset of the main dataframe. The whole columns are lister in the dictionary below
age_groups_type procedureschoice=aortic_valve_repair    procedureschoice=arterial_switch
0   Pediatrics  False                                   True
1   Pediatrics  False                                   True
2   Pediatrics  False                                   True
3   Adults      True                                    False
4   Adults      True                                    False
5   Pediatrics  False                                   True
6   Adults      True                                    False
7   Pediatrics  False                                   True
8   Adults      True                                    False
9   Pediatrics  False                                   True

This dictionary contains the category of each operation whether being 'Aortic', 'Mitral'. etc. and their corresponding age_group_type whether being 'Adults' or 'pediatrics' (children)
{'Adults': {'Aortic': {'procedureschoice=aortic_valve_repair',
   'procedureschoice=arch_replacement',
   'procedureschoice=ascending_aortic_replacement',
   'procedureschoice=avrmechanical',
   'procedureschoice=avrstented_bioprosthesis',
   'procedureschoice=bentall',
   'procedureschoice=freestyle',
   'procedureschoice=homograft_aortic_root_replacement',
   'procedureschoice=ross',
   'procedureschoice=valve-sparing_aortic_root_replacement'},
  'Mitral': {'procedureschoice=mitral_valve_repair',
   'procedureschoice=mvrmechanical',
   'procedureschoice=mvrstented_bioprosthesis'},
  'Tricuspid': {'procedureschoice=tricuspid_valve_repair',
   'procedureschoice=tvrmechanical',
   'procedureschoice=tvrstented_bioprosthesis'},
  'CABG': {'procedureschoice=cabg'},
  'Myectomy': {'procedureschoice=myectomy'},
  'GUCH': {'procedureschoice=alcapa_repair',
   'procedureschoice=arterial_switch',
   'procedureschoice=asd_closure',
   'procedureschoice=atrial_septectomy',
   'procedureschoice=atrial_switchmustard',
   'procedureschoice=av_canal_repairpartial',
   'procedureschoice=av_canal_repairtransitional',
   'procedureschoice=central_shunt',
   'procedureschoice=coarctectomy_with_extended_end-to-end_anastomosis',
   'procedureschoice=cor-triatriatum_repair',
   'procedureschoice=coronary_av_fistula_repair',
   'procedureschoice=extra-anatomical_bypass_of_coa',
   'procedureschoice=fallot_repair',
   'procedureschoice=fontan',
   'procedureschoice=glenn',
   'procedureschoice=lpa_reconstruction',
   'procedureschoice=mbt_shunt',
   'procedureschoice=mpa_reconstruction',
   'procedureschoice=pa_banding',
   'procedureschoice=papvc_repair',
   'procedureschoice=pda_closure',
   'procedureschoice=pulmonary_trans-annular_patch',
   'procedureschoice=pulmonary_valve_replacementfreestyle',
   'procedureschoice=pulmonary_valve_replacementhomograft',
   'procedureschoice=pulmonary_valve_replacementstented_bioprosthesis',
   'procedureschoice=pulmonary_valvotomy',
   'procedureschoice=rastelli',
   'procedureschoice=relief_of_rvoto',
   'procedureschoice=resection_of_subaortic_membrane',
   'procedureschoice=rpa_reconstruction',
   'procedureschoice=rupture_sinus_of_valsalva_repair',
   'procedureschoice=rvot_patch',
   'procedureschoice=supravalvular_as_repair',
   'procedureschoice=vascular_ring_repair',
   'procedureschoice=vsd_closure'}},
 'Pediatrics': {'VSD': {'procedureschoice=vsd_closure'},
  'TGA': {'procedureschoice=arterial_switch',
   'procedureschoice=atrial_switchmustard',
   'procedureschoice=rastelli'},
  'Arch': {'procedureschoice=arch_repair',
   'procedureschoice=coarctectomy_with_extended_end-to-end_anastomosis',
   'procedureschoice=extra-anatomical_bypass_of_coa'},
  'Canal': {'procedureschoice=av_canal_repaircomplete',
   'procedureschoice=av_canal_repairpartial',
   'procedureschoice=av_canal_repairtransitional'},
  'Valvular': {'procedureschoice=aortic_valve_repair',
   'procedureschoice=avrmechanical',
   'procedureschoice=avrstented_bioprosthesis',
   'procedureschoice=bentall',
   'procedureschoice=freestyle',
   'procedureschoice=homograft_aortic_root_replacement',
   'procedureschoice=maze_procedure',
   'procedureschoice=mitral_valve_repair',
   'procedureschoice=mvrmechanical',
   'procedureschoice=mvrstented_bioprosthesis',
   'procedureschoice=ross',
   'procedureschoice=tricuspid_valve_repair',
   'procedureschoice=tvrmechanical',
   'procedureschoice=tvrstented_bioprosthesis',
   'procedureschoice=valve-sparing_aortic_root_replacement'},
  'RVOT_PA': {'procedureschoice=fallot_repair',
   'procedureschoice=lpa_reconstruction',
   'procedureschoice=mpa_reconstruction',
   'procedureschoice=pulmonary_trans-annular_patch',
   'procedureschoice=pulmonary_valve_replacementfreestyle',
   'procedureschoice=pulmonary_valve_replacementhomograft',
   'procedureschoice=pulmonary_valve_replacementstented_bioprosthesis',
   'procedureschoice=pulmonary_valvotomy',
   'procedureschoice=relief_of_rvoto',
   'procedureschoice=rpa_reconstruction',
   'procedureschoice=rvot_patch'},
  'Palliative': {'procedureschoice=atrial_septectomy',
   'procedureschoice=central_shunt',
   'procedureschoice=dks',
   'procedureschoice=first_stage_switchpab,_bts',
   'procedureschoice=fontan',
   'procedureschoice=glenn',
   'procedureschoice=mbt_shunt',
   'procedureschoice=pa_banding'}}}

what I need is to create a new column procedure_group that filled with the dictionary keys ['Aortic', 'Mitral', 'Tricuspid', 'CABG', 'Myectomy', 'GUCH'] for adult patients and ['VSD', 'TGA', 'Arch', 'Canal', 'Valvular', 'RVOT_PA', 'Palliative'] for pediatric patients.
I tried this
def code_map(row):
    for key in code.keys():
        for i in code[key].keys():
            for k in list(code[key][i]):
                if row[row['age_groups_type'] == 'Adults' & row[k] == True]:
                    return i
                elif row[row['age_groups_type'] == 'Pediatrics' & row[k] == True]:
                    return i
df['procedure_group'] = df.apply(code_map, axis=1)

and this
def code_map(df):
    for col in df:
        for i in range(len(adult_list)):
            if code["Adults"][i][col] == True:
                return code["Adults"][i]
        for i in range(len(pediatrics_list)):
            if code["Pediatrics"][i][col] == True:
                return code["Pediatrics"][i]
df['procedure_group'] = df.apply(code_map(df), axis=1)

and other solutions, but all trials failed.
The final output will be like this
age_groups_type procedureschoice=aortic_valve_repair    procedureschoice=arterial_switch       procedure_group
0   Pediatrics  False                                   True               TGA
1   Pediatrics  True                                    False              Aortic
2   Pediatrics  False                                   True               TGA
3   Adults      True                                    False              Aortic
4   Adults      True                                    False              Aortic
5   Pediatrics  False                                   True               TGA
6   Adults      True                                    False              Aortic
7   Pediatrics  False                                   True               TGA
8   Adults      True                                    False              Aortic
9   Pediatrics  False                                   True               TGA

The logic I'm thinking of is if, in each row, the procedure is True and the patient is Adults, return the dictionary values corresponding this row.
How can I do this?


text:
Q: How can a gem provide Cucumber features and step definitions? I have two Rails projects (A and B) with the following gems, among others:
#project A
gem "green_theme", :path => "~/dev/themes/green_theme"
gem "devel_tasks", :path => "~/dev/themes/devel_tasks"

#project B
gem "red_theme", :path => "~/dev/themes/red_theme"
gem "devel_tasks", :path => "~/dev/themes/devel_tasks"

Both projects, A and B, have a features dir for features and steps.
Both themes, red and green, should have common functionalities like
login/logout buttons, html meta-tags, and so on.
What I need to do is place the common theme related features and steps
inside the devel_tasks gem. This way I can share the tests and use
them to check whether a given template is compliant with the standard.
A simple way to test what I need to do is create a new Rails project
with a sample Cucumber feature, then try to run "cucumber
examples/i18n/en/features".

A: If possible I'd extract the common functionality out of the two projects into a gem and test it once there.
If for some reason the two projects really have to separately implement the same functionality:
You can provide step definitions in a gem simply by putting them in a file and instructing the user to require that file in their env.rb.
I don't know of a way to provide features in a gem that can simply be run in place, so you'll have to provide a generator that copies the features to the features directory. And if you're going to generate the features it's probably simpler for the user to generate the step definitions too.


text:
Q: Postgres slow distinct query for multiple columns I have a very simple query that is taking way too long to run.
SELECT DISTINCT col1,col2,col3,col4 FROM tbl1;

What indexes do I need to add to speed up? I ran a simple vacuum; command and added the following index but neither helped.
CREATE INDEX tbl_idx ON tbl1(col1,col2,col3,col4);

The table has 400k rows.  In fact counting them is taking extremely long as well.  Running a simple
SELECT count(*) from tbl1;

is taking 8 seconds.  So it's possible my problems are with vacuuming or reindexing or something I'm not sure.
Here is the explain command
EXPLAIN SELECT DISTINCT col1,col2,col3,col4 FROM tbl1;
                                   QUERY PLAN
---------------------------------------------------------------------------------
 Unique  (cost=3259846.80..3449267.51 rows=137830 width=25)
   ->  Sort  (cost=3259846.80..3297730.94 rows=15153657 width=25)
         Sort Key: col1, col2, col3, col4
         ->  Seq Scan on tbl1 (cost=0.00..727403.57 rows=15153657 width=25)
(4 rows)

Edit: I'm currently running vacuum full; which hopefully fixes the issue and then maybe someone can give me some pointers on how to fix where I went wrong.  It is several hours in and still going as far as I can tell.  I did run
select relname, last_autoanalyze, last_autovacuum, last_vacuum, n_dead_tup from pg_stat_all_tables where n_dead_tup >0;

and the table has nearly 16 million n_dead_tup rows.

A: My data doesn't change that frequently so I ended up creating a materialized view
CREATE MATERIALIZED VIEW tbl1_distinct_view AS SELECT DISTINCT col1,col2,col3,col4 FROM tbl1;
that I refresh with a cronjob once a day at 6am
0 6 * * * psql -U mydb mydb -c 'REFRESH MATERIALIZED VIEW tbl1_distinct_view;

A: VACUUM and VACUUM FULL are two commands that sound the same but have very different effects.
VACUUM scans a table for tuples that it no longer needs, so that it can overwrite that space during INSERT or UPDATE statements. This command only looks at deleted rows, and does not "defragment" the table - it leaves the space usage the same, but simply marks some space as "dead" in order that it can be reused.
VACUUM FULL looks at every row, and reclaims the space left by deleted rows and dead tuples, essentially "defragmenting" the table. If this is done on a live table, it can take a very long time, and can result in heavy weight locks, increased IO, and index bloat.
I imagine what you need is a VACUUM followed by an ANALYZE, which will rebuild your statistics for each table, improving index performance. These should be performed reasonably regularly in low-usage times for a database. Only if you have a lot of space to reclaim (due to lots of DELETE statements) should you use VACUUM FULL.
Anyhow, since you've run a VACUUM FULL, once that it complete you should run an ANALYZE on the database, followed by a REINDEX (on the database), and then an EXPLAIN on your query again, you should notice an improvement.

A: try force database to use your index
set enable_seqscan=off ;
SELECT DISTINCT col1,col2,col3,col4 FROM tbl1;
set enable_seqscan=on ;


text:
Q: Arithmetic mean and Gini index in a grouped distribution In the following table is represented the relative frequency distribution of 100 families related to the class of annual income (in thousands of dollars):
Income:                         10-25   25-40   40-60   60-100  100-200
Relative frequencies:           0,48    0,25    0,15    0,10    0,02

Calculate arithmetic mean and Gini index.
I started calculating the middle value of the classes and the cumulative frequency:
Income (middle value):          17,5    32,5    50      80      150
Cumulative frequency:           0,48    0,73    0,88    0,90    1

Problem is, how do I calculate the arithmetic mean? I though it was the summation of the middle values * their relative frequency, which outputs 35,025 (8,4 + 8,125 + 7,5 + 8 + 3). The problem is that the sum of the residuals from the estimated mean isn't zero!
17,5-35,025 = -17,525   +
32,5-35,025 = -2,525    +
50-35,025   = 14,975    +
80-35,025   = 44,975    +
150-35,025  = 114,975   =

154,875 ≠ 0

Is 35,025 still the correct value for arithmetic mean even if the sum of residuals isn't 0?
The other question: Gini index. It's a concentration estimator. It's calculated in this way:

Where Qi are cumulative frequency and Pi are cumulative frequency in case of equidistribution.
Can you help me? :)


text:
Q: How do I NOT require user's email when using Rails Omniauth gem and Google OpenID My current /config/initializers/omniauth.rb file contains:
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :open_id, nil, :name => 'google', :identifier => 'https://www.google.com/accounts/o8/id'
end

When I login via Google by going to /auth/google, Google reports:

DOMAIN is asking for some information from your Google Account EMAIL
  -  Email address: NAME (EMAIL)

My application doesn't need the user's email and so I'd like to remove this barrier to entry.  Is there anyway to remove this requirement.  For Facebook, I've found I can add the "scope" property of options, for example:
provider :facebook, 'APP_ID', 'APP_SECRET', {:scope => ''}

A: Based on a quick review of the source for the OpenID strategy (which Google Aps auth inherits from), you can pass in options specifying which attributes are optional vs. required for an Attributes Exchange (AX) auth.
See source code here for options: https://github.com/intridea/omniauth/blob/master/oa-openid/lib/omniauth/strategies/open_id.rb
Based on that, I think you could change the options like so to remove email as a required attribute:
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :open_id, nil, :name => 'google', :identifier => 'https://www.google.com/accounts/o8/id', :required => [], :optional => []
end

Good luck.  I didn't test this, just reading the source.


text:
Q: java.lang.IncompatibleClassChangeError: org.apache.http.params.SyncBasicHttpParams Whenever i try to install my app via .apk , i get a crash and logcat shows following stack trace:

FATAL EXCEPTION: main
      Process: com.example.sabeeh.helloworld, PID: 24905
      java.lang.IncompatibleClassChangeError: org.apache.http.params.SyncBasicHttpParams
              at dalvik.system.DexFile.defineClassNative(Native Method)
              at dalvik.system.DexFile.defineClass(DexFile.java:226)
              at dalvik.system.DexFile.loadClassBinaryName(DexFile.java:219)
              at dalvik.system.DexPathList.findClass(DexPathList.java:321)
              at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:54)
              at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
              at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
              at java.lang.Class.classForName(Native Method)
              at java.lang.Class.forName(Class.java:309)
              at com.activeandroid.ReflectionUtils.getParsers(ReflectionUtils.java:158)
              at com.activeandroid.Registry.initialize(Registry.java:100)
              at com.activeandroid.ActiveAndroid.initialize(ActiveAndroid.java:8)
              at com.activeandroid.app.Application.onCreate(Application.java:9)
              at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1012)
              at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4553)
              at android.app.ActivityThread.access$1500(ActivityThread.java:151)
              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
              at android.os.Handler.dispatchMessage(Handler.java:102)
              at android.os.Looper.loop(Looper.java:135)
              at android.app.ActivityThread.main(ActivityThread.java:5254)
              at java.lang.reflect.Method.invoke(Native Method)
              at java.lang.reflect.Method.invoke(Method.java:372)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
  04-15 18:55:44.698

It works fine when played from android studio , I have research heavily over the internet , and most of the answers are from 2 3 years back , in which they have asked to downgrade the apache mime, but older versions lack significant functionality .
Currently i am using these versions:
compile files('src/libs/httpmime-4.3.6.jar')
compile files('src/libs/httpcore-4.3.3.jar')
compile files('src/libs/httpclient-4.3.6.jar')

Please do note , i have already tried downgrading and upgrading libraries.


text:
Q: Group Identity Users in many-to-many relationship and limit to a resource based on role I'm trying to setup my database using code-first to acheieve the following.  A user signs up to the site and becomes an admin using built in roles, and has access to a single Instance class (using ApplicationUserInstance).  The admin can then add another Admin/Manager/User who become part of the same user group, and also have access to the same Instance.
There will be higher role called SuperAdmin, who will beable to acess multiple Instances rather than just a single like above.
So far i'm adding an Admin, and creating an instance fine and then assigning the admin to the instance.  When i then try and create a group and assign the user to the group i got a foreign key error like shown below.
I'm not sure this is even the best way to achieve what i require, any help would be appreicated. Thanks
DbContext:
public class ApplicationUser : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Company { get; set; }
    public string Telephone { get; set; }
    public string Postcode { get; set; }
    public virtual ICollection<ApplicationUserInstance> ApplicationUserInstances { get; set; }
    public virtual ICollection<UserGroup> UserGroups { get; set; }
}

public class UserGroup
{
    public string ApplicationUserId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
    public string GroupId { get; set; }
    public virtual Group Group { get; set; }
}

public class Group
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public string GroupId { get; set; }
    [MaxLength(50)]
    public string Company { get; set; }
    public virtual ICollection<UserGroup> UserGroups { get; set; }
}

public class ApplicationUserInstance
{
    public string ApplicationUserId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
    public string InstanceId { get; set; }
    public virtual Instance Instance { get; set; }
}

public class Instance
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public string InstanceId { get; set; }
    [MaxLength(100)]
    public string Company { get; set; }
    public virtual ICollection<ApplicationUserInstance> ApplicationUserInstances { get; set; }
    public virtual ICollection<GSMSite> GSMSites { get; set; }
}

builder.Entity<ApplicationUserInstance>().HasKey(aui => new { aui.ApplicationUserId, aui.InstanceId });
builder.Entity<UserGroup>().HasKey(ug => new { ug.ApplicationUserId, ug.GroupId });

User Service:
var newInstance = new Instance
    {
       Company = request.Company
    };
var createInstance =  await _dbContext.Instances.AddAsync(newInstance);

var createInstanceUser = await _dbContext.ApplicationUserInstances.AddAsync(new ApplicationUserInstance { ApplicationUserId = newUser.Id, InstanceId = newInstance.InstanceId });

 var newGroup = new Group
     {
       Company = request.Company
     };
 var createGroup = await _dbContext.Groups.AddAsync(newGroup);

 var createUserGroup = await _dbContext.UserGroups.AddAsync(new UserGroup { ApplicationUserId = newUser.Id, GroupId = newGroup.GroupId });

  await _dbContext.SaveChangesAsync();

Error:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details.

---> Microsoft.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint "FK_UserGroups_AspNetUsers_GroupId". The conflict occurred in database "GSMProfile", table "dbo.AspNetUsers", column 'Id'.

The statement has been terminated.

A: Adding the following Fluent API seemed to do the job, it now works:
 builder.Entity<UserGroup>()
        .HasOne(c => c.ApplicationUser)
        .WithMany(e => e.UserGroups)
        .HasForeignKey(c => c.ApplicationUserId);

 builder.Entity<UserGroup>()
        .HasOne(c => c.Group)
        .WithMany(e => e.UserGroups)
        .HasForeignKey(c => c.GroupId);


text:
Q: Чем открыть флеш-сайт, кроме WebBrowser? Чем открывать флеш-сайт, кроме WebBrowser?
И как это сделать

UPD
пробовал Awesomium, но там почему-то не работает аппаратное ускорение, всё тормозит. Да и размер проекта становится 40 мб... я думал может есть какое-то другое решение, сам флеш-плеер какой-то голый, но он же не может открыть сайт? или может... если он полностью на флеше

A:
пробовал Awesomium, но там почему-то не работает аппаратное ускорение,
  всё тормозит.

А документацию и гугл изучали? Где-то должно включаться, еще можно попробовать другой плагин, другую версию.

Да и размер проекта становится 40 мб...

Это много?

сам флеш-плеер какой-то голый, но он же не может открыть сайт? или
  может... если он полностью на флеше....

SWF точно может открыть. Пробуйте скачать SWF и открывать...

A: Через COM компонент Shockwave Flash Object
axShockwaveFlash1.LoadMovie(0, "http://site.com/flash.swf");   // флеш-объект в сети
axShockwaveFlash1.Movie = @"C:\holdthelinegame.swf";           // локальный файл

(!) Флеш-объект в сети обязательно должен быть прямой ссылкой на .swf файл. Узнать прямую ссылку можно покопавшись в исходном тексте страницы сайта.


text:
Q: Поиск решения нелинейных задач методом ОПГ или подобным как в Excel для Python коллеги,подскажите пожалуйста, какие есть методы в Python для решения многопараметрических нелинейных задач, которые в  Excel решаются методом ОПГ (поиск решения) или подобным способом?
Опишу задачу:
Я расчитываю стальную трубу на устойчивость. Моя задача подобрать такой начальный параметр mx*, чтобы прийти к заранее заданному значению решения ex0. Зависимость между ними нелинейная, но если бы существовала функция ex0(mx*), то она была бы возрастающей. Я прописала весь ход решения в excel и на python. В excel я просто пользовалась кнопкой "подбор параметра", а в python решала эту задачу методом дихотомии, задаваясь начальным и конечным значением mx*, и, таким образом постепенно приближалась к нужному ex0. Однако, это долгий метод. Какой метод можно применить вместо него? Какая там математика?
Для понимания на сколько задача не линейная, прикладываю схему расчета. По моему мнению стандартные решатели нелинейных уравнений тут не годятся.


text:
Q: HIVE - Manual parse data enclosed by double quotes and separated by comma I've seen some similar questions but since the problem is not exactly the same or then solutions do not apply in my case, I post my issue here.
I am parsing a table that contains a csv rows in a csv_line column.
The issue is that some columns have commas, which is also the field separator. Those columns are embedded in quotes.
The parsing I was doing is:
with
sample as (
select 'field1,field3,"http://another.domain/abc/...eIds=111,222,333,444,...,",CustomerX,end' as csv_line)

select

 regexp_extract(csv_line,'(,?(".*?"|[^,]*)){1}') as f1
 regexp_extract(csv_line,'(,?(".*?"|[^,]*)){n}') as fn

from raw_sample

I have tried to replace characters/commas.
I know that OpenCSVSerde allows to define the separator character and escape double-quotes, in the Create table, but I am looking perhaps to a property that can be set, or perhaps a regular expression, that can do the split in the correct way.
Thanks in advance

A: with raw_sample as (
select 'field1,field2,fiend3,123,456,"http://some.domain/abc/Player.aspx?playerID=111&BrowseIds=2221,423062611,423870887,424044345,...,",THIS_IS_MY,en,20 294 998 1001,end' as raw_line
)

select  regexp_extract(raw_line,'(,?(".*?"|[^,]*)){01}',2) as c01
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){02}',2) as c02
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){03}',2) as c03
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){04}',2) as c04
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){05}',2) as c05
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){06}',2) as c06
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){07}',2) as c07
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){08}',2) as c08
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){09}',2) as c09
       ,regexp_extract(raw_line,'(,?(".*?"|[^,]*)){10}',2) as c10

from    raw_sample
;

+--------+--------+--------+-----+-----+-----------------------------------------------------------------------------------------------------+------------+-----+-----------------+-----+
|  c01   |  c02   |  c03   | c04 | c05 |                                                 c06                                                 |    c07     | c08 |       c09       | c10 |
+--------+--------+--------+-----+-----+-----------------------------------------------------------------------------------------------------+------------+-----+-----------------+-----+
| field1 | field2 | fiend3 | 123 | 456 | "http://some.domain/abc/Player.aspx?playerID=111&BrowseIds=2221,423062611,423870887,424044345,...," | THIS_IS_MY | en  | 20 294 998 1001 | end |
+--------+--------+--------+-----+-----+-----------------------------------------------------------------------------------------------------+------------+-----+-----------------+-----+


text:
Q: NAudio WaveOut.GetCapabilities().ProductName returns invalid characters in the device name Our application uses NAudio WaveOut to get audio devices connected to user computer. In this particular case, the use has windows machine running in Polish language. Therefore, when we enumerate the devices, WaveOut returns invalid characters in the Name of the devices.
For example. The device name should be "Głośniki (Urządzenie zgodne ze standardem High Definition Audio)"
But WaveOut returns something like this
Gԯݮiki (Urzڤzenie zgodne ze
Probably it is a case of UTF-8 encoding, which is missing in this case.
Will need help to fix this.
Thanks,

A: It was my mistake.. WaveOut.GetCapabilites() does returns strings in Unicode by default. We were printing it out in our logs as ansi-code and,therefore was printed incorrectly and presumed it to be incorrect.


text:
Q: cPickle:SystemError: error return without exception set While dumping large matrix (170000*20000) as follows
 cPickle.dump(train_set,gzip.open('train.pickle.gz','wb'), cPickle.HIGHEST_PROTOCOL)

I get following error:
SystemError: error return without exception set

How would I deal in this case?

A: cPickle can't be used for storing very large objects ( see http://bugs.python.org/issue11564 ).
You have several options:

*

*split the data into chunks and store it in multiple files

*numpy.save

*h5py <- my favorite because of its convenient numpy-like interface, plus the data are stored in hdf5 which enables interopability with other software/languages.

*pytables


text:
Q: Как подключить jQuery к index.html - Google расширениях у меня проблема с подключениям jQuery в Google расширениях.
index.html
<!DOCTYPE html>
<html lang="ru">
<head>
    <link rel="stylesheet" href="/style/style.css"/>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</head>
<body>
    SomeContent
    <script src="js/main.js"></script>
</body>
</html>

manifest.json
{
    "name": "TestEx",
    "description": "TestDescEx",
    "version": "1.0",
    "manifest_version": 3,
    "action":{
        "default_popup": "index.html"
    }
}

main.js
$("body").css("background","black");

в консоли выдаёт ошибку


text:
Q: How to decrease a memory in paged pool that consumed by CM31 tag? My RAM disappears for unknown tasks. I have known that my Paged pool has grown to 582 MB. Task manager does not show which process has consumed this RAM. Poolmon: CM31 = 338 MB, MmSt = 42, CM25 = 33, MmRe = 19...
This information is collected while Opera browser and Thunderbird work. Closed apps before monitoring: Element Desktop, Nheko.
In fact I did not capture when Paged pool has started to grow. I monitored 36 hours Paged pool is about 580 MB all time. I want to decrease memory consuming by CM31, but I don't like idea to reboot my PC each time. How can I decrease Paged pool without system reboot?
Findstr returned empty result for system32. I also tried to find driver using findstr in syswow64. Empty result else.


text:
Q: Can't understand assembly mov instruction between register and a variable I am using NASM assembler on linux 64 bit.
There is something with variables and registers I can't understand.
I create a variable named "msg":
 msg db "hello, world"

Now when I want to write to the stdout I move the msg to rsi register, however I don't understand the mov instruction bitwise ... the rsi register consists of 64 bit , while the msg variable has 12 symbols which is 8 bits each , which means the msg variable has a size of 12 * 8 bits , which is greater than 64 bits obviously.
So how is this even possible to make an instruction like:
mov rsi, msg  , without overflowing the memory allocated for rsi.
Or does the rsi register contain the memory location of the first symbol of the string and after writing 1 symbol it changes to the memory location of the next symbol?
Sorry if I wrote complete nonsense, I'm new to assembly and i just can't get the grasp of it for a while.

A: In NASM syntax (unlike MASM syntax) mov rsi, symbol puts the address of the symbol into RSI.  (Inefficiently with a 64-bit absolute immediate; use a RIP-relative LEA or mov esi, symbol instead.  How to load address of function or label into register in GNU Assembler)
mov rsi, [symbol] would load 8 bytes starting at symbol.  It's up to you to choose a useful place to load 8 bytes from when you write an instruction like that.
mov   rsi,  msg           ; rsi  = address of msg.  Use lea rsi, [rel msg] instead
movzx eax, byte [rsi+1]   ; rax  = 'e' (upper 7 bytes zeroed)
mov   edx, [msg+6]        ; rdx  = ' wor' (upper 4 bytes zeroed)

Note that you can use mov esi, msg because symbol addresses always fit in 32 bits (in the default "small" code model, where all static code/data goes in the low 2GB of virtual address space).  NASM makes this optimization for you with assemble-time constants (like mov rax, 1), but probably it can't with link-time constants.  Why do x86-64 instructions on 32-bit registers zero the upper part of the full 64-bit register?

and after writing 1 symbol it changes to the memory location of the next symbol?

No, if you want that you have to inc rsi.  There is no magic.  Pointers are just integers that you manipulate like any other integers, and strings are just bytes in memory.
Accessing registers doesn't magically modify them.
There are instructions like lodsb and pop that load from memory and increment a pointer (rsi or rsp respectively), but x86 doesn't have any pre/post-increment/decrement addressing modes, so you can't get that behaviour with mov even if you want it.  Use add/sub or inc/dec.

A: Disclaimer: I'm not familiar with the flavor of assembly that you're dealing with, so the following is more general.  The particular flavor may have more features than what I'm used to.  In general, assembly deals with single byte/word entities where the size depends on the processor.  I've done quite a bit of work on 8 and 16-bit processors, so that is where my answer is coming from.
General statements about Assembly:
Assembly is just like a high level language, except you have to handle a lot more of the details.  So if you're used to some operation in say C, you can start there and then break the operation down even further.
For instance, if you have declared two variables that you want to add, that's pretty easy in C:
x = a + b;

In assembly, you have to break that down further:
mov R1, a  * get value from a into register R1
mov R2, b  * get value from b into register R2
add R1,R2  * perform the addition (typically goes into a particular location I'll call it the accumulator
mov x, acc * store the result of the addition from the accumulator into x

Depending on the flavor of assembly and the processor, you may be able to directly refer to variables in the addition instruction, but like I said I would have to look at the specific flavor you're working with.
Comments on your specific question:
If you have a string of characters, then you would have to move each one individually using a loop of some sort.  I would set up a register to contain the starting address of your string, and then increment that register after each character is moved. It acts like a pointer in C.  You will need to have some sort of indication for the termination of the string or another value that tells the size of the string, so you know when to stop.


text:
Q: Eclipse and Apache Axis2 plugin Java Soap -- Class not found I have eclipse 3.5.1 installed along with the apache axis2 plug in...
I'm trying to generate my web service by going file -> new-> axis2 service archiver...
I go through the steps and select the bin directory of my project and when I get to the last step and type in the name of the class and click load it says "Error: Class not found"
I have tried about every combination of of paths etc. Not sure what to do next.
Seems like a huge headache trying to build a single soap service... any recommendations...
I was looking forward to only having to write the classes and running that to develop the SOAP service.

A: What exact class is missing?
And did you follow a guide like this one?
Initially I used Axis2 Codegen Wizard and Axis2 Service Archiver. Initially I got few error dialogs like java.lang.reflect.InvocationTargetException
 (not the same error, I know)

Though I found out way to fix it by adding few jars to the lib folder of the pluggin and modifying the pluggin.xml, it was not really useful as it just generate the required files and there was no possibility I could find to debus the services.

(the rest of the guide describe his development environment)
You also have this Guide in the same idea: "Writing Apache Axis 2 webservice using Tomcat and eclipse"


text:
Q: use HTML5 and CSS to create 5 equal and elastic columns that adjust height in a single row I'm fairly beginner with CSS and wish to make a HTML block from scratch on our Jive platform that is a single row of 5 buttons.  Each button will contain an icon and text with the entire button being a link.
I want the block to span 100% of the div it is in, and the buttons to adjust height and width depending on page width so that all 5 buttons are always on the same row until the screen width drops to below 600px and each button will fill a row each.
So far I have:

#newsnav-container {
  display: block;
  width: 100%;
  height: 100px;
  margin: 0 auto;
  background-color: beige;
}
#newsnav-container a {
  overflow: hidden;
  /*display:inline-block;
     height:100%;
     width:23%;
     margin:0 2% 0 0;*/
  background-color: #96C;
}
#newsnav-container a > div {
  padding: 15px;
  margin: 0 5px 0 0;
  background-color: #96C;
  float: left;
  width: 18.16%;
}
@media screen and (max-width: 600px) {
  #newsnav-container a > div {
    float: left;
    width: 100%;
    margin: 0 0 5px 0;
  }
}

  < <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">

1

2

3

4

5

The problem I have at the moment and can't get past is the 5th button won't stay up in the row with the others if the window is any smaller than full-screen on my 1920 res.

How do I fix this?
(Please excuse my lack of formatting and content - like I said I'm building from scratch and am using block colours to get my elements' responsiveness right first)

A: Method #01 (Preferred):
Use css3 flexbox:
#newsnav-container {
    display: flex;
}
#newsnav-container a {
    width: 19%;
}

#newsnav-container {
  width: 100%;
  height: 50px;
  margin: 0 auto;
  background-color: beige;
  display: flex;
}

#newsnav-container a {
  margin-right: 1%;
  width: 19%;
}
#newsnav-container a > div {
  padding: 15px;
  background-color: #96C;
}

@media screen and (max-width: 600px) {
  #newsnav-container {
    flex-direction: column;
  }
  #newsnav-container a {
    margin: 0 0 5px;
    width: 100%;
  }
}

1

2

3

4

5

Method #02:
Use display: table and display: table-cell propreties.
#newsnav-container {
    display: table;
    width: 100%;
}
#newsnav-container a {
    display: table-cell;
}

#newsnav-container {
  display: table;
  width: 100%;
  height: 50px;
  margin: 0 auto;
  background-color: beige;
}

#newsnav-container a {
  display: table-cell;
}
#newsnav-container a > div {
  padding: 15px;
  margin:0 5px 0 0;
  background-color:#96C;
}

@media screen and (max-width: 600px) {
  #newsnav-container {
    display: block;
  }
  #newsnav-container a {
    margin-bottom: 5px;
    display: block;
  }
}

1

2

3

4

5

A: There are two ways to solve this. One is with floating the parent a and making its box-sizing as border-box. The border-box property will count padding and border in its width.
Another way can be with display as table-cell

#newsnav-container {
  display: block;
  width: 100%;
  height: 100px;
  margin: 0 auto;
  background-color: beige;
  box-sizing: border-box;
}
#newsnav-container a {
  overflow: hidden;
  display: inline-block;
  box-sizing: border-box;
  width: 20%;
  float: left;
}
#newsnav-container a > div {
  padding: 15px;
  margin: 0 5px 0 0;
  background-color: #96C;
}
#newsnav-container a:last-child > div {
  margin-right: 0
}
/*
@media screen and (max-width: 600px) {
  #newsnav-container a > div {
    float: left;
    width: 100%;
    margin: 0 0 5px 0;
  }
}
*/
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">

1

2

3

4

5

A: The easiest way to solve this is using CSS Flexbox.
Apply display: flex; property to #newsnav-container and give flex: 1; to its childrens i.e. #newsnav-container a. Have a look at the code below for proper understanding.

#newsnav-container {
    display: flex;
}

#newsnav-container a {
    overflow: hidden;
    flex: 1;
    background-color:#96C;
}
#newsnav-container a > div {
  padding: 15px;
  margin:0 5px 0 0;
  background-color:#96C;
  float: left;
  width: 18.16%;
}

@media screen and (max-width: 600px) {
  #newsnav-container a > div {
    float: left;
    width: 100%;
    margin:0 0 5px 0;
  }
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">

1

2

3

4

5

Learn more about CSS Flexbox.
Hope this helps!


text:
Q: Kivy Character Counter from TextInput again! I'm trying to add a character counter to my TextInput widget, but I don't know what parameters to pass for the four arguments, or much on how they're supposed to function. I checked the documentation, but it was putting me further into the woods. Anyway, here are the relevant snippets.
def charsLeft(window, keycode, text, modifiers):
     # Do some magic, pass some parameters, and then...
     ansLen.text = str(len(hidden.text) - len(answer.text))

And here's the code for my layout:
ansLen = Label(bold=True, halign="center", size_hint=(.2, .5), text_size=self.size, valign="middle")
answer = TextInput(id="sbt", multiline=False, size_hint=(.8, .5), text="")
answer.bind(keyboard_on_key_down=charsLeft)

I figure since it's on virtually every website, it ought to be fairly straightforward. I just don't know what I don't know here.

A: if you want to set a text counter you do not need to use keyboard_on_key_down, you just need to catch the text change for them we use bind, then we can use a lambda function to update the values since the bind returns the instance and the property changed, to set the value we use setattr:
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout

class MyApp(App):
    def build(self):
        layout = BoxLayout(orientation='vertical')
        answer = TextInput(multiline=False, text="", size_hint=(1, 0.5))
        ansLen = Label(bold=True, halign="center", text="", size_hint=(1, 0.5))

        answer.bind(text=lambda instance, text: setattr(ansLen, "text", str(len(text))))
        layout.add_widget(answer)
        layout.add_widget(ansLen)
        return layout

if __name__ == '__main__':
    MyApp().run()


text:
Q: Ansible-Galaxy for private gitlab repo referencing only one role's files for all roles I am just diving into hosting custom made roles in a private gitlab git repository.
The answer to this may just be "you must have only 1 repo for 1 role," which I have not done. I have tried to put two roles in a repo and have just used folders to differentiate them at the top level.
I seem to have gotten the "requirements.yml" written correctly, as it pulled my roles. However it is putting all the files from 'nexus' into my skeleton role of 'chocolatey_factory'. The 'nexus' imported role comes across fine.
My requirements file is the following:
---
- src: git+ssh://git@[local_ip_address]/gitlab-instance-937dde58/my_first_project.git
  scm: git
  version: main
  name: nexus

- src: git+ssh://git@[local_ip_address]/gitlab-instance-937dde58/my_first_project.git
  scm: git
  version: main
  name: chocolatey_factory

Here is my repo layout. The idea is I would have each folder at the top level of the repo be a role. So in this case, I have two roles.
Top Level of Repo
nexus folder/role files
chocolatey_factory galaxy init folder
What am I doing wrong here?
One is 'nexus,' the other is 'chocolatey_factory'. Nexus is the public role available for configuring Sontaype nexus that I grabbed. Chocolatey_factory is one I am making, but it is just a ansible-galaxy init skeleton at this time:
I then run my ansible-galaxy command
ansible-galaxy install -r roles/requirements.yml -p roles/

It imports the roles. But the files from 'nexus' role appear in the 'chocolatey_factory' role.
The 'nexus' role has files like pom.xml, where the 'chocolatey_factory' does not have anything other than what ansible-galaxy init creates (ie it does not have a pom.xml file).
You can see here both folders have all the same files.
ls roles
chocolatey_factory  nexus  requirements.yml

ls roles/chocolatey_factory
chocolatey_factory  filter_plugins  molecule          tasks
CODE_OF_CONDUCT.md  handlers        pom.xml           templates
defaults            LICENSE.md      README.md         tests
files               meta            requirements.txt  vars

ls roles/nexus
chocolatey_factory  filter_plugins  molecule          tasks
CODE_OF_CONDUCT.md  handlers        pom.xml           templates
defaults            LICENSE.md      README.md         tests
files               meta            requirements.txt  vars

Why are my files from one role being inserted into the other? Can you not have two roles in the same git repository?


text:
Q: On number of shifted integer solutions to a linear system Let $M$ be a random diagonally dominant non-singular $3\times 3$ integer matrix
$$\begin{bmatrix}
m_{11}&m_{12}&m_{13}\\
m_{21}&m_{22}&m_{23}\\
m_{31}&m_{32}&m_{33}
\end{bmatrix}$$
where $|m_{ij}|<T^{8}$ and consider the equation
$$\begin{bmatrix}
m_{11}&m_{12}&m_{13}\\
m_{21}&m_{22}&m_{23}\\
m_{31}&m_{32}&m_{33}
\end{bmatrix}\begin{bmatrix}a\\b\\c\end{bmatrix}=\begin{bmatrix}
r_{1}+k_1p\\
r_{2}+k_2q\\
r_{3}+k_3r
\end{bmatrix}$$
where $p,q,r$ are distinct primes with size in $[T^9,2T^9]$ and $|r_1|<p,|r_2|<q$ and $|r_3|<r$ holds.
In above $m_{ij},r_i$ are fixed at every $i,j\in\{1,2,3\}$ and $p,q,r$ is fixed.
If $|a|,|b|,|c|<T^{3}$ and $|k_1|,|k_2|,|k_3|<T^{2}$ holds and we know there is an integer solution $(a,b,c,k_1,k_2,k_3)\in\mathbb Z^6$ to the above system.

How many additional solutions $(a,b,c,k_1,k_2,k_3)\in\mathbb Z^6$ with $|a|,|b|,|c|<T^{3}$ and $|k_1|,|k_2|,|k_3|<T^{2}$ can we expect?


text:
Q: Why does this program fail to copy files? this morning, my friend and I discussed and wrote the below code. The idea behind this Perl script is to create the directory structure and copy the files to the corresponding directory.
#!/usr/bin/perl
use File::Path;
use File::Copy;
use Path::Class;
use File::Basename qw/dirname/;
my $src = "/Vijay/new.txt";
unless (open(MYFILE, "file1")) {
    die ("cannot open input file file1\n");
}
$line = <MYFILE>;
while ($line ne "") {
    print ($line);
    mkdir_and_copy($src,$line);
    $line = <MYFILE>;
}
sub mkdir_and_copy {
    my ($from, $to) = @_;
    my($directory, $filename) = $to =~ m/(.*\/)(.*)$/;
    print("creating dir $directory");
    system "mkdir -p $directory";
    print("copying file $from to $to");
    system "cp -f $from $to";
    return;
}

The above piece of code creates the directory structure, but fails to copy the files to the corresponding directory. Could you please let us know, where exactly we are wrong?
Contents of file1:
test/test1/test2/test.txt

Contents of new.txt:
Shell/Test/test1/test1.txt
Shell/Test/test2/test2.txt
Shell/Test/test3/test3.txt

Output:
> ./mypgm.pl
test/test1/test2/test.txt
creating dir test/test1/test2/copying file /Vijay/new.txt to     test/test1/test2/test.txt
cp: cannot access /Vijay/new.txt: No such file or directory
>

The directory Vijay has the file new.txt with the above mentioned content.
Thanks in advance,
Vijay

Hello everyone,
I just modified my code. Please refer the below section of code.
#!/usr/bin/perl
use File::Path;
use File::Copy;
use File::Basename qw/dirname/;

my $src = "./Vijay/new.txt";
unless (open(MYFILE, "file1"))
{
die ("cannot open input file file1\n");
}

$line = ;
while ($line ne "")
{
print ($line); print("\n");
mkdir_and_copy($src,$line);
$line = ""; }

sub mkdir_and_copy
{
my ($from, $to) = @_;
my($directory, $filename) = $to =~ m/(.\/)(.)$/;
$temp = $directory.$filename;
print("Creating dirrectory $directory \n");
if(! -d $directory)
{
mkpath($directory) #or die "Failed to create path";
}
printf("From: $from \n");
printf("To: $temp \n");
copy($from,$temp) or die "Failed to Copy";
return;
}

Now, it creates the exact directory structure and copies the file to the corresponding directory. Could you please tell me that, whether the above code is a proper one?

A: Your goal is not clear to me, but perhaps this will help you solve the problem:
# Perl scripts should always include this.
# Your original script was generating some useful warnings.
use strict;
use warnings;

my $src = "/Vijay/new.txt";
my $f1  = 'file1';

# This is the recommended way to open a file --
# that is, using a lexical file handle.
open(my $file_handle, '<', $f1) or die "open() failed : $f1 : $!";

# This is the typical way of iterating over the lines in a file.
while (my $line = <$file_handle>){
    # You probably want to remove the newline
    # before passing the line to mkdir_and_copy()
    chomp $line;

    mkdir_and_copy($src, $line);
}

sub mkdir_and_copy {
    my ($from, $to) = @_;
    my ($directory, $filename) = $to =~ m/(.*\/)(.*)$/;

    # When writing a script that makes system() calls,
    # start by simply printing them. After everything
    # looks good, convert the print commands to system() calls.
    print "system(): mkdir -p $directory", "\n";
    print "system(): cp -f $from $to",     "\n";

    # The return is not needed.
}

When I run the script with the inputs you provided, here's the output:
system(): mkdir -p test/test1/test2/
system(): cp -f /Vijay/new.txt test/test1/test2/test.txt

This can't be your intent. In particular, why are you iterating over file1 when it contains only one line? Perhaps you meant to iterate over new.txt?

A: The first thing to do if something "does't work" is to catch errors and to look at them. Then to investigate content of variables. In your case the variable $to just contains the file name, so the script copies it into the current working directory, I'd imagine, not into the newly created directory.
HOWEVER, the methods you're using to get your job done are not exactly the best. It would be better to actually use File::Path and File::Copy, and in particular your way of splitting a path into directory and filename at the first slash is anything but general. This sort of thing should be done in libraries, of which Perl has many.

A: I'll bet your $line variable still has a newline appended to it. The input returned from the filehandle input operator (<MYFILE>) includes the record separator (usually the newline character(s) for your OS). Try this:
$line = <MYFILE>;
chomp($line);


text:
Q: node.js formidable make variable with uploaded file URL Hi Im using node and formidable to submit a file in a form, this file's URL I need to save in a global variable to later use it with WATSON IBM image recognition api.
I'm new with node so I'm stuck, the variable name is newpath, I'm able to print it after the form is submitted, but can't access the variable later.
I must be doing something wrong, I really appreciate if you can point me out my mistake.
const http = require('http');
var formidable = require('formidable');

const hostname = '127.0.0.1';
const port = 3500;

var fs = require('fs');

/// WATSON

var VisualRecognitionV3 = require('watson-developer-cloud/visual-recognition/v3');
var visualRecognition = new VisualRecognitionV3({
  version: '2018-03-19',
  iam_apikey: 'xxxxxxx'
});

// SERVER AND FORM

const server = http.createServer((req, res) => {

  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = '/users/myuser/coding/visualr/' + files.filetoupload.name;

      fs.rename(oldpath, newpath, function (err) {
        if (err) throw err;
        res.write('File uploaded and moved!');
        // this is the path, variable newpath, but can't be accessed
        // outside this function, tried to make it global but didn't work either

        res.write('newpath');
        res.end();
      });

 });

  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload">
');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
  }
  });

 var images_file = fs.createReadStream(newpath);
// I want to put the variable newpath in this function: but it doesn't work...

var params = {
  images_file: images_file,
};

visualRecognition.classify(params, function(err, response) {
  if (err)
    console.log(err);
  else
    console.log(JSON.stringify(response, null, 2))
});

// ENDS

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

A: The variable is defined within the context of the if (req.url == '/fileupload') {...} block, so it won't be available outside of that block.
To use the variable everywhere in the code, define it outside of the createServer block:
var newpath; // this variable will have global context for this file

const server = http.createServer((req, res) => {

  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.path;

      // set the variable to its intended value here
      newpath = '/users/myuser/coding/visualr/' + files.filetoupload.name;

      fs.rename(oldpath, newpath, function (err) {
        if (err) throw err;
        res.write('File uploaded and moved!');
        res.write('newpath');
        res.end();
      });
    });
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
    res.write('<input type="file" name="filetoupload">
');
    res.write('<input type="submit">');
    res.write('</form>');
    return res.end();
  }
});

console.log(newpath); // the variable should be available here, because of its context


text:
Q: how to prevent drools engine looping on entry point data I'm using drools to raise alarm on streaming transaction data.
The drools engine is STREAM and ACTIVE mode. I also use an entry point (OM-TRANS) to transmit data to the rule engine.
I have written a simple rule to test the behaviour of the engine. I got some results but i don't understand them and their are not what i expect.
This is the first simple rule:
rule "My rule"
    no-loop true
    when
        $transaction: TransactionOmDto($msisdn: msisdn) from entry-point "OM-TRANS"
    then
        System.out.println("------------ an alarm on "+$msisdn+" ----------");
    end

These are the results i got after testing:

*

*transaction from msisdn msisdn_1:

------------ an alarm on msisdn_1 ----------

*transaction from msisdn msisdn_1 again:

------------ an alarm on msisdn_1 ----------

*transaction from msisdn msisdn_2:

------------ an alarm on msisdn_2 ----------

*transaction from msisdn msisdn_2 again:

------------ an alarm on msisdn_2 ----------

*transaction from msisdn msisdn_3:

------------ an alarm on msisdn_3 ----------
This is now the second version of the rule:
rule "My rule"
    no-loop true
    when
        $transaction: TransactionOmDto($msisdn: msisdn) from entry-point "OM-TRANS"
        $datasTransaction: List() from collect(TransactionOmDto(msisdn == $msisdn) from entry-point "OM-TRANS")
    then
        System.out.println("------------ an alarm on "+$msisdn+", total Transaction: "+$datasTransaction.size()+" ----------");
    end

and i got the following results and what i expect:

*

*transaction from msisdn msisdn_1:

------------ an alarm on msisdn_1, total Transaction: 1 ----------
(this is the one expected)

*transaction from msisdn msisdn_1 again:

------------ an alarm on msisdn_1, total Transaction: 2 ----------
------------ an alarm on msisdn_1, total Transaction: 2 ----------

What i expected is : A sigle row ------------ an alarm on msisdn_1, total Transaction: 2 ----------

*transaction from msisdn msisdn_2:

------------ an alarm on msisdn_2, total Transaction: 1 ---------- (as expected)

*transaction from msisdn msisdn_2 again:

------------ an alarm on msisdn_2, total Transaction: 2 ----------
------------ an alarm on msisdn_2, total Transaction: 2 ----------

What i expected is : A sigle row ------------ an alarm on msisdn_2, total Transaction: 2 ----------

*transaction from msisdn msisdn_3:

------------ an alarm on msisdn_3, total Transaction: 1 ----------
(this is the one expected)

*transaction from msisdn msisdn_3 again:

------------ an alarm on msisdn_3, total Transaction: 2 ----------
------------ an alarm on msisdn_3, total Transaction: 2 ----------

What i expected is : A sigle row ------------ an alarm on msisdn_3, total Transaction: 2 ----------

*transaction from msisdn msisdn_3 again:

------------ an alarm on msisdn_3, total Transaction: 3 ----------
------------ an alarm on msisdn_3, total Transaction: 3 ----------
------------ an alarm on msisdn_3, total Transaction: 3 ----------

What i expected is : A sigle row ------------ an alarm on msisdn_3, total Transaction: 3 ----------
Can someone explain to me why i got those result?
Is it possible to get what i expect ?
Thanks you.

A: Because your events expire only in 24h, older ones do participate in the rule logic.
Usually this can be fixed with sliding length window
 over window:length(1) from entry-point "OM-TRANS"

full snippet
rule "My rule2"
no-loop true
when
    $transaction: TransactionOmDto($msisdn: msisdn) over window:length(1) from entry-point "OM-TRANS"
    $datasTransaction: List() from collect(TransactionOmDto(msisdn == $msisdn) from entry-point "OM-TRANS")
then
    System.out.println("------------ an alarm on "+$msisdn+", total Transaction: "+$datasTransaction.size()+" ----------");
end

output
------------ an alarm on msisdn_1, total Transaction: 1 ----------
------------ an alarm on msisdn_1, total Transaction: 2 ----------
------------ an alarm on msisdn_1, total Transaction: 3 ----------


text:
Q: Recursive query on Windows Server automation? We have a bunch of 2008-2012 HyperV hosts who have Windows Server domain controllers (2008 DC level, 2008 and 2012 servers across different unrelated sites). Occasionally, when the DC guest comes up after a host reboot after updates, clients call us the site doesn't have internet (Intranet works, external does not). In the DNS manager, I click Properties of the DNS server (the DC), click Monitoring, and run Simple and Recursive query test. Simple always passes, recursive always fails. We restart the DNS Server service and then everything passes.
The servers are configured to use the ISP DNS (ie. 75.75.75.75, 76.76.76.76) as forwarders.
The issue is, we're an MSP. We should know the site doesn't have internet before they do. We should be able to call them and say what is happening before they call us. We're using Kaseya and have the ability to set up monitoring sets and what not, so that's the tool we have to use. DNS is one of those things I don't touch too often so my knowledge may be a bit rusty.
My ideas have been checking the perf monitor (DNS sets) for failures while DNS Server is turned OFF, which did not give me meaningful results. I've been trying to figure out where the results for "Perform Automatic testing at the following interval" is located since I could just check that for failures, but I have no idea where it is. Another idea is to do 'nslookup 127.0.0.1 ' which results in a failure, but I don't know if that will help me.
I am looking for something a bit more in depth than clearing cache and pinging a website. Something more robust I can deploy to 50 sites. Any ideas?


text:
Q: Spring integration flow vs regular service and adapter I had some legacy code that had SOAP services. Now I am building Rest API for some objects that may call one or more SOAP operation. I was looking into Spring Integration. From the docs

In addition to wiring together fine-grained components, Spring Integration provides a wide selection of channel adapters and gateways to communicate with external systems.

Above statement sounds enticing. I was writing rest microservice controller, Validation service, Rest request to SOAP request mapper and SOAP client. I some cases when there are multiple calls, there is even more code I had to write and I did write the code in many cases.
Spring Integration at high level looked like a framework oriented for Async messages. My problem is that the call need to be more or less a synchronous call and performance is critical. Had anyone used Spring integration for this problem and can you share your experiences.

A: To complement Artem's answer it's worth to note that if you're going to use one of Spring Integration DSLs (Java, Groovy or Scala) then (the synchronous) DirectChannel will be picked by default by Spring Integration to wire up the endpoints of your integration flow. This means that as long as your endpoints stay synchronous and you rely on default channels between them, the whole integration flow stay synchronous as well.
For instance (in Java DSL):
  @Bean
  public IntegrationFlow syncFlow() {
    return IntegrationFlows
        .from(/* get a REST message from microservice */)
        // here the DirectChannel is used by default
        .filter(/* validate (and filter out) incorrect messages */)
        // here the DirectChannel is used by default too
        .transform(/* map REST to SOAP */)
        // guess what would be here?
        .handle(/* send a message with SOAP client */)
        .get();
  }

This absolutely doesn't mean you tied up with synchronous flow forever. At any step you can go async or parallel. For example, if you decide to send SOAP messages in parallel all you need to do is to specify appropriate channel before SOAP client invocation:
  @Bean
  public IntegrationFlow syncFlow() {
        // ... the same as above ...
        .transform(/* map REST to SOAP */)
        .channel(c -> c.executor(Executors.newCachedThreadPool()))  // see (1)
        .handle(/* send a message with SOAP client */)
        .get();
  }

(1) From this point on the downstream flow will be processed in parallel thanks to use of ExecutorChannel.
Note that message endpoints may also behave asynchronously depending on their logic.
I've used Spring Integration for building synchronous integration flows in my home and work projects and it's proven to be a very powerful yet flexible solution.

A: One of the first class citizens in Spring Integration is MessageChannel abstraction. The simplest, synchronous, and therefore direct method invocation is DirectChannel.
Not sure what makes you think that everything in Spring Integration is async. Actually it is always direct unless you tell to be async.