text:
Q: When to use 'componentDidUpdate' method? I wrote dozens of Reactjs files, but I never used the componentDidUpdate method.
Is there any typical example of when need to use this method?
I want a real-world example, not a simple demo.

A: Sometimes you might add a state value from props in constructor or componentDidMount, you might need to call setState when the props changed but the component has already mounted so componentDidMount will not execute and neither will constructor; in this particular case, you can use componentDidUpdate since the props have changed, you can call setState in componentDidUpdate with new props.

A: This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes.
You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from previous state. Incorrect usage of setState() can lead to an infinite loop.
Take a look at the example below that shows a typical usage example of this lifecycle method.
componentDidUpdate(prevProps) {
 //Typical usage, don't forget to compare the props
 if (this.props.userName !== prevProps.userName) {
   this.fetchData(this.props.userName);
 }
}

Notice in the above example that we are comparing the current props to the previous props. This is to check if there has been a change in props from what it currently is. In this case, there won't be a need to make the API call if the props did not change.
For more info, refer to the  official docs:

A: componentDidUpdate(prevProps){

    if (this.state.authToken==null&&prevProps.authToken==null) {
      AccountKit.getCurrentAccessToken()
      .then(token => {
        if (token) {
          AccountKit.getCurrentAccount().then(account => {
            this.setState({
              authToken: token,
              loggedAccount: account
            });
          });
        } else {
          console.log("No user account logged");
        }
      })
      .catch(e => console.log("Failed to get current access token", e));

    }
}

A: I have used componentDidUpdate() in highchart.
Here is a simple example of this component.
import React, { PropTypes, Component } from 'react';
window.Highcharts = require('highcharts');

export default class Chartline extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      chart: ''
    };
  }

  public componentDidUpdate() {
    // console.log(this.props.candidate, 'this.props.candidate')
    if (this.props.category) {
      const category = this.props.category ? this.props.category : {};
      console.log('category', category);
      window.Highcharts.chart('jobcontainer_' + category._id, {
        title: {
          text: ''
        },
        plotOptions: {
          series: {
            cursor: 'pointer'
          }
        },
        chart: {
          defaultSeriesType: 'spline'
        },
        xAxis: {
          // categories: candidate.dateArr,
          categories: ['Day1', 'Day2', 'Day3', 'Day4', 'Day5', 'Day6', 'Day7'],
          showEmpty: true
        },
        labels: {
          style: {
            color: 'white',
            fontSize: '25px',
            fontFamily: 'SF UI Text'
          }
        },
        series: [
          {
            name: 'Low',
            color: '#9B260A',
            data: category.lowcount
          },
          {
            name: 'High',
            color: '#0E5AAB',
            data: category.highcount
          },
          {
            name: 'Average',
            color: '#12B499',
            data: category.averagecount
          }
        ]
      });
    }
  }
  public render() {
    const category = this.props.category ? this.props.category : {};
    console.log('render category', category);
    return <div id={'jobcontainer_' + category._id} style={{ maxWidth: '400px', height: '180px' }} />;
  }
}

A: When something in the state has changed and you need to call a side effect (like a request to api - get, put, post, delete). So you need to call componentDidUpdate() because componentDidMount() is already called.
After calling side effect in componentDidUpdate(), you can set the state to new value based on the response data in the then((response) => this.setState({newValue: "here"})).
Please make sure that you need to check prevProps or prevState to avoid infinite loop because when setting state to a new value, the componentDidUpdate() will call again.
There are 2 places to call a side effect for best practice - componentDidMount() and componentDidUpdate()

A: A simple example would be an app that collects input data from the user and then uses Ajax to upload said data to a database. Here's a simplified example (haven't run it - may have syntax errors):
export default class Task extends React.Component {

  constructor(props, context) {
    super(props, context);
    this.state = {
      name: "",
      age: "",
      country: ""
    };
  }

  componentDidUpdate() {
    this._commitAutoSave();
  }

  _changeName = (e) => {
    this.setState({name: e.target.value});
  }

  _changeAge = (e) => {
    this.setState({age: e.target.value});
  }

  _changeCountry = (e) => {
    this.setState({country: e.target.value});
  }

  _commitAutoSave = () => {
    Ajax.postJSON('/someAPI/json/autosave', {
      name: this.state.name,
      age: this.state.age,
      country: this.state.country
    });
  }

  render() {
    let {name, age, country} = this.state;
    return (
      <form>
        <input type="text" value={name} onChange={this._changeName} />
        <input type="text" value={age} onChange={this._changeAge} />
        <input type="text" value={country} onChange={this._changeCountry} />
      </form>
    );
  }
}

So whenever the component has a state change it will autosave the data. There are other ways to implement it too. The componentDidUpdate is particularly useful when an operation needs to happen after the DOM is updated and the update queue is emptied. It's probably most useful on complex renders and state or DOM changes or when you need something to be the absolutely last thing to be executed.
The example above is rather simple though, but probably proves the point. An improvement could be to limit the amount of times the autosave can execute (e.g max every 10 seconds) because right now it will run on every key-stroke.
I made a demo on this fiddle as well to demonstrate.

For more info, refer to the official docs:

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

A: @K.tin, if you call setState in componentDidUpdate(), would that cause the same data to be fetched again?
For example, [id, data_for_id] are states, and id can be changed by a click counter and data_for_id is fetched from a web API.
Now we click to change Id by setState(), and componentDidUpdate() is executed, which fetches the data_for_id, we do setState for data_for_id, which will trigger another componentDidUpdate().
The first time componentDidUpdate is called, we have prevState.ID = 0 and state.ID=1, so componentDidUpdate is run. The second time we have prevState.ID = 1 and state.ID = 1, and componentDidUpdate can be avoid entirely, which perhaps could also be implemented with shouldComponentUpdate().
Still, this causes TWO rerenders, one for ID change and one for data_for_id change, Ideally, once we detect ID change, data_for_id should be fetched, and we should have [Id, data_for_id] state changed in a single shot, and the rerender happens only once for this change ID click.
So as a general rule, we should not do any setState in componentDidUpdate(), if the change of two or more state components are related, we should perform the changes together in one place and setState in a single shot.
This is just my reasoning. I am not a react guru, so please comment.

A: You should be careful when it's used. because it's making multiple API calls. Sometimes unlimited calls

A: componentDidUpdate should not have setState inside of it. you should use componentDidUpdate specially in manipulating the dom base on this.state values. CRUD or updating state values is not good inside of componentDidUpdate. Also dont fetching new data inside of componentDidUpdate as is can cause multiple http request on server and sometimes can cause laggy specially when the code is not structural or multiple use of setState.


text:
Q: JavaScript : How to detect if a node has been removed? I think the best way to describe my question is to create some image objects in such a matter:

In my JavaScript I could have the following:
$('.image').each(function( index, element ){
    var image = new Image(); //NEW INSTANCE(S) CREATED (IN MEMORY)
    image.src = $(this).attr('data-src');
    $(this).parent().append(image);
});

Keep in mind this is an example in my real script new Image() is a custom object.
This script is done automatically so where ever I put

 an image will be created. Now some programmer uses this scripts and imports it and creates his own script with the following code:
$('#image_collection').remove(); //OR
$('#image_collection').html('Some new content');

Now my script fires first and it will convert all images, creating new instances, but when the programmer removes the nodes within image_collection, my believe is those image instances will still remain in memory. How can I remove those image instances once they are not used in the DOM anymore?

A: The .remove() function removes nodes from the DOM and returns them. If you're not doing anything with the return value, they get cleaned up eventually.

A: If you are really worried about memory you can  put those images in a global image (or your custom object) array instead of putting it in a local variable.
Take a global variable
var image_cleaned=false;
Use timer  (i.e. setTimeOut ) to check if the din contains img tag with class image.
If it does not find any matching element (and image_cleaned is false ) then delete that array. Then set image_cleaned=true; . Then remove timer (optional but better).

A: The Image() object is destroyed when the scope of $(.image).each() ends: actually, the 'image' var is created in that scope and it cannot survive after the .each() end.
So far, you have only the DOM node but it's removed by .remove().
You can feel comfortable :P

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding git repositories to python 3 interpreter
I am working with Ubuntu 14.4 Trusty Tahr LTS on EC2. I want to use the Python 3.4.0 interpreter which is installed by default. I want to be able to be able to add git repositories to be accessed by python3.4.
I previously ran:
~$ sudo apt-get -y install git-core

but this appears to associate git repos with python2.7 How can I associate them with python3.4?

A: There is a python library used to interact with Git repositories
It can be used in Fetching Remote Git Repo with Python, e.g..
There's also the old fashioned way
cd /path/to/git/repo
python3 my_favorite.py

But I think you will find Git to be Python version independent, and that possibly you want to associate Python code, files and extensions with Python 3.4 rather than 2.7, and that would be via mime.types
How is it determined which application is to open a file of specific mime-type?
How to change the default application for a given type of file in Ubuntu Linux
For example, I use Idlex as an IDE.  I've added text/x-python=idlex3.desktop to the ~/.local/share/applications/mimeapps.list file.  Now, double clicking on a Python file opens that file in the IDE to be looked at, edited, and/or run.


text:
Q: Reset or change slides array of jQuery plugin I'm using the supersized plugin for jQuery to show fullsize background pictures. I want to change the array with the images (with jquery.click()), but without reloading the page. The link loads the content into a div via AJAX, and at the same time I want to switch the array.
This is the default code I load for supersized:
$.supersized({
    random: 1,
    image_protect: 0,
    slide_interval: 5000,
    transition: 1,
    transition_speed: 3000,
    vertical_center: 0,
    horizontal_center: 0,
    fit_portrait: 1,
    slides:
    [
        {image : 'imgs/bg-01.jpg'},
        {image : 'imgs/bg-02.jpg'},
        {image : 'imgs/bg-03.jpg'},
    ]
});

This is what I've done to change the array:
$('#link1').click(function() {
    // placeholder for ajax load

    $.supersized({
        random: 1,
        image_protect: 0,
        slide_interval: 5000,
        transition: 1,
        transition_speed: 3000,
        vertical_center: 0,
        horizontal_center: 0,
        fit_portrait: 1,
        slides:
        [
            {image : 'other-imgs/new-bg-01.jpg'},
            {image : 'other-imgs/new-bg-02.jpg'}
        ]
    });
});

but this only adds the 2 new images to the other 3. How can I clear the first array and/or replace the content of it?

A: UPDATED
Here's what I do to reload Supersized with dynamic slides and to prevent it from going batshit  crazy with the new slides (i had mine jump randomly from a slide to another speeding up)
create a function in your main JS file that will be called to update the slides :
function start_supersized(slides) {
    $('#supersized-loader').empty().remove();
    $('#supersized').empty().remove();
    $('#hzDownscaled').empty().remove();
    $('body').append('

');
    $.supersized({slides: slides}); // add your other SZ options here
};

all we're doing here is emptying and removing the DOM elements that SZ appends to the body of our document, and initializing the plugin again.
Then we can call this function with a slides array as an argument, ie:
var new_slides = [{image: "/img/slide1.png"}, {image: "/img/slide2.png"}];
start_supersized(new_slides);

That's not all though. We need to tweak a couple of lines inside the supersized JS file (yeah it's a hack, but the plugin authors won't get back to me)
In the un-minified version of the script, version 3.2.7 you'll have to:
1) remove the very first lines, where this happens (lines 17 / 20 or so)
    $(document).ready(function() {
        $('body').append('

');
    });

update
2) add
    var slideshow_intervals = [];
this array will keep track of all the interval id's the plugin will create
3) locate the function
    base._start = function() {

(around line 124) and add to the top of the function this line :
jQuery.each(slideshow_intervals, function(i, e) {
 clearInterval(e);
});

4) wherever there's a setInterval() call, add the returned value to our array, like so:
slideshow_intervals.push(vars.slideshow_interval);

All this is used to reset the supersized animation intervals and prevents the script to start speeding up between a frame and the other. I know it's kinda hacky, but hey.

A: To stop supersized 3.2.7 from speeding up on re-initialize dynamic slideshows. I made this changes in the uncompressed javascript file:
search for "base._start" function (around row 116)
paste:
    clearInterval(vars.slideshow_interval);
in the top of the base._start function to clear all previous initialized intervals.
that should do it.

A: Before call again the supersized script I reset HTML content with:
jQuery("#thumb-list").remove();
jQuery("#supersized").html('');

And it works form me.


text:
Q: Apache/PHP cache headers problem <?php
    chdir('../../../../');
    include('bootstrap.php');

    $place = isset($_GET['place'])  ?   (is_array($_GET['place']))   ?   intval($_GET['place'][0]) :   intval($_GET['place'])      : null;

    $query = mysql_query("SELECT `place`, `image`, `imagetype` FROM `topvideo` WHERE `place` = '" . $place . "'");
    if (mysql_num_rows($query))
    {
        while ($row = mysql_fetch_array($query))
        {
            $im = imagecreatefromstring($row['image']);
            if ($im !== false)
            {
                header('Cache-Control: public, proxy-revalidate');
                header('Last-Modified:Mon, 02 Nov 2009 09:50:18 GMT');
                header('Expires: ' . gmdate ("D, d M Y H:i:s", time() + 60 * 60 * 24 * 24 . ' GMT');

                header('Content-Type: image/jpeg');
                imagejpeg($im);
                imagedestroy($im);
            }
        }
    }

The response is always  200, but I need to cache the image for 2 days and the response was 304.... why?
sorry for bad english

A: to send 304 You need to include Etag in your response headers, etag is something like hash of content itself and date of it's creation.
After you include etag in response the browser will send you request header "If-None-Match".
You have to compare this headers and if they match respond with 304, if not send new content with new Etag header and status 200.


text:
Q: What's the httpd_module name so that Apache/Httpd works with PHP 5.5? I've been having some issues installing PHP 5.5 on a CentOS machine using Chef. I was finally able to install it, but when I access the index.php it just download a file with the content.
I'm guessing it's because Apache (technically Httpd, as I'm with CentOS) doesn't have mod_php installed/configured.
I installed PHP using php cookbook with the following packages:
# ... code to add webtatic repository to yum

node.set['php']['packages'] = ['php55w', 'php55w-devel', 'php55w-cli', 'php55w-snmp', 'php55w-soap', 'php55w-xml', 'php55w-xmlrpc', 'php55w-process', 'php55w-mysqlnd', 'php55w-pecl-memcache', 'php55w-opcache', 'php55w-pdo', 'php55w-imap', 'php55w-mbstring']

If I'm right, the code above didn't install mod_php. The following is my web chef recipe:
httpd_service 'apps' do
    mpm 'prefork'
    action [:create, :start]
    listen_ports ['80', '443']
end

# ... code for virtual hosts

# Install the mod_php Apache module.
# httpd_module 'php' do
#    instance 'apps'
# end

I had the httpd_module 'php' directive uncommented when using PHP 5.4. What's the correct name for the http_module to work with PHP 5.5?

A: It looks like you've found one of the people who went the Debian route and set their packages up as php55- instead of php-. That makes things a pain if you want to go from 5.5 to any higher version, because you're having to uninstall those and install the new ones (i.e. php70-).
Instead I recommend switching your recipe to the Remi repo and use the php- packages.
All that having been said, php55w is your base PHP package. I don't see a php55w-common package tho. Try adding that (or php-common) and that should get it into Apache.


text:
Q: Equation of sphere through points $(1,1,2)$ and $(2,-2,3)$ with center on $2x+3y=0=5x+y-z$ I'm having trouble finding the values of $u$, $v$ and $w$ through solving the equations by substituting the given points in $x^2+y^2+z^2+2ux+2vy+2wz+d=0$.
The answer given is $2(x^2+y^2+z^2)- 3x + 2y -13z + 15 = 0$ and my answer is nowhere close.
Edit: Perhaps it may be either the equation is wrong or the answer is. I believe it more likely to be an incorrect answer.

A: First find the line of intersection between
$2 x + 3y = 0$
$5x + y - z = 0 $
The point $(0,0,0)$ is an obvious solution.
The direction vector of the line is
$V = (2, 3, 0) \times (5, 1, -1) = (-3, 2, -13) $
So the line is $\ell(t) = t (-3, 2, -13)$
So now have
$ R^2 = (1 + 3 t)^2 + (1 - 2 t)^2 + (2 + 13 t)^2 = (2 + 3 t)^2 + (-2 - 2 t)^2 + (3 + 13 t)^2$
Therefore,
$1^2 + 1^2 + 2^2 + t (6 - 4 + 52) = 2^2 + (-2)^2 + 3^2 + t (12 + 8 + 78)$
So that
$ t (44) = - 11 $
and $ t = -\dfrac{1}{4} $
Therefore, the center is
$ C = -\dfrac{1}{4} (-3, 2, -13) = ( \dfrac{3}{4}, - \dfrac{1}{2} , \dfrac{13}{4} ) $
and
$ R^2 = (\dfrac{1}{4})^2 + (\dfrac{3}{2})^2 + (\dfrac{5}{4})^2 = \dfrac{62}{16} $
And the equation of the sphere is
$ (x - \dfrac{3}{4})^2 + (y + \dfrac{1}{2} )^2 + ( z - \dfrac{13}{4})^2 = \dfrac{62}{16} $
Multiplying through by $16$
$ (4 x - 3 )^2 + (4 y + 2 )^2 + (4 z - 13)^2 = 62 $
Expanding
$ 16 (x^2 + y^2 + z^2) - 24 x + 16 y - 104 z + 9 + 4 + 169 = 62 $
And finally,
$ 16 x^2 + 16 y^2 + 16 z^2 - 24 x + 16 y - 104 z + 120 = 0 $
Dividing through by $8$
$ 2 x^2 + 2 y^2 + 2 z^2 - 3 x + 2 y - 13z + 15 = 0 $


text:
Q: ITfoxtec.Identity.Saml2.Saml2RequestException: 'There is not exactly one Assertion element.' Good day,
We used ITfoxtec library version 1.2.2. This solution worked correctly.
We are now integrating the version 4.0.5 library. We need to use SHA-256 encoding. We used the 4.0.5 library from Nugets. According to the implementation example https://github.com/ITfoxtec/ITfoxtec.Identity.Saml2.
The SAML request was sent successfully. Arrived SAML response. Exception is throw on the method AssertionConsumerService() in line binding.ReadSamlResponse(Request.ToGenericHttpRequest(), saml2AuthnResponse);.
Throw exception: ITfoxtec.Identity.Saml2.Saml2RequestException: 'There is not exactly one Assertion element.'
This is my SAML response:
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
                xmlns:dsig="http://www.w3.org/2000/09/xmldsig#"
                xmlns:enc="http://www.w3.org/2001/04/xmlenc#"
                xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
                xmlns:x500="urn:oasis:names:tc:SAML:2.0:profiles:attribute:X500"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                Destination="https://xxx/saml/post/ac"
                ID="id-cefHM2F1RpCggtiERcLI-Z5AwyqM43zoVhtjSan0"
                InResponseTo="_99a2e207-8b49-46ab-85a8-7448f32b34e9"
                IssueInstant="2020-07-14T11:03:49Z"
                Version="2.0"
                >
    <saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://yyy/oam/fed</saml:Issuer>
    <dsig:Signature>
        <dsig:SignedInfo>
            <dsig:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
            <dsig:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
            <dsig:Reference URI="#id-cefHM2F1RpCggtiERcLI-Z5AwyqM43zoVhtjSan0">
                <dsig:Transforms>
                    <dsig:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                    <dsig:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
                </dsig:Transforms>
                <dsig:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
                <dsig:DigestValue>/pQoLtuBTH/YNe4OKD4V6+qc2Rxf+na6pa8HonSRNeY=</dsig:DigestValue>
            </dsig:Reference>
        </dsig:SignedInfo>
        <dsig:SignatureValue>WW5g8Kzh3XMvohJKsYKebvO...</dsig:SignatureValue>
        <dsig:KeyInfo>
            <dsig:X509Data>
                <dsig:X509Certificate>MIIDUTCCAjmgAwIBAgIKTAxTewAAAAA...</dsig:X509Certificate>
            </dsig:X509Data>
        </dsig:KeyInfo>
    </dsig:Signature>
    <samlp:Status>
        <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
    </samlp:Status>
    <saml20:EncryptedAssertion xmlns:saml20="urn:oasis:names:tc:SAML:2.0:assertion">
        <xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"
                            Id="id-a7DCb68sppndtm1EJHGc7tGXeaybYZqovq6DSXUP"
                            Type="http://www.w3.org/2001/04/xmlenc#Element"
                            >
            <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" />
            <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
                <dsig:RetrievalMethod Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey"
                                      URI="#id-OlT01t8FNBO2pIuB8ba-IlZ10dYXJEIgkMyiSOiZ"
                                      />
            </KeyInfo>
            <xenc:CipherData>
                <xenc:CipherValue>WNCrzgQXVzhAJ61coe4qClUi8hyZVUQ8Z...</xenc:CipherValue>
            </xenc:CipherData>
        </xenc:EncryptedData>
        <xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"
                           Id="id-OlT01t8FNBO2pIuB8ba-IlZ10dYXJEIgkMyiSOiZ"
                           >
            <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
            <dsig:KeyInfo>
                <dsig:X509Data>
                    <dsig:X509Certificate>MIIDNDCCAhygAwIBAgIQhNtIL...</dsig:X509Certificate>
                </dsig:X509Data>
            </dsig:KeyInfo>
            <xenc:CipherData>
                <xenc:CipherValue>R5usMrow6yS8ulpX0HApH/ExWk...</xenc:CipherValue>
            </xenc:CipherData>
            <xenc:ReferenceList>
                <xenc:DataReference URI="#id-a7DCb68sppndtm1EJHGc7tGXeaybYZqovq6DSXUP" />
            </xenc:ReferenceList>
        </xenc:EncryptedKey>
    </saml20:EncryptedAssertion>
</samlp:Response>

This SAML response is not correct SAML? Using library 1.2.2, the same SAML response was accepted. Why is it not accepted when using the 4.0.5 library?
Please help. Well thank you. DM

A: Generally the new ITfoxtec Identity SAML library is much more restrictive and secure then the old library.
The decrypted SAML Authn Response looks correct.
To troubleshoot:

*

*Is the decryption certificate configured in config.DecryptionCertificate with the private key?

*After the Exception, is the binding.XmlDocument.OuterXml in the AuthController.AssertionConsumerService method then decrypted?

If the the XML in the binding.XmlDocument.OuterXml should be decrypted at the point where the exceptions is thrown, otherwise there the problem is in relation to decryption.

A: This is decrypted SAML from SAML Tracker tool:
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:enc="http://www.w3.org/2001/04/xmlenc#" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:x500="urn:oasis:names:tc:SAML:2.0:profiles:attribute:X500" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Destination="https://zzz/saml/post/ac" ID="id-0v6rnx86H21iac3g666IWswoc2QDD-ECzGZ6FQNo" InResponseTo="_705c6a70-d335-496b-aa00-1f09760f5d6e" IssueInstant="2020-07-17T05:18:02Z" Version="2.0">
    <saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://yyy/oam/fed</saml:Issuer>
    <dsig:Signature>
        <dsig:SignedInfo>
            <dsig:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
            <dsig:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
            <dsig:Reference URI="#id-0v6rnx86H21iac3g666IWswoc2QDD-ECzGZ6FQNo">
                <dsig:Transforms>
                    <dsig:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                    <dsig:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                </dsig:Transforms>
                <dsig:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                <dsig:DigestValue>TJSWg8IdPf2dm3mmI7sllXWjPq3kmW7FjwWtMdr256I=</dsig:DigestValue>
            </dsig:Reference>
        </dsig:SignedInfo>
        <dsig:SignatureValue>i3cOo...</dsig:SignatureValue>
        <dsig:KeyInfo>
            <dsig:X509Data>
                <dsig:X509Certificate>MIIDUTCCA...</dsig:X509Certificate>
            </dsig:X509Data>
        </dsig:KeyInfo>
    </dsig:Signature>
    <samlp:Status>
        <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
    </samlp:Status>
    <saml:Assertion ID="id-AVyUEGJACHdCqUGL4k1EzdEHhnPbwp31S44hFIwI" IssueInstant="2020-07-17T05:18:02Z" Version="2.0">
        <saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://yyy/oam/fed</saml:Issuer>
        <dsig:Signature>
            <dsig:SignedInfo>
                <dsig:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                <dsig:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
                <dsig:Reference URI="#id-AVyUEGJACHdCqUGL4k1EzdEHhnPbwp31S44hFIwI">
                    <dsig:Transforms>
                        <dsig:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                        <dsig:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                    </dsig:Transforms>
                    <dsig:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                    <dsig:DigestValue>53ThYIAb6b/K79YvgKijhlb+TE5OPJVUtHDjKrnp4Gc=</dsig:DigestValue>
                </dsig:Reference>
            </dsig:SignedInfo>
            <dsig:SignatureValue>EWGE0k4...</dsig:SignatureValue>
            <dsig:KeyInfo>
                <dsig:X509Data>
                    <dsig:X509Certificate>MIIDUTCC...</dsig:X509Certificate>
                </dsig:X509Data>
            </dsig:KeyInfo>
        </dsig:Signature>
        <saml:Subject>
            <saml:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient" NameQualifier="https://yyy/oam/fed" SPNameQualifier="http://xxx.sk">id-npAtUDygjM-XA-WWIIMK2sR9KkVgS-rj7UMo8-Pi</saml:NameID>
            <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
                <saml:SubjectConfirmationData InResponseTo="_705c6a70-d335-496b-aa00-1f09760f5d6e" NotOnOrAfter="2020-07-17T05:38:02Z" Recipient="https://zzz/saml/post/ac"/>
            </saml:SubjectConfirmation>
        </saml:Subject>
        <saml:Conditions NotBefore="2020-07-17T05:18:02Z" NotOnOrAfter="2020-07-17T05:38:02Z">
            <saml:AudienceRestriction>
                <saml:Audience>http://xxx.sk</saml:Audience>
            </saml:AudienceRestriction>
        </saml:Conditions>
        <saml:AuthnStatement AuthnInstant="2020-07-17T05:18:01Z" SessionIndex="id-sQ0oOmh3quTIgiosRU4SguBx957VEmXNJ8KGJI0M" SessionNotOnOrAfter="2020-07-17T05:38:02Z">
            <saml:AuthnContext>
                <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef>
            </saml:AuthnContext>
        </saml:AuthnStatement>
        <saml:AttributeStatement>
            <saml:Attribute Name="SubjectIDSector" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
                <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">SECTOR_DDD</saml:AttributeValue>
            </saml:Attribute>
            <saml:Attribute Name="Actor.AuthResourceType" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
                <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">1</saml:AttributeValue>
            </saml:Attribute>
            <saml:Attribute Name="Actor.AuthResourceSubType" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
                <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string"/>
            </saml:Attribute>
            ...
        </saml:AttributeStatement>
    </saml:Assertion>
</samlp:Response>

But in the method "private XmlElement GetAssertionElementReference ()" is this SAML response (does not contain "Assertion"):
<samlp:Response xmlns:samlp="urn:oasis:namesSAML:2.0:protocol" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:enc="http://www.w3.org/2001/04/xmlenc#" xmlns:saml="urn:oasis:namesSAML:2.0:assertion" xmlns:x500="urn:oasis:namesSAML:2.0:profiles:attribute:X500" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Destination="https://xxx/saml/post/ac" ID="id-8g-TC7zKiftlwjMuiPmvaaEaabPJr0pLnOthXlUEJE" InResponseTo="_7d3ab415-2c83-4f45-a5f9-2aa2d690c1fe" IssueInstant="2020-07-20T13:13:28Z" Version="2.0">
    <saml:Issuer Format="urn:oasis:namesSAML:2.0:nameid-format:entity">https://yyy/oam/fed</saml:Issuer>
    <dsig:Signature>
        <dsig:SignedInfo>
            <dsig:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
            <dsig:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
            <dsig:Reference URI="#id-8g-TC7zKiftlwjMuiPmvEbaaPJr0pLnOthXlUEJE">
                <dsig:Transforms>
                    <dsig:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                    <dsig:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
                </dsig:Transforms>
                <dsig:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
                <dsig:DigestValue>eMPiWff...</dsig:DigestValue>
            </dsig:Reference>
        </dsig:SignedInfo>
        <dsig:SignatureValue>GEr6eKff...</dsig:SignatureValue>
        <dsig:KeyInfo>
            <dsig:X509Data>
                <dsig:X509Certificate>MIIDUTCCAjm...</dsig:X509Certificate>
            </dsig:X509Data>
        </dsig:KeyInfo>
    </dsig:Signature>
    <samlp:Status>
        <samlp:StatusCode Value="urn:oasis:namesSAML:2.0:status:Success" />
    </samlp:Status>
    <saml20:EncryptedAssertion xmlns:saml20="urn:oasis:namesSAML:2.0:assertion">
        <xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Id="id-i9cF6A0M7-HLqav1DoaaqMrDlr20rUzeNL7fvq3S" Type="http://www.w3.org/2001/04/xmlenc#Element">
            <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" />
            <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
                <dsig:RetrievalMethod Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey" URI="#id-VmiCL-pXfnwU13AYHv-v9FSMaaZ3WPsjRGwk4MoD" />
            </KeyInfo>
            <xenc:CipherData>
                <xenc:CipherValue>dj2AfxCBA...</xenc:CipherValue>
            </xenc:CipherData>
        </xenc:EncryptedData>
        <xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Id="id-VmiCL-pXfnwU13AYHv-v9FSMmqZ3WPsjRGwk4MoD">
            <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
            <dsig:KeyInfo>
                <dsig:X509Data>
                    <dsig:X509Certificate>MIIDNDCCA...</dsig:X509Certificate>
                </dsig:X509Data>
            </dsig:KeyInfo>
            <xenc:CipherData>
                <xenc:CipherValue>DlGyVs...</xenc:CipherValue>
            </xenc:CipherData>
            <xenc:ReferenceList>
                <xenc:DataReference URI="#id-i9cF6A0M7-HLqav1Dot0qaaDlr20rUzeNL7fvq3S" />
            </xenc:ReferenceList>
        </xenc:EncryptedKey>
    </saml20:EncryptedAssertion>
</samlp:Response>


text:
Q: Ansible - how to parse/combine output from win_find Could someone please throw some light on how the below could be achieved with ansible:
I am currently searching for a file recursively using the win_find module (it's a windows box):
  - win_find:
      paths:
        - C:\Apps
      patterns: [ 'specific.file' ]
      recurse: yes
    register: apps_found

This produces the following list:
"apps_found": {
    "changed": false,
    "examined": 785,
    "failed": false,
    "files": [
        {
            "attributes": "Archive",
            "checksum": "67a43ebf47567ba43a29573a28479180392168d5",
            "creationtime": 1560515765.3164558,
            "extension": ".file",
            "filename": "specific.file",
            "isarchive": true,
            "isdir": false,
            "ishidden": false,
            "islnk": false,
            "isreadonly": false,
            "isshared": false,
            "lastaccesstime": 1560515765.2705016,
            "lastwritetime": 1560515765.2944584,
            "owner": "BUILTIN\\Administrators",
            "path": "C:\\Apps\\App1\\specific.file",
            "size": 247
        },
        {
            "attributes": "Archive",
            "checksum": "64dea9b49819fa4eee34dce52d2dc589a6f9667b",
            "creationtime": 1560769272.8943222,
            "extension": ".file",
            "filename": "specific.file",
            "isarchive": true,
            "isdir": false,
            "ishidden": false,
            "islnk": false,
            "isreadonly": false,
            "isshared": false,
            "lastaccesstime": 1560769272.847435,
            "lastwritetime": 1560769272.8788242,
            "owner": "BUILTIN\\Administrators",
            "path": "C:\\Apps\\App2\\specific.file",
            "size": 246
        }
    ],
    "matched": 2
}

What I want to do is:
For each found file, the 'path' key/value pair, I need to parse the subfolder name (App1, App2 in this case) and display it along with the contents of the specific.file.
So that at the end my playbook will produce a message such as:
"found application app1 with contents: "
"print the contents of the file."
How to do this easily in Ansible?
Thanks a lot upfront.

A: I don't have a windows machine to test so I briefly validated my below solution against your current data structure and some tests I made on my linux localhost.
To achieve your requirement, I first used the json_query filter to extract the paths from your result. This is used as a loop input to the slurp module to retreive the base64 representation of each file in a registered var.
Finally, I used a combination of win_dirname and win_basename filters to extract your application name in the final debug loop.
Here is the final example playbook (not fully tested as advised above):
---
- name: Show found app files
  hosts: whatever_group

  tasks:

    - name: Look for files on host
      win_find:
        paths:
          - C:\Apps
        patterns: [ 'specific.file' ]
        recurse: yes
      register: apps_found

    - name: Get the content of found files from host
      slurp:
        src: "{{ item }}"
      loop: "{{ apps_found | json_query('files[].path') }}"
      register: slurped_files

    - name: Display result
      debug:
        msg: "Found application {{ item.item | win_dirname | win_basename }} with contents: {{ item.content | b64decode }}"
      loop: "{{ slurped_files.results }}"


text:
Q: Python select match - OpenERP With the following function I'm trying to identify if a column already have X value.
def error_verify(self, cr, uid, ids, context=None):
    for record in self.browse(cr, uid, ids, context):
        nr = int(record.nr_service) # Gets the current value from field

        cr.execute("SELECT nr_service FROM services WHERE nr_service = %s", [nr])
        values = cr.fetchall()

        if values: # if there's ANY result it means there's at least one
                   # row with that value in the table
           return True
    return False

The function is called this way:
_constraints = [
        (error_verify, 'Error: Already that ID in the table', [''])
    ]

The thing is: I'm not getting any results. I'm trying to get the error message, but I can't reach there. I put some existing values inside the "record.nr_service", but it doesn't throw any message. My question is: Am I doing the function right?
I also tried this way:
 def error_verify(self, cr, uid, ids, context=None):
        for record in self.browse(cr, uid, ids, context):
            nr = int(record.nr_service) # Gets the current value from field

            cr.execute("SELECT nr_service FROM services WHERE nr_service = %s", [nr])
            values = cr.fetchall()

            for n in values:
                if nr == int(n[0]):
                   return True
        return False

And in this situation, also doesn't throw any message.
How can I solve it?

A: Ok, I've been testing and I think I found where my error is. Let's say I have the value "3" in the database. So, whenever I write the value "3" in the field it should display a error message, otherwise it let me go free.
This works:
def error_verify(self, cr, uid, ids, context=None):
        cr.execute("SELECT nr_service FROM services WHERE nr_service = %s", (3,))
        values = cr.fetchall()
        if values:
            return False # Returning false means that there's already a value "3" in the database.
        return True

This also works:
 def error_verify(self, cr, uid, ids, context=None):
            cr.execute("SELECT nr_service FROM services WHERE nr_service = %s", (55,))
            values = cr.fetchall()
            if values:
                return False
            return True # it returns true, it let me go free, because I don't have any value of "55" in the database

The problem here is that I can't tell the value "3" in the query, I should get that value from a field -> OpenERP field -> like this way:
for record in self.browse(cr, uid, ids, context=context): # loop through the fields
    nr_value = record.nr_service # this is the field
    cr.execute("SELECT nr_service FROM services WHERE nr_service = %s", (nr_value,))
    values = cr.fetchall()
    if values:
      return False
return True

With this code it retrieves me the message of error (which is on the 1st post) no matter the value I put inside the field. So, the problem must be on the loop. But I really need to get the value from that field.
Thanks!

A: Solved.
def verify_service(self, cr, uid, ids, context=None):
        record = self.browse(cr, uid, ids)[0]
        rec_value = str(record.nr_service)
        cr.execute("SELECT COUNT(*) FROM services WHERE nr_service = %s", [rec_value])
        values = cr.fetchone()
        if values[0] <= 1:
            return True
        return False


text:
Q: css: margin-top causes scrollbar The h1 element causes a scrollbar to appear. Can anyone explain me why?

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
}
header {
  height:10%;
}
section {
  height:90%;
}

    Hello

  test

A: Because the h1 comes with a margin, applied by the default style sheet.
When you add this margin (often margin-top: .67em and margin-bottom: .67em) to the height: 100% in your code, this exceeds the viewport height, launching a vertical scroll bar.
Give the h1 a margin: 0.
Whether you use box-sizing: content-box or border-box, the margin space will always be added to your height declaration.
If you want to add space around your h1 without adding height, use padding instead of margin, along with box-sizing: border-box. Here are some implementation options: https://css-tricks.com/box-sizing/

A: That's because

*

*h1 have some vertical margin by default, usually 0.67em.

*The top margin of h1 collapses

*height never includes the height of the margin area

Since the top margin of h1 collapses, it behaves like the margin belonged to the header instead of the h1. Since the content height of the h1 is 10%, its total height will be calc(10% + 0.67em).
That's why there is overflow.
If you remove the top margin but leave the bottom one there is no problem, because the bottom one does not collapse, due to the non-auto height. From Collapsing margins,

Two margins are adjoining if [...] both belong to vertically-adjacent
  box edges, [... e.g.]

*

*top margin of a box and top margin of its first in-flow child

*bottom margin of a last in-flow child and bottom
  margin of its parent if the parent has auto computed height.

So you can do any of the following

*

*Remove h1's top margin

*Prevent the margin collapse

*Propose a box-sizing: margin-box to the CSS Working Group. It will probably be rejected.

A: h1 by default has a margin applied.

A:

*
{
  margin:0px auto;
}
html, body {
  margin: 0 ;
  padding: 0;
  height: 100%;
}
header {
  height:10%;
}
section {
  height:90%;
}

    Hello

  test

Just add universal selector and make the margin *{margin:0px auto;} . Hope it will work

A: h1 tag in a block level element has some margin.
To remove such type of extra margin and padding, it is recommended to reset all elements margin and padding to 0.
This can be done by :
 * {
     margin: 0;
     padding: 0;
 }

* {
  margin: 0;
  padding: 0;
}
html, body {
  height: 100%;
}
header {
  height:10%;
}
section {

    Hello

  test


text:
Q: Context Variable will not show up in Django template I am writing a blog application, and a variable will not show up when the page is rendered. Here is my views.py function for my blog app:
def post_share(request, post_id):
    # retrieves post by id
    post = get_object_or_404(Post, id=post_id, status='published')
    sent = False

    if request.method == 'POST':
        # FORM was submitted
        form = EmailPostForm(request.POST)
        if form.is_valid():
            # form fields passed validation
            cd = form.cleaned_data

            post_url = request.build_absolute_uri(post.get_absolute_url())
            subject = '{} ({}) recommends you reading "{}"'.format(cd['name'], cd['email'], post.title)
            message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments'])

            send_mail(subject, message, 'admin@myblog.com', [cd['to']])
            sent = True

    else:
        form = EmailPostForm()
    return render(request, 'blog/post/share.html', {'post': post,
                                                'form': form,
                                                'sent': sent})

And forms.py:
from django import forms
from .models import Comment

class EmailPostForm(forms.Form):
    name = forms.CharField(max_length=25)
    email = forms.EmailField()
    to = forms.EmailField()
    comments = forms.CharField(required=False, widget=forms.Textarea)

Relevant part of my HTML template:
{% block content %}
    {% if sent %}

 Email successfully sent

            "{{ post.title }}" was successfully sent to {{ cd.to }} .

    {% else %}

 Share "{{ post.title }}" by email

        <form action="." method="post">
            {{ form.as_p }}
            {% csrf_token %}
            <input type="submit" value="Send e-mail">
        </form>
    {% endif %}

The template loads and the email is sent but it only says:

"Post Test" was succesfully sent to .

I need it to say the recipients email.

A: You need to include the cleaned data in the template context. However, cd is only defined when the form is valid, so you can do something like:
data = {
    'post': post,
    'form': form,
    'sent': sent,
}

if sent:
    data['cd'] = cd
return render(request, 'blog/post/share.html', data)

Since you don't need the entire cd dictionary in the template, another option would be to pass only the variable you need, cd['to'].
data = {
    'post': post,
    'form': form,
    'sent': sent,
}

if sent:
    data['sent_to'] = cd['to']
return render(request, 'blog/post/share.html', data)

Then in your template, you would use {{ sent_to }} instead of {{ cd.to }}

A: cd is only used within your view, but it is not a context variable.
To make it a context variable and accessible in the template you have to add it to your existing context variables:
return render(request, 'blog/post/share.html', {'post': post,
                                            'form': form,
                                            'sent': sent,
                                            'cd': cd})

A: You need to add to or cd to your context:
return render(request, 'blog/post/share.html', {'post': post,
                                                'form': form,
                                                'sent': sent})

For example:
{'cd': cd,
 'post': post,
 'form': form,
  'sent': sent}


text:
Q: laravel:how to get columns name of eloquent model? I am using laravel 5.2 ,i want to get all the column (attribute) name of selected eloquent model,is there way to do this?
following is my code in controller method
    if($request->method=="edit")
    {
        /*we are in edit mode details of given news ID should be attached*/
        $curNews=News::find($request->newsID);
        if($curNews==null)return back()->withErrors(["Unable to Edit News:No Data Found For Given News ID"]);

        foreach((array)$curNews->attributes as $key=>$val)
        {
            $data[$key]=$val;
        }

    }

    return view('adminarea.news.news-addedit',$data);

A: $columns = Schema::getColumnListing('users'); // users table
dd($columns); // dump the result and die

A: If you want get the names of your attributes, you can try this
$item = News::find($request->newsID);

    $attributes = array_keys($item->getOriginal());
// or
$attributes = array_keys($item->getAttributes());

A: don't know i am right or not, but i have overcome with following code,and its working for me.
    if($request->method=="edit")
    {
        /*we are in edit mode details of given news ID should be attached*/
        $curNews=News::find($request->newsID);
        if($curNews==null)return back()->withErrors(["Unable to Edit News:No Data Found For Given News ID"]);

        foreach($curNews->toArray() as $key=>$val)
        {
            $data[$key]=$val;
        }

    }

    return view('adminarea.news.news-addedit',$data);


text:
Q: Constraining image's placement / size for a background in a div I am trying to make my background image constrained so it fills the section but is not so zoomed in. Any help would be appreciated. I currently have this code

Sign up now for
a 14-day trial

Try it for free today

This is how it looks so far:

How i want it to look

A: Add background-position: center; along with the background-image property and see the result. If there's an issue with spacing there is the background-size property which in most cases is best to set as background-size: cover;


text:
Q: Android LinearLayout changes on screen rotation I am using the following XML code for tablets in API Level 17.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_gravity="center" >

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_gravity="center_horizontal"
    android:padding="40dp" >

    <EditText
        android:id="@+id/etUsername"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:inputType="text" >
    </EditText>

    <TextView
        android:id="@+id/tvUsername"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="User Name" />
</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_gravity="center_horizontal"
    android:padding="40dp" >

    <EditText
        android:id="@+id/etPassword"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:inputType="textPassword" />

    <TextView
        android:id="@+id/tvPassword"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Password" />
</LinearLayout>

<Button
    android:id="@+id/submitbutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@drawable/buttonpressing"
    android:text="Submit"

     />

<TextView
    android:id="@+id/showresult"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:layout_gravity="center" />

I want my TextView, EditText and Button to be centered. In landscape view (horizontal) they seem to be centred but in portrait(vertical) screen, they are in centre at the top of the screen.
How am I gonna fix it that no matter which view is this, they all stay in centre of screen?

A: Problem is that you set height of the root layout to "match_parent"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_gravity="center_horizontal"
    android:padding="40dp">

    <EditText
        android:id="@+id/etUsername"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:inputType="text"></EditText>

    <TextView
        android:id="@+id/tvUsername"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="User Name" />
</LinearLayout>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_gravity="center_horizontal"
    android:padding="40dp">

    <EditText
        android:id="@+id/etPassword"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:inputType="textPassword" />

    <TextView
        android:id="@+id/tvPassword"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Password" />
</LinearLayout>

<Button
    android:id="@+id/submitbutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="Submit"
    />

<TextView
    android:id="@+id/showresult"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:layout_gravity="center" />
</LinearLayout>


text:
Q: JsonElement convert hex or Base64 to byte array, problem with 0x00 Why string "0x00" is recognized as Base64 in convert method?
I'am trying convert JsonElement to byte[]. In JsonElement I have "0x00" but:
Span<byte> buffer = new Span<byte>(new byte[toConvert.Length]); // toConvert is JsonElement.ToString()
bool t = Convert.TryFromBase64String(toConvert, buffer, out int bytesParsed);

and
jsonElement.TryGetBytesFromBase64(out byte[] returnBytes)

Both method return true with
byte[211,29,52] - jsonElement.TryGetBytesFromBase64
byte[211,29,52,0] - Convert.TryFromBase64String
For "0x00" in byte[] should I have byte[0]. How can I fix it?


text:
Q: logrotate in SUSE Enterprise Server I can't manage to work this dummy config file (I placed it in etc/logrotate.d):
/var/log/test_log/mylogfile {
copytruncate
dateext
rotate 3
compress
missingok
size=+2
}

I write to the log (echo "hello world" > /var/log/test_log/mylogfile) but it's just not working.
Doing cat /etc/crontab shows:
# check scripts in cron.hourly, cron.daily, cron.weekly, and cron.monthly
#
-*/15 * * * *   root  test -x /usr/lib/cron/run-crons && /usr/lib/cron/run-crons >/dev/null 2>&1

I later redirected the output to in this way:
-*/15 * * * *   root  test -x /usr/lib/cron/run-crons && /usr/lib/cron/run-crons > /var/log/test_log/log_logrotate

But nothing happened.
Should I add another line in the etc/crontab to force the cron.dayly to happen kind of like in Ubuntu:
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )

or the problem may be in the /usr/lib/cron/run-crons file??
I am under SUSE Linux Enterprise Server 11 SP2

A: I think I found an answer to my question. The issue was tricky because "the newer Cron versions of Linux may run abit differently than in older versions" to what I was used to.
It seems now Cron consists of the script usr/lib/cron/run-crons, which checks whether cron.dayly in /var/spool/cron/lastrun/ is older than one day (By default it checks if it is more than or exactly 1440 minutes since lastrun). Or if we want the cron.dayly to run at a fixed time we should set the DAILY_TIME variable in the /etc/sysconfig/cron file to a time (i.e:"12:00") and it will be run at that time dayly (within 15minutes).
Note (from the /etc/sysconfig/cron comments):Due to the fact that cron script runs only every 15 minutes, it will only run on xx:00, xx:15, xx:30, xx:45, not at the accurate time you set.
I found the answer here:

A: logrotate runs either when time period is given weekly, daily and so on, or in the case of size when filesize exeeds the given size.
Just put there size=2, instead of size=+2, and it should work.

size size
Log files are rotated when they grow bigger then size bytes.  If
size  is  followed by M, the size if assumed to be in megabytes.
If the k is used, the size is in kilobytes. So  size  100,  size
100k, and size 100M are all valid.


text:
Q: CouchBase map multiple documents with key prefix I have the following keys in my Couch DB :
content_HASHKEY
content_info_HASHKEY

In the above example the HASHKEY is unique in both my documents however the prefix and document content vary for both and for my web client I do not want them to be making multiple Couch DB calls to retrieve both pieces of information (related ot the same HASHKEY), what is the most efficient way to retrieve both the documents in a single call from Couch base Db ?
EDIT :
DO I actually need the HASHKEY to be a property insideexach of the documents as well to be able to JOIN them ?:
content_HASHKEY
     HashKeyVal : HASHKEY
content_info_HASHKEY
     HashKeyVal : HASHKEY


text:
Q: Where is MSVS 2015 store settings? Where is MSVS 2015 store settings?
Infinite restoration damaged options.

*

*not help
uninstall MSVS2015
delete remainder after uninstall
c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe
c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe.config
c:\Program Files (x86)\Microsoft Visual Studio 14.0\
search in c:\Users\ and delete
*.vssettings
*.config
studio (for VisualStudio)
14 (14.0)
c:\users*\documents\visual studio 2015\settings\CurrentSettings.vssettings
c:\Users*\Documents\Visual Studio 2015\
c:\Users*\AppData\Local\Microsoft\VisualStudio\14.0\
c:\Users*\AppData\Local\Microsoft\VSCommon\14.0\
c:\Users*\AppData\Roaming\Microsoft\VisualStudio\14.0\
c:\Users*\AppData\Roaming\Microsoft\Windows\Recent\
c:\Users*\Microsoft\Windows\Start Menu\Programs\Visual Studio 2015\
c:\Users\All Users\regid.1991-06.com.microsoft\regid.1991-06.com.microsoft Microsoft Visual Studio Enterprise 2015.swidtag
c:\Users\All Users\Microsoft\VisualStudio\14.0\
c:\ProgramData\Microsoft Visual Studio\14.0\
Create new windows user, without password, with administrative rights of Administrators.
Install MSVS2015.
Tools->Options saved even after that.
Where saved Tools->Options?
Many options without changes, even font is same.

MSVS 2015 not work rebuild project on start project, not work auto rebuild.
Windows 10
MSVS2015, press green triangle (Local Windows Debugger), it will start previous *.exe instead make new from new code.
Message (This project is out of date Would you like to build it) appears only once.
Seems Code Analysis work once too.
Old project starts with syntax errors in new project.
Cause creating wrong old *.exe, not new.
Difficult to delete modification file of MSVS2015, which not delete even after uninstall.

May help, but not appropriate.
Manually delete after each creation.
\ConsoleApplication\Release\ConsoleApplication*.pdb
Or manually clean, rebuild project each time.
Or Build->Batch Build.
Or reinstall windows, take too much time.
Install on fresh W10 work, but not appropriate.

*

*not help
repair from installation disk
vs_enterprise.exe

*not help
Devenv.exe /ResetSettings "c:\Users*\Documents\Visual Studio 2015\settings\CurrentSettings.vssettings"

*not help
Tools->Options->Projects and Solutions->Build and Run
Diagnostic instead of Minimal
Seems any changes in Build and Run without effect.

*not help
Present. Only build startup projects and dependencies on Run.
Always build.
Prompt to launch.
Absent. For new solutions use the currently selected project at the startup project.
Output. Minimal. Log file. Minimal.

*not help
Build -> Configuration Manager -> [Build] present

*not help
Replace c:\users*\documents\visual studio 2015\settings\CurrentSettings.vssettings with file from working MSVS2015 from other OS W10

*not help
Tools->Import and Export Settings->Reset all settings->without save->Visual C++
choose Visual C++, then back to initial.
Or Reset all modification.

*not help
change in CurrentSettings.vssettings
[PropertyValue name="NOENCRebuild"]0[/PropertyValue]
to
[PropertyValue name="NOENCRebuild"]1[/PropertyValue]

*not help
istead of
c:\Program Files (x86)\Microsoft Visual Studio 14.0\
create by guest user, install MSVS2015 in
c:\Microsoft Visual Studio 14.0\
Programming Languages->Visual C++

*not help
Tools->Import and Export Settings
Import selected environment settings->General->All->Finish

*not help
if delete C:\Users*\Documents\Visual Studio 2015\Settings
The automatically saved settings file 'c:\users*\documents\visual studio 2015\settings\CurrentSettings.vssettings' cannot be found. You can change this file on the 'Import and Export Settings' Tools Options page. The IDE will use your most recent settings for this session.

*not help
Is there conflict between MSVS2015 and other programs, SDK, redistributables?
Seems, reinstall windows, or work on other computer easier than find solution, so.
Uninstall MSVS2015.
Uninstall many useful and not very programs via Control Panel.
Reinstall MSVS2015.

Perhaps it hide in windows registry or in packed, changed form?


text:
Q: paypal recurring payment with initial payment Hello im using paypal express checkout with the merchant sdk.
I have implemented recurring payment using the integration manual, but the given example doesnt make an initial payment(charge the user right away).
My code for making the payment is:
Initializing the payment:
    $cart = $this->cart->getCart();
    $items = $cart['items'];
    $itemTotal = 0;

    foreach ($items as $k => $item) {
        $product = $this->addItem($item);
        $itemTotal += $product->Amount;
        $this->paymentDetails->PaymentDetailsItem[$k] = $product;
    }

    $this->orderTotal->currencyID = 'USD';
    $this->orderTotal->value = $this->cart->getCartAmount();

    $this->paymentDetails->OrderTotal = $this->orderTotal;
    $this->paymentDetails->PaymentAction = 'Sale';
    $this->paymentDetails->InvoiceID = $invoice_id->{'$id'};

    $setECReqDetails = new \PayPal\EBLBaseComponents\SetExpressCheckoutRequestDetailsType();
    $setECReqDetails->PaymentDetails[0] = $this->paymentDetails;
    $setECReqDetails->CancelURL = $this->cancelURL;

    $setECReqDetails->ReturnURL = $this->returnURL;

    $billingAgreementDetails = new \PayPal\EBLBaseComponents\BillingAgreementDetailsType('RecurringPayments');
    $billingAgreementDetails->BillingAgreementDescription = 'recurringbilling';
    $setECReqDetails->BillingAgreementDetails = array($billingAgreementDetails);

    $setECReqType = new \PayPal\PayPalAPI\SetExpressCheckoutRequestType();
    $setECReqType->Version = $this->version;
    $setECReqType->SetExpressCheckoutRequestDetails = $setECReqDetails;

    $setECReq = new \PayPal\PayPalAPI\SetExpressCheckoutReq();
    $setECReq->SetExpressCheckoutRequest = $setECReqType;

    return $this->paypalService->SetExpressCheckout($setECReq);

And then on the return url i supplied i create the recurring payment with this code:
$profileDetails = new \PayPal\EBLBaseComponents\RecurringPaymentsProfileDetailsType();
    $profileDetails->BillingStartDate = "2014-01-24T00:00:00:000Z";

    $paymentBillingPeriod = new \PayPal\EBLBaseComponents\BillingPeriodDetailsType();
    $paymentBillingPeriod->BillingFrequency = 10;
    $paymentBillingPeriod->BillingPeriod = "Day";
    $paymentBillingPeriod->Amount = new \PayPal\CoreComponentTypes\BasicAmountType("USD", "1.0");
    $scheduleDetails = new \PayPal\EBLBaseComponents\ScheduleDetailsType();
    $activationDetails = new \PayPal\EBLBaseComponents\ActivationDetailsType();
    $activationDetails->InitialAmount = new \PayPal\CoreComponentTypes\BasicAmountType('USD', 49);
    $activationDetails->FailedInitialAmountAction = 'ContinueOnFailure';
    $scheduleDetails->Description = "recurringbilling";
    $scheduleDetails->ActivationDetails = $activationDetails;
    $scheduleDetails->PaymentPeriod = $paymentBillingPeriod;

    $createRPProfileRequestDetails = new \PayPal\EBLBaseComponents\CreateRecurringPaymentsProfileRequestDetailsType();
    $createRPProfileRequestDetails->Token = $token;

    $createRPProfileRequestDetails->ScheduleDetails = $scheduleDetails;
    $createRPProfileRequestDetails->RecurringPaymentsProfileDetails = $profileDetails;

    $createRPProfileRequest = new \PayPal\PayPalAPI\CreateRecurringPaymentsProfileRequestType();
    $createRPProfileRequest->CreateRecurringPaymentsProfileRequestDetails = $createRPProfileRequestDetails;

    $createRPProfileReq = new \PayPal\PayPalAPI\CreateRecurringPaymentsProfileReq();
    $createRPProfileReq->CreateRecurringPaymentsProfileRequest = $createRPProfileRequest;

    return $this->paypalService->CreateRecurringPaymentsProfile($createRPProfileReq);
}

In my sandbox account i can see that the recurring payment is created, but there is no initial payment.
My question is: How can i setup this recurring payment, so that an initial payment is made?
Hope i`ve explained good my problem. If you need more information comment.
EIDT: My question was how to create a recurring payment with initial payment. and i edited my code snippet. After some reading i saw that i missed to set it up with setting "ActivationDetailsType". I set it up and it works fine with one problem ... The payment profile is pending for 4-5 hours and then comes through. I read in forums and etc... that this was a sandbox issue but unfortunetly i cannot be sure that the payment will not be deleyd. In my case i need the payment to be approved right away. My new question is, when creating recurring payment profile, and the response for the account is ok(succes or what not) and the profile is pending can i count the payment as successful and be sure i`ll get the money for sure
Thank you for the time.
Regards,
Georgi

A: Quite late but I'm having similar concerns.

My new question is, when creating recurring payment profile, and the response for the account is ok(succes or what not) and the profile is pending can i count the payment as successful and be sure i`ll get the money for sure?

I'm currently working on it but I wouldn't count the pay until PayPal reflects the payment. I would utilize the IPN to trigger actions that should be made when the payment has come through. As for the 4-5 hour processing by PayPal (though sources from the web say production should not have the same delay), I'll just be sure to notify the buyer that his/her payment is still being processed by PayPal.


text:
Q: Laravel - How do I select all where column is equals to x or y or z (and on..)? I'm working on Laravel framework version 5.1
How do I select all of my rows from an eloquent model where his abc column equals to a or b or c?
Sorry if I haven't explained myself very well.

A: You just chain the conditions:
App\SomeModel::where('abc', 'a')->orWhere('abc', 'b')->orWhere('abc', 'c')->get();

Or as an alternative you can use whereIn for more compact solution:
App\SomeModel::whereIn('abc', ['a', 'b', 'c'])->get();

Which checks if the value of the abc column is present in the array passed.

You can check out the Laravel documentation for more info on using Where Clauses.


text:
Q: How to make an string input from user into an array of the individual letters in the input? I am making a solution where the user inputs a word or just letters and it shows the permutations of the word without duplicates. How could i make it so the input is made into an array of characters.(I am modifying another persons code to try and do this) so I want to assign a given value where i commented SOMEHOW in my code below so that I can Split it into the array. Im new to coding and would appreciate the help.
public static void Main()
    {
                string input;
        //char word_inputed;
        Console.WriteLine("Please print a word");
        input = Console.ReadLine();
        //string phrase = "The quick brown fox jumps over the lazy dog.";
        string[] words = input.Split(' ');

        foreach (var word in words)
        {

            foreach (var letter in word)
            {

               //SOMEHOW values = Console.Write($"{letter},");

            }
        }

        ArrayList list = new ArrayList();
        list.AddRange(values.Split(new char[] { ',' }));

        char[] word_inputed = { 'A' };
        int n = word_inputed.Length;
        findPermutations(word_inputed, 0, n);

    }

A: Here is the Microsoft sample
// Sample for String.ToCharArray(Int32, Int32)
using System;

class Sample {
    public static void Main() {
    string str = "012wxyz789";
    char[] arr;

    arr = str.ToCharArray(3, 4);
    Console.Write("The letters in '{0}' are: '", str);
    Console.Write(arr);
    Console.WriteLine("'");
    Console.WriteLine("Each letter in '{0}' is:", str);
    foreach (char c in arr)
        Console.WriteLine(c);
    }
}
/*
This example produces the following results:
The letters in '012wxyz789' are: 'wxyz'
Each letter in '012wxyz789' is:
w
x
y
z
*/

door


text:
Q: Adding Reference in Vb6- MSR and DAO 3.6 Maybe i don't have any knowledge of how referencing works in VB6. I have an application written on visual basic 6. I've added Microsoft Scripting Runtime and Data Access Object 3.6 as references. I wanna know which component should be placed in others systems to prevent issues related to these two references. I mean if the user has windows XP, Vista,7 or 8 does my application will run correct in that versions of windows? (considering these two references)

A: You will have to include DAO 3.6 redistributable files, as explained on the Microsoft support page; However, your application will work properly on all of these target Windows versions, if no other potential issues exists (e.g. other incompatible used ActiveX control)

A: Have your clients install the EXEs created by Microsoft:

*

*For Microsoft Scripting Runtime, check out the "Cause" Section of this article.

*For DAO, check out the resolutiion section of this article.


text:
Q: reCAPTCHA fails on one domain - same code (except key) passes on other domain I have two sites
Both of them have a reCAPTCHA 2.0 from google
I have implemented the exact same code on both domains (except for the keys)
To troubleshoot, I have asked the server to show me php-version and extensions:
Working reCaptcha
Failing reCaptcha
I have no idea why it fails on the one domain and not at the other.
Both reCaptchas have just been created and are both version 2.0
The basic code for both is:
Client side:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Recaptcha test</title>

reCAPTCHA

<form action="responce.php" method="post">

Name: <input type="text" name="name">

Mail: <input type="text" name="email">

    <input type="submit" value="test">
</form>

Server side:
$sender_name=stripslashes($_POST["name"]);
$sender_email=stripslashes($_POST["email"]);

$secret="--My-Server-Key--";
$response=$_POST["g-recaptcha-response"];
$verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
$captcha_success=json_decode($verify);

if ($captcha_success->success==false) {
$success="isFalse";
}
else if ($captcha_success->success==true) {
$success="isTrue";
}

echo $success . "
";
echo 'php version => '. phpversion() . '
';
foreach (get_loaded_extensions() as $i => $ext) {
echo $ext .' => '. phpversion($ext). '
';
}
?>


text:
Q: DirectX11 buffer for generated 2D map I am working on simple 2D game (pacman like).
Map for game is made of tiles (2D array 30x40), each tile is represented by 16px x 16px graphic.
My problem is that I  redraw all tiles (30x40 = 1200 tiles) each frame which makes FPS pretty low.
My idea to solve this is to draw map (1200 tiles) to one big buffer, then each frame draw only this buffer, but I do not know how to achieve that, this is my first project with DirectX.
How to achieve that or maybe you have better idea.
Code (simplified):
ID3D11Device* pDevice;
ID3D11DeviceContext* pImmediateContext;
ID3D11RenderTargetView* pRenderTargetView;
IDXGISwapChain* pSwapChain;
ID3D11Resource* pResource;
ID3D11ShaderResourceView* pTexture;
std::unique_ptr<DirectX::SpriteBatch> spriteBatch;
Game* pGame;

Function used to render frame
void GameApp::renderGame(float dt) {
    pImmediateContext->ClearRenderTargetView(pRenderTargetView, DirectX::Colors::Black);
    spriteBatch->Begin();
    pGame->draw();
    spriteBatch->End();
    pSwapChain->Present(0, 0);
}

pGame->draw();
void Game::draw() {
    for (int i = 0; i < sizeY; ++i) {
        for (int j = 0; j < sizeX; ++j) {
            // Draw tile
            spriteBatch->Draw(pTexture, vPosition, &sourceRect, tint, rotation, vOrigin, vScale,
            DirectX::SpriteEffects::SpriteEffects_None, 0.0f);
            tile->Draw(spriteBatch);
        }
    }
}

Function I use to load sprites (I call it once, not in loop)
DirectX::CreateDDSTextureFromFile(device, file, &pResource, &pTexture)

Tell me if you need more detail.


text:
Q: Unable to extract jsonarray from jsonobject I have been battling with response from server using retrofit.
I have this json response from server
{
    "success": true,
    "message": "Your Requests",
    "data": {
        "requests": [
            {
                "_id": "5d163a5ed2399f8be6d8d867",
                "created": "2019-06-28T16:03:42.463Z",
                "pickupCoordinates": [
                    8.0099,
                    6.0909
                ],
                "destinationCoordinates": [
                    9.088788,
                    3.099403
                ],
                "customerName": "Seun Akinbode",
                "pickupAddress": "Lekki",
                "destinationAddress": "Ajah",
                "accessCode": "3334",
                "busPlate": "DD222RR",
                "flaName": "Simi",
                "flaEmail": "awele@kobo360.com",
                "__v": 0
            } ]
}

I use below class to parse the json but unfortunately, it couldn't extract  the array requests into jsonArray
 public ArrayList<RequestModel> getData(String response)
        {
            Log.d("responseData :", response);
            ArrayList<RequestModel> dataList = new ArrayList<>();
            try {
                JSONObject mainObj = new JSONObject(response);
                JSONArray array = mainObj.getJSONArray("data");
                Log.d("The main Array :", array.toString());
                RequestModel data;
                for(int i = 0;i<array.length();i++)
                {
                    data = new RequestModel();
                    JSONObject resObj = array.getJSONObject(i);
                    JSONArray reqArray = resObj.getJSONArray("requests");
                    for( int j =0;j<reqArray.length();j++) {
                        JSONObject reqObj = reqArray.getJSONObject(j);
                        data.setAccessCode(reqObj.getString("accessCode"));
                        Log.d("Accessecode :", reqObj.getString("accessCode"));
                        data.setCustomerName(reqObj.getString("customerName"));
                        Log.d("customerName :", reqObj.getString("customerName"));
                    }

                    dataList.add(data);

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

            return dataList;
        }

Logcat is printing the JSONObject but it says at ... data of type org.json.JSONObject cannot be converted to JSONArray

A: You are trying to extract an array from the data field, while the response contains an object. Perhaps you meant to get the object data, then the array requests from within it.

A: This could be the problem:
JSONArray array = mainObj.getJSONArray("data");

data is an object as seen in the response, not an array.


text:
Q: DESCRIBE table returns nothing According to docs, this command should return table structure:
DESCRIBE schema.<table>

I tried:
-- Some CSV of 1000 lines (csv.extract_header=true)
DESCRIBE dfs.`sample_data.csv`
-- Empty result

-- Output format set to parquet
CREATE TABLE dfs.tmp.`test_parquet` AS SELECT * FROM dfs.`sample_data.csv`
-- > 1000 rows created

-- Querying newly created table
DESCRIBE dfs.tmp.`test_parquet`
-- Empty result

-- Querying my own parquet from somewhere else
DESCRIBE dfs.`another.parquet`
-- Empty result

REFRESH TABLE METADATA dfs.tmp.`test_parquet`
DESCRIBE dfs.tmp.`test_parquet`
-- Empty result

-- I've got postgres datasource connected as "pg"
DESCRIBE pg.public.MyPostgresTable
-- > Returns valid structure

It seems that DESCRIBE command does not describe parquets and CSV.
What I'm missing?
Drill v1.15

A: According to docs, this command may be used for views created in a workspace, tables created in Hive and HBase, or schemas.
DESCRIBE does not support tables created in a file system.


text:
Q: Как изменить external library в maven проекте? В моем maven проекте есть следующая зависимость, которая успешно скачивается и работает.
<dependency>
    <groupId>net.thucydides</groupId>
    <artifactId>thucydides-core</artifactId>
    <version>${thucydides.version}</version>
</dependency>

Сейчас добавляю в проект yandex html elements, но не могу выполнить одно действие - отредактировать класс SmartElementProxyCreator.java в
thucydides/thucydides-сore/src/main/java/net/thucydides/core/annotations/locators.
Idea всегда говорит о том что файл read only, что логично, так как это внешний репозитарий.

Как мне правильно изменить этот класс внешней библиотеки и сделать deploy в свой проект?

A: Чтобы изменить класс - качаете исходники данной библиотеки, далее меняете класс, собираете и приатачиваете к проекту.

A: Дополню следующими конкретными шагами для таких же зеленых, как я:
1) Скачать исходники с гита для нужной версии и распаковать
2) Открыть в IDE как maven проект, главный из всех называется thucydides
3) Изменить нужный класс
4) Сделать mvn compile
5) mvn install - так jar файл этого проекта окажется в локальном репозитарии
6) Закрыть этот проект
7) Открыть или создать новый проект
8) в pom файле указать dependency на этот jar
9) убедиться что версии junit, maven plugins, selenium указанные в pomнике совместимы. Если у вас на этапе compile-install возникают ошибки, скорее всего проблема в версиях


text:
Q: Can the minimum value of a binary search tree not be the leftmost entry? If I construct a binary search tree as I have below, is it right? Or is such a tree not a valid binary search tree?
    7
   / \
  5   8
     / \
    4  10

Because I have followed the rule of smaller element on the left and larger element on the right. So I imagine this is a binary search tree?

A: Try to walk the tree manually; pretending that you're a function looking for the 4.

*

*You start at the root of the tree: the 7.

*4 is less than 7, so you go left to 5.

*4 is less than 5 so you go left again.

*There's nothing there, so you'd come to the conclusion that 4 is not in the tree.

Of course that's incorrect though, so no, this is not a valid setup  for a BST. It isn't simply that each value needs to only be in the correct position relative to its direct parent. Each value also needs to be in a correct position relative to the other nodes in the tree.
The exact position depends on the insertion order of each value, but with this configuration of values, the 4 should be to the left of the 5.

A: It's definitely a binary tree, as each node only has two leaves.
But like others said, it's not a binary search tree. A way of judging is for each node, all left leaves' values should be smaller than self's value and all right leaves' values should be greater than self's value. Only in this way can perform binary search.


text:
Q: What's the significance of using a generator to prove a cyclic subgroup? I have the main group of a general linear group of order 3, over real numbers. How is it that the below is a cyclic subgroup?
$$H = \begin{bmatrix}
    1 & 0 & a\\ 0 & 1 & 0\\ 0 & 0 & 1
\end{bmatrix}, a \in integers$$
The point of the question is to understand the importance of generators, but how do I get the generator of a matrix? From there, I'm assuming I can simply use the two-step subgroup test to prove that it is a subgroup. Any idea on why it would be cyclic though?

A: This group is generated by
$$\begin{pmatrix} 1&0&1 \\ 0&1&0 \\ 0&0&1 \end{pmatrix},$$
which has inverse
$$\begin{pmatrix} 1&0&-1 \\ 0&1&0 \\ 0&0&1 \end{pmatrix}.$$
This is the reason it is clearly cyclic --- you can explicitly give the generator.

A: A cyclic subgroup is the subgroup $\{ x^n \mid n \in \mathbb{Z} \}$ generated by one of its elements $x \in G$, so you would like to find this element.
If you have a matrix $X$ of your form, try calculating its powers $X^n$ for $n\in \mathbb{Z}$. What do you get?


text:
Q: How to wrap JavaScript fetch in a function - unhandled promise rejection I'm trying to write a wrapper function for the JavaScript fetch command.
I took the example code from this post:
function fetchAPI(url, data, method = 'POST') {
const headers = {
    'Authorization': `Token ${getAuthToken()}`,
};

return fetch(url, { headers, 'method': method, 'body': data })
    .then(response => {
        if (response.ok) {
            const contentType = response.headers.get('Content-Type') || '';

            if (contentType.includes('application/json')) {
                return response.json().catch(error => {
                    return Promise.reject(new Error('Invalid JSON: ' + error.message));
                });
            }

            if (contentType.includes('text/html')) {
                return response.text().then(html => {
                    return {
                        'page_type': 'generic',
                        'html': html
                    };
                }).catch(error => {
                    return Promise.reject(new Error('HTML error: ' + error.message));
                });
            }

            return Promise.reject(new Error('Invalid content type: ' + contentType));
        }

        if (response.status === 404) {
            return Promise.reject(new Error('Page not found: ' + url));
        }

        return response.json().then(res => {
            // if the response is ok but the server rejected the request, e.g. because of a wrong password, we want to display the reason
            // the information is contained in the json()
            // there may be more than one error
            let errors = [];
            Object.keys(res).forEach((key) => {
                errors.push(`${key}: ${res[key]}`);
            });
            return Promise.reject(new Error(errors)
            );
        });
    }).catch(error => {
        return Promise.reject(new Error(error.message));
    });

};
And I'm calling it like this:
fetchAPI('/api/v1/rest-auth/password/change/', formData).then(response => {
        console.log('response ', response);
    });

Edit: I have modified the code to display information returned by the server if the request is ok but refused, for example because of an invalid password. You have to interrogate the response json if ok == false.
A valid URL fetch is fine. But if there is an error, I see an Unhandled Rejection (Error): error message.
Why is it that the rejects are unhandled even though they are in catch blocks? What's the secret sauce here?

A: The way to avoid an unhandled promise rejection, is to handle it:
fetchAPI('/api/v1/rest-auth/password/change/', formData).then(response => {
    console.log('response ', response);
}).catch(error => {
   // do something meaningful here.
});;


text:
Q: Find a non-zero 2×2 matrix such that $$\begin{pmatrix}
4 & -2  \\
-8 & 4  \\
\end{pmatrix}\times\begin{pmatrix}
unknown & unknown  \\
 unknown & unknown  \\
\end{pmatrix}=    \begin{pmatrix}0 & 0  \\
 0 & 0  \\
\end{pmatrix}$$
What I tried doing is replacing all of the unknowns by a arbitrary variables, so $x,y,s,t$. that gave me $4$ variables (unknown), and $4$ equations.
i changed the upper left unknown to x, upper right to y, lower left to s, lower right to t. i ended up getting $4x-2s=0$,
$4y-2t=0$,
$-8x+4s=0$,
 $-8y+4t=0$
...
I tried isolating variables, but I ended up no where (kept getting 0=0).

A: This is the answer that I gave for the post that you deleted:
Let's consider
$$\begin{bmatrix} 4 &- 2 \\ - 8 & 4\end{bmatrix}\begin{bmatrix} x & y\\ s & t\end{bmatrix}= \begin{bmatrix} 0 & 0\\ 0 & 0\end{bmatrix}$$
We can focus on
$$\begin{bmatrix} 4 &- 2 \\ - 8 & 4\end{bmatrix}\begin{bmatrix} x \\ s \end{bmatrix}= \begin{bmatrix} 0 \\ 0 \end{bmatrix}$$
Note that the two equations are dependent, hence
$$\begin{bmatrix} 2 &- 1 \\ 0 & 0\end{bmatrix}\begin{bmatrix} x \\ s \end{bmatrix}= \begin{bmatrix} 0 \\ 0 \end{bmatrix}$$
That is we have $$2x-s=0$$
that is $s=2x$ is a solution.
Similarly, $t=2y$ is a solution, that is whenever, we decide $x$ and $y$, we can recover our $s$ and $t$.
There are non-trivial solutions to the system.
You just have to pick $x=y=1$, then you get $s=t=2$ to get a possible solution.

A: Let $$\begin{pmatrix}
a & b  \\
c & d  \\
\end{pmatrix}$$ denote the unknown matrix you want to find.
You get four equations,
$$-8a+4c=0$$
$$4a-2c=0$$
$$4b-2d=0$$
$$-8a+4d=0$$
First equation say that $-8a+4c=0$ in other words $8a=4c$ which further implies that $c=2a$. similarly you can use the third equation to conclude that $d=2b$
So you have these two relation $$c=2a$$ and $$d=2b$$
It means you are free to pick $a$ and then for $c$ you have to just double the value of $a$ you picked. Similarly for $b$ and $d$.
In particular,
Take $a=1$ then two times of $1$ is $2$ so $c=2$,
similarly $b=1,d=2$ and see whether they satisfy the equation or not.


text:
Q: Xcode Adding 3rd Party Code To My Project Sorry, I'm an Obj-c noob so I'm probably just missing something simple...
I'm trying to add the code in this question to my project. I want to have a simple facebook photo chooser. What does he mean when he says, "And Implement FBImagePickerDelegate delegate with delegate method imagePickingFinishedWithImage: (which is required)."?
Facebook Photo Picker Controller for iOS (similar to the Places Picker controller)
I've added the files to my project but am getting some errors. For one, it doesn't understand FBSession, which was easy to fix by importing the facebook SDK, then however I get another error.
No visible @interface for UIImageView declares the selector 'setImageWithUrl' on this line...
 [objCell.imgAlbumCoverPhoto setImageWithURL:urlPhoto];

A: objCell.imgAlbumCoverPhoto is that a subclass of UIImageView? because UIImageView have no method called setImageWithURL by default. Then you probably havn't imported the headerfile  for that class correctly.


text:
Q: Many-to-one cascade delete NHibernate results in RESTRICT (MySQL 5) I've a simple category class. Each category can have zero or more children of type category. Therefore I have chosen to register the parent of a category, which can be null or the id of another category. When a category is deleted, all its children (of type category) must be deleted as well.
When the schema of the table is created by NHibernate, the foreign key exists, but On Delete: is set to RESTRICT.
NOTE: When I manually change On Delete: to CASCADE all works as expected.
I've read that this is a wrong approach to relate the child to a parent. I do not see why. Hence, it works. But NHibernate doesn't configure the On Delete how I would like to.
I've read about inverse collections and bags, and using separate tables. But I am confused about what my approach should be.
How would one achieve the on delete cascade with this category class, and why?
My mapping looks like this:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="BackEnd"
                   namespace="BackEnd.Models">
  <class name="Category">
    <id name="Id">
      <generator class="native"/>
    </id>
    <property name="Name" />
    <many-to-one class="Category" name="Parent" cascade="delete"/>
    <property name="Description" />
  </class>
</hibernate-mapping>

A: This is how its possible to map a parent child relationship in the same table, listing all childeren to your object, and deleting all childs when a parent is deleted.
I finally got this by trial and error. It took me 15 attempts.
    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                       assembly="BackEnd"
                       namespace="BackEnd.Models">
      <class name="Category">
        <id name="Id">
          <generator class="native"/>
        </id>
        <property name="Name" />
        <property name="ParentId" />
        <bag name="Children" table="Category" inverse="true" cascade="all-delete-orphan">
          <key column="ParentId" on-delete="cascade"/>
          <one-to-many class="Category"/>
        </bag>
        <property name="Description" />
      </class>
    </hibernate-mapping>

This is the code for the class I use.
/// <summary>
/// The ModelBase takes care of the CRUD (Create, Read, Update, Delete) functionalities for each derived class.
/// public functions here must be virtual, read this: http://thatextramile.be/blog/2009/03/must-everything-be-virtual-with-nhibernate/
/// This is an abstract class as it has no purpose on its own.
/// </summary>
public abstract class ModelBase<T>
{

    /// <summary>
    /// The id by which this transient object is related to a persistent object in database.
    /// </summary>
    public virtual ulong Id { get; set; }

    /// <summary>
    /// Many objects, like categories, issues, etc, can have a parent of the same type
    /// </summary>
    public virtual ulong ParentId { get; set; }

    /// <summary>
    /// The childeren of this object, if any
    /// </summary>
    public virtual IList<T> Children
    {
        get;
        set;
    }

    /// <summary>
    /// Constructor only available for derived classes.
    /// </summary>
    protected ModelBase()
    {
    }

    /// <summary>
    /// Creates or updates this object in database.
    /// </summary>
    public virtual void CreateOrUpdate()
    {
        using(ISession Session = Gate.SessionFactory.OpenSession())
        {
            Session.SaveOrUpdate(((T)((Object)this)));
            Session.Flush();
            Session.Close();
        }
    }

    /// <summary>
    /// Deletes this object from database
    /// </summary>
    public virtual void Delete()
    {
        using (ISession Session = Gate.SessionFactory.OpenSession())
        {
            Session.Delete(((T)((Object)this))); //Needs to be casted as the type of the top most class, or it will fail to get its properties.
            Session.Flush();
            Session.Close();
        }
    }

    /// <summary>
    /// Loads a persistent object (from database) in to a transienst object (variable).
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="Id">The Id of the object by which it is known in database.</param>
    /// <returns>A strong typed object.</returns>
    public static T Load(ulong Id)
    {
        /* TODO: Lazy loading only possible when sessinos remains open.
         * Solve this by adding some kind of OnDispose event that automatically closes the connection when the object is disposed.
         */
        //using (ISession Session = Gate.SessionFactory.OpenSession())
        //{
        //    ModelObject = Session.Load<T>(Id);
        //    Session.Close();
        //}
        ISession Session = Gate.SessionFactory.OpenSession();
        return Session.Load<T>(Id);
    }
}

And finally the category class that is derived from the base class
/// <summary>
/// A part can be categorized, under one or more, categories.
/// Each category is an instance of this class.
/// </summary>
public class Category : ModelBase<Category>
{
    /// <summary>
    /// The name of the category that is displayed to the user.
    /// </summary>
    public virtual String Name { get; set; }

    /// <summary>
    /// A description of what this category is about.
    /// </summary>
    public virtual String Description { get; set; }

    /// <summary>
    /// The constructor creates a new category object.
    /// </summary>
    public Category()
    {
    }
}


text:
Q: update an element in deeply nested array after checking multiple conditions in MongoDB Say, I have a document structure
[ {
  "name" : "in",
  "states" : [ {"name" : "up",
                "cities" : [ {"name" : "dp", "places" : [ {"name" : "pvr"}, {"name" : "lpu"} ] },
                            {"name" : "mo", "places" : [ {"name" : "pvr"}, {"name" : "lpu"} ] } ]},
               {"name" : "tn",
               "cities" : [ {"name" : "ab", "places" : [ {"name" : "pvr"}, {"name" : "lpu"} ] },
                            {"name" : "cd", "places" : [ {"name" : "pvr"}, {"name" : "lpu"} ] } ]}
             ]
  },
  {
  "name" : "ik",
  "states" : [ {"name" : "up",
                "cities" : [ {"name" : "dp", "places" : [ {"name" : "pvr"}, {"name" : "ont"} ] },
                            {"name" : "lo", "places" : [ {"name" : "zcv"}, {"name" : "bft"} ] } ]},
               {"name" : "kl",
               "cities" : [ {"name" : "hp", "places" : [ {"name" : "bgh"}, {"name" : "vhi"} ] },
                            {"name" : "mp", "places" : [ {"name" : "hup"}, {"name" : "plm"} ] } ]}
             ]
} ]

I would like to change the "{"name" : "pvr"}" to "{"name" : "cvr"}" of "places" where ("name":"ik" and "states.name":"up" and "cities.name":"dp"). How to check for all three conditions and update?

A: Since the position of array element you want to update is unknown, you will need to fetch the matching states and cities, iterate over places and the set the new value in your application code. Alternatively, you can model your data differently if this kind of update is done frequently so you do not have so many levels deep of array elements.


text:
Q: Lucene.Net persisting boost values I have an Index created but it has lot of junk data. What I hope to accomplish is a voting system, where more votes equates to a higher boost value. Unfortunately the boost values are not saved back to the index after user submits a vote.
This is the breakdown of the code for my Boost function, does anyone have any ideas as to what I'm doing wrong? I used explain(), but it doesn't have anything related to the boost value.
BoostUp(int documentId)
{

    IndexSearcher searcher = new IndexSearcher(dir);

    Document oldDoc = search.doc(documentId);
    //get all the stored information from old document

    Document updatedDocument = new Document();
    //Add fields containing data from old document.

    updatedDocument.Boost = oldDoc.Boost * 1.5F;

    IndexWriter writer = new IndexWriter(dir, new StandardAnalyzer(Version.LUCENE_30), false, MaxFieldLength.LIMITED);

    Term uniqueTerm = new term("content_id", content_id_from_old_document);

    writer.UpdateDocument(uniqueTerm, updatedDocument);
    writer.Commit();
    writer.Dispose();
}

A: The problem is that you can't retrieve that value from the index.  The retrieved document doesn't have the boost set.  It is combined with other index-time scoring factors and encoded in the index such that it is not possible to retrieve it.
The solution, I think, would be to save the boost as a field stored in the index, and retrieve that, and use it to modify and set the boost.
Something along these lines:
Field boostField = oldDoc.getField("saved_boost");
float newBoost = boostField.numericValue().floatValue() * 1.5F;
updatedDocument.setBoost(newBoost);
updatedDocument.removeField("saved_boost");
NumericField boostField = new NumericField("saved_boost",Field.Store.YES,false);
boostField.setFloatValue(newBoost);
updatedDocument.add(boostField);

//No changes from here on...

IndexWriter writer = new IndexWriter(dir, new StandardAnalyzer(Version.LUCENE_30), false, MaxFieldLength.LIMITED);

Term uniqueTerm = new term("content_id", content_id_from_old_document);

writer.UpdateDocument(uniqueTerm, updatedDocument);


text:
Q: Pooler (pgbouncer) + MasterDB + Slaves During a spike, my connections go from 30 to over 140, as you can see below:

I'm willing to set-up a pooler like pgbouncer, but have some questions as my scenario is not that easy:

1 Load Balancer (nginx)
2 web servers (www01 and www02)
5 DB servers (master01, slave01 (read-only), slave02 (hot_standby),
  slave03 (hot_standby), slave04 (hot_standby)
Just ONE Database. Size: 2TB
max_connections: 200
I'm using PostgreSQL 9.2

Question:
Can pgbouncer handle with my master and slave01, as I'm using slave01 as read-only server? Also.. I've got 2 www servers... Do I have to have pgbouncer in both of them?

A: Yes you can define in pgbouncer your 2 servers (or more) masetr and slave and connect to each of them.
There is different kind of topology you can install pgbouncer on each www, as is the connection will be the fastest (www process can use unix socket to connect), on install a pgbouncer on each server (master and slave) or install it on a new host to be single.
PErsonnaly I recommend another topology, install pgbouncer everywhere, on each www (to increase the connection), and on each db server, it will help you when you'll want to do migrations for example. PgBouncer support PAUSE/RESUME on connection, as is you can reconfigure your conenction on move traffic to master to a new host when you'll upgrade verison for example.