text:
Q: Secured social doesn't redirect correctly with NGINX in play framework After successful login, securedsocial redirect to the URL http://sss/ instead of http://ip:9009. The proxy_pass works fine except when logging to the system with securedsocial.Any fix to this?
NGIXIN.conf
 upstream sss {
     server ip:9009;
 }

SecuredSocial.conf
 onLoginGoTo=/

worker_processes  auto;
events {
   worker_connections  20000;
}

http {
include       mime.types;
default_type  application/octet-stream;
sendfile        on;
keepalive_timeout  65;

upstream playserver {
    server 127.0.0.1:9009;
  }

server {
    listen  80;
    server_name  localhost;

        access_log off;
    location / {
        proxy_pass http://playserver;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}
 }


text:
Q: Magento Varnish Turpentine By Pass a Block (dont cached a block) I am testing magento with varnish and turpentine extesion. I installed all successfully but when i try to by pass (or flush per second) a block, it is hidden or disapear.
For Example i want to by pass product.info.media block.
My xml configuration for by pass in turpenine_esi.xml :
<catalog_product_view>
    <reference name="product.info.media">
        <action method="setEsiOptions">
            <params>
                <access>public</access>
                <ttl>1</ttl>
            </params>
        </action>
    </reference>
</catalog_product_view>

The block is:
<block type="catalog/product_view_media" name="product.info.media" as="media" template="catalog/product/view/media.phtml">
    <block type="core/text_list" name="product.info.media.after" as="after" />
</block>

is possible to do this? I'm doing wrong?
thanks a lot.

A: Can you try next:
<catalog_product_view>
    <reference name="product.info.media">
        <action method="setEsiOptions">
            <params>
                <method>esi</method>
                <access>public</access>
                <scope>page</scope>
                <ttl>1</ttl>
            </params>
        </action>
    </reference>
</catalog_product_view>

Also check what your block inherit from Mage_Core_Block_Template class.

A: You're better off putting your ESI options in the local.xml for your theme, since turpentine_esi.xml may get overwritten when you update the extension.
Turn on debugging in Turpentine and see if anything interesting shows up in your system.log. Other caching extensions or having other caches enabled can cause errors like these. Also, check for exceptions being generated from your template, those can also cause issues like this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP validating individual form fields then all of them My simple php form validation script:
$email      = (isset($_POST['email'])) ? $_POST['email'] : '' ;
$password       = (isset($_POST['password'])) ? $_POST['password'] : '' ;
$fname      = (isset($_POST['fname'])) ? $_POST['fname'] : '' ;
$lname      = (isset($_POST['lname'])) ? $_POST['lname'] : '' ;

if (!empty($email) && !empty($password) && !empty($fname) && !empty($lname)) {
    $auth->createAccount($email, $password, $fname, $lname);
}

For some reason it doesn't look very good to me.
How can I check each form field to indicate which one is the one that needs filling out and then at the end check to make sure all fields are filled out before calling the createAccount() function.
Note: the createAccount() function sanitizes the input so there is no need to do this here.

A: Most common way to deal with this that I've seen is to create an array:
if (!$_POST['email']) {$errors[] = 'Email field is empty.';}
if (!$_POST['password']) {$errors[] = 'Password field is empty.';}
if (!$_POST['fname']) {$errors[] = 'First name field is empty.';}
if (!$_POST['lname']) {$errors[] = 'Last name field is empty.';}

And then loop through the errors to display them:
foreach ($errors as $error) {
    echo $error.'
';
}

A: Try this:
<?php
$form_names = array(
    'email' => 'e-mail',
    'password' => 'password',
    'fname' => 'firstname',
    'lname' => 'lastname'
); //So that the user understands the errors better
$errors = array();
foreach ($_POST as $field=>$val) {
    if (empty($val)) {
        array_push($errors, 'Please fill out ' . $form_names[$field]);
    }
}
if (count($errors) == 0) {
    //No errors call the submit PHP function
}
else {
    $string = implode('
', $errors);
    echo '
' . $string . '
';
}
?>

However, the setback is that form names should be appropriate to echo out to the user in an intelligible way. As some may require spaces, you can create an array for form names connected to their actual and use that value to echo out to the user via. $good_name = $form_names[$field]


text:
Q: Can we use non-relative clauses as descriptive modifiers? In most grammar books, adjective/relative clauses are limited to specific constructs involving words such as 'that' or 'which' (as two of multiple examples):

[1] The house that I grew up in

There are also examples of non-finite relative clauses, which use participles and infinitives:

[2] The man speaking on the stage

[3] The best time to be alive

However, there are other examples that are rarely spoken about. Consider these:

[4] The time before he found his calling

[5] The moment after she discovered the truth

[6] Life as we know it

In the grammar resources that I have read, these types of clauses are always presented as adverbial, usually modifying a verb. Clearly, this is not their sole function. That being the case, are the examples above (4–6) correct? They are often used in both informal and formal English, so why do most resources neglect to mention them? If they are correct, would we class them as relative clauses?

A:
[1] the house [that I grew up in]
[2] the man [speaking on the stage]
[3] the best time [to be alive]
[4] the time [before he found his calling]
[5] the moment [after she discovered the truth]
[6] life [as we know it]

These are a mixed bag of noun phrases containing various modifiers (bracketed), but only two of the modifiers are relative clauses:
[1] is a genuine relative construction, where the modifier is a relative clause modifying "house".
[2] The modifier here is a non-finite participial clause modifying "man". It is semantically similar to the relative clause in the man who is/was speaking on the stage.
[3] contains the infinitival relative clause "to be alive", which modifies "best time". It has a modal meaning comparable to that expressed in finites by "can/could" or "should", cf. the best time that we could be alive.
The modifiers in [4] - [6] are not clauses at all, but preposition phrases where [4-5] have a temporal meaning, [6] a comparative one.


text:
Q: c++, boost: how to fill buffer and transfer (image) file data over network? I'm working on an application where I need to send a "filename", "filesize" and the filedata over the network. I created a server using boost which, for now, reads in the filesize and name.
I'm wondering how I can fill a buffer with the file data (if necessary) and how to transfer it to the server.
This is what I've got now:
#ifndef OFXFILETRANSFERSENDH
#define OFXFILETRANSFERSENDH

#undef check // necessary to get Boost running on Mac

#include <vector>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

#include "ofxFileTransferConnection.h"
using boost::asio::ip::tcp;
class ofxFileTransferSend : public boost::enable_shared_from_this<connection> {
public:
    typedef boost::shared_ptr<ofxFileTransferSend> pointer;
    static pointer create(
                        boost::asio::io_service& rIOService
                        ,std::string sServer
                        ,const char* sPort)
    {
        return pointer(new ofxFileTransferSend(rIOService,sServer, sPort));
    }

private:
    //--------------------------------------------------------------
    ofxFileTransferSend(
                    boost::asio::io_service &rIOService
                    ,const std::string sServer
                    ,const char* sPort
    )
        :port(sPort)
        ,socket_(rIOService)
        ,resolver_(rIOService)
    {

        tcp::resolver::query query(sServer, sPort);
        resolver_.async_resolve(
                            query
                            ,boost::bind(
                                    &ofxFileTransferSend::handleResolve
                                    ,this
                                    ,boost::asio::placeholders::error
                                    ,boost::asio::placeholders::iterator
                            )
        );
    }

    //--------------------------------------------------------------
    void handleResolve(
        const boost::system::error_code &rError
        ,tcp::resolver::iterator oEndPointIterator
    )
    {
        if (!rError) {
            tcp::endpoint end_point = *oEndPointIterator;
            socket_.async_connect(
                                end_point
                                ,boost::bind(
                                    &ofxFileTransferSend::handleConnect
                                    ,this
                                    ,boost::asio::placeholders::error
                                    ,++oEndPointIterator
                                )
            );
        }
        else {
            std::cout << "Error while resolving server: " << std::endl;
        }
    }

    //--------------------------------------------------------------
    void handleConnect(
        const boost::system::error_code &rError
        ,tcp::resolver::iterator rOEndPointIterator
    )
    {
        if(!rError) {
            std::cout << "Connected to remote server!" << std::endl;
            std::size_t size = 1235;
            std::ostream send_data_stream(&send_data);
            send_data_stream << "filename.jpg" << "\r\n";
            send_data_stream << size << "\r\n";

            boost::asio::async_write(
                            socket_
                            ,send_data
                            ,boost::bind(
                                &ofxFileTransferSend::handleSendFileInfo
                                ,this
                                ,boost::asio::placeholders::error
                            )
            );
        }
        else {
            // @todo on failure retry!
            std::cout << "Error connecting to ofxFileTransferServer:" << rError.message()<< std::endl;
        }
    }

    //--------------------------------------------------------------
    void handleSendFileInfo(
        const boost::system::error_code &rError
    )
    {
        if(!rError) {
            cout << "okay nice, send file data done!\n";
        }
        else {
            std::cout << "Error sending file info: " << rError.message() << std::endl;
        }
    }

    tcp::resolver resolver_;
    tcp::socket socket_;
    boost::asio::streambuf send_data;
    const char* port;
};
#endif

A: How about just dumping the file on the wire?  That's how HTTP does it.  In fact, I see you are using almost the same protocol as HTTP.  Send all metadata as clear text first (name, size, etc), put in an empty line as a terminator for the metadata (\r\n) and now all you need is to dump the file itself:
void handleSendFileInfo(
    const boost::system::error_code &rError
)
{
    if(!rError) {
        std::ofstream fileData(fileName);

        boost::asio::async_write(
                        socket_
                        ,fileData
                        ,boost::bind(
                            &ofxFileTransferSend::handleSendFileData
                            ,this
                            ,boost::asio::placeholders::error
                        )
        );
    }
    else {
        std::cout << "Error sending file info: " << rError.message() << std::endl;
    }
}


text:
Q: Trying to add ACF to authors meta and adding a class at the same time I am trying to add a an acf field called "name" while also adding a css-class to it
the_field('name')

to this code
if ($go_magazine_options['post_meta_author'] === 'enable' && in_the_loop()) {
    echo '' . get_the_field('name') .
   '' .
   esc_html(get_the_author()) . '' . "\n";
}

but something is not working?

A: Little Aprilia learns to code ;-)
was a silly idea to mix two things, justed added the ACF-Field, using its own if-rule
if( get_field('apri') ): ?>
<?php the_field('apri'); ?>
<?php endif;


text:
Q: How to create collection of abstract class type objects I'm writing a powershell script on Microsofts WHCK 2.0 API. I'm from perl background so do not know much in powershell or c#.
Well, my code is:
$ObjectModel  = [Reflection.Assembly]::LoadFrom($env:WTTSTDIO + "microsoft.windows.Kits.Hardware.objectmodel.dll")
$DbConnection = [Reflection.Assembly]::LoadFrom($env:WTTSTDIO + "microsoft.windows.Kits.Hardware.objectmodel.dbconnection.dll")
$Submission   = [Reflection.Assembly]::LoadFrom($env:WTTSTDIO + "microsoft.windows.Kits.Hardware.objectmodel.submission.dll")

And a little bit later.
   $List = New-Object "System.Collections.Generic.List``1[Microsoft.Windows.Kits.Hardware.ObjectModel.Target]"

When I run this code, it produces this error:
"New-Object: Cannot find type: [System.Collections.Generic.List`1[Microsoft.Windows.Kits.Hardware.ObjectModel.Target]]: make sure the aseembly containing this type is loaded."
I've verified that the aseemblies are loaded correctly, using CurrentDomain.getAssemblies() method.
Also I have verified that the type "Microsoft.Windows.Kits.Hardware.ObjectModel.Target" is present in "Microsoft.Windows.Kits.Hardware.ObjectModel.dll" assembly, as:
$ObjectModel.GetTypes() | % {
      if($_.FullName -eq "Microsoft.Windows.Kits.Hardware.ObjectModel.Target")
      {
          $found=1
      }
}

One more thing I would like to mention, "Microsoft.Windows.Kits.Hardware.ObjectModel.Target" this type/class is an abstract class.
I've searched a lot but couldnt get the right way to get rid of this error. Please suggest and help overcoming this error.

A: try this:
$List = New-Object 'System.Collections.Generic.List[Microsoft.Windows.Kits.Hardware.ObjectModel.Target]'


text:
Q: how to select one element in jQuery I am experimenting with a different kind of review system for my application. I have 5 radiobuttons with values 1 to 5, and every value represent a color.
If a user is going to review the movie "Batman: the dark knight", it would look something like this:

When a user clicks on a value, it changes the background-color. I am using jQuery to control this.
What the problem is: The user should only be able to choose one value and that only that value should change background-color, right now you change click any value and it change its background-color.
How can I do that in jQuery, any tips or ideas are welcome!
Here is a exempel in jsfiddle: http://jsfiddle.net/puWJZ/
HTML:

 <input id="#rb1" type="radio" value="1"   name="reviewbutton" /> Bad

 <input id="#rb2" type="radio" value="2"   name="reviewbutton" /> Acceptable

 <input id="#rb3" type="radio" value="3"   name="reviewbutton" /> Good

 <input id="#rb4" type="radio" value="4"   name="reviewbutton" /> Very good

 <input id="#rb5" type="radio" value="5"   name="reviewbutton" /> Excellent

POP UP!

CSS:
.input-check {
    display: block;
    height:20px;
    padding:10px;
    width:90px;
    color:#EEEEEE;
    font-weight: 600;
    text-align: center;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    background-color: #333333;
    margin:10px;
    cursor: pointer;
}
input {
    display:none;
}
.ch1:hover{background-color: #ba0012; cursor: pointer;}
.ch2:hover{background-color: #ba0099; cursor: pointer;}
.ch3:hover{background-color: #00ba88; cursor: pointer;}
.ch4:hover{background-color: #0bbdf0; cursor: pointer;}
.ch5:hover{background-color: #f0b10b; cursor: pointer;}

jQuery:
$(document).ready(function(){
    $('.box').hide();
    /* Bad */
    $('.ch1').click(function(){
        $(this).css({'background-color' : '#ba0012'});
        $('.box').show();
    });
    /* Acceptable */
    $('.ch2').click(function(){
        $(this).css({'background-color' : '#ba0099'});
        $('.box').show();
    });
    /* Good */
    $('.ch3').click(function(){
        $(this).css({'background-color' : '#00ba88'});
        $('.box').show();
    });
    /* Very good */
    $('.ch4').click(function(){
        $(this).css({'background-color' : '#0bbdf0'});
        $('.box').show();
    });
    /* Excellent */
    $('.ch5').click(function(){
        $(this).css({'background-color' : '#f0b10b'});
        $('.box').show();
    });
});

A: To reset the colors for the rest of the elements, just prepend:
$('.input-check').css('background-color',"");

to all your event handlers.
Here is a demonstration: http://jsfiddle.net/puWJZ/1/
Alternatively, you could add this event listener to the end of your code:
$('.input-check').click(function(){
    $('.input-check').not(this).css('background-color',"");
});

Here is a demonstration of the alternate approach: http://jsfiddle.net/puWJZ/3/

A: I don't really like the way that you are doing it, you don't need to create a function for each label. But I think that what you want to do is use the jQuery not selector Let me propose you a better way to do this:
$(document).ready(function(){
    var myColors=new Array('#ba0012', '#ba0099', '#00ba88', '#0bbdf0', '#f0b10b');
    $('.box').hide();
    $('.input-check').click(function(){
        $(this).css({'background-color' : myColors[$('.input-check').index($(this))]});
        $('.input-check').not($(this)).css({'background-color' : ''});
        $('.box').show();
    });
});

http://jsfiddle.net/puWJZ/7/

A: I would completely remove the inline CSS and toggle a class on your buttons instead. You already have all the css colors in your :hover styles, simply adding selectors to include an active class would make it a lot cleaner as it is much simpler removing a class than it is storing and reverting inline css
CSS sample
.ch1:hover, .ch1.selected {background-color: #ba0012; cursor: pointer;}

JS to change class:
$('.input-check').click(function(){
   $('.input-check.selected').removeClass('selected');
   $(this).addClass('selected');

     /* other code when clicked*/
})

A: As mentioned by the other answers, definitely go with one piece of code to handle the click event for all the buttons. Here I have added the bgcolor as a custom attribute to each radio button:
<input id="#rb1" type="radio" value="1"   name="reviewbutton" bgcolor="#ba0012"/> Bad

I have also added a class on all the input labels:

We then check for a click on any of these elements, get the bgbolor from the custom attributed and set it on the clicked element (and reset all other elements)
$(document).ready(function(){
    $('.box').hide();
    $('.rating_item').click(function(){
        $('.rating_item').each(function(){
            $(this).css("background-color","#333333");
        });
        var this_bg_color = $(this).children().attr("bgcolor");
        $(this).css('background-color',this_bg_color);
        $('.box').show();
    });
});

http://jsfiddle.net/UxyWq/3/

A: This is a very basic way of changing all the other colours back to their original colours.
$('.ch2, .ch3, .ch4, .ch5').css({'background-color' : '#333'});
http://jsfiddle.net/puWJZ/5/

A: Mark labels using classes and set that classes same as in hover css
css:
.ch1:hover,.ch1.checked{background-color: #ba0012; cursor: pointer;}
.ch2:hover,.ch2.checked{background-color: #ba0099; cursor: pointer;}
.ch3:hover,.ch3.checked{background-color: #00ba88; cursor: pointer;}
.ch4:hover,.ch4.checked{background-color: #0bbdf0; cursor: pointer;}
.ch5:hover,.ch5.checked{background-color: #f0b10b; cursor: pointer;}

js:
$(document).ready(function() {
    $('.box').hide();
    $('label.input-check input').click(function(e) {
        e.stopPropagation();
        $('label.input-check').removeClass('checked');
        //the reason for next string it is just to make same code compatible with checkboxes
        //if not needed it ok to set $(this).parent().addClass('checked');
        $('label.input-check input:checked').parent().addClass('checked');
    });
    $('label.input-check').click(function(e) {
        var $t = $(this);
        if ($t.attr('type') == 'radio') {
            return true;
        }
        $t.children().first().click();
    });
});

demo

other way to solve it is to make input same size as parent and set opacity to 0:

js:
$(document).ready(function() {
    $('.box').hide();
    $('label.input-check input').click(function(e) {
        $('label.input-check').removeClass('checked');
        //the reason for next string it is just to make same code compatible with checkboxes
        //if not needed it ok to set $(this).parent().addClass('checked');
        $('label.input-check input:checked').parent().addClass('checked');
    });

});

in css remove input and set this:
label.input-check input {
    width: 100%;
    height: 100%;
    opacity: 0;
    position: absolute;
}
.ch1:hover,.ch1.checked{background-color: #ba0012; cursor: pointer;}
.ch2:hover,.ch2.checked{background-color: #ba0099; cursor: pointer;}
.ch3:hover,.ch3.checked{background-color: #00ba88; cursor: pointer;}
.ch4:hover,.ch4.checked{background-color: #0bbdf0; cursor: pointer;}
.ch5:hover,.ch5.checked{background-color: #f0b10b; cursor: pointer;}

demo2


text:
Q: Backbone dynamically set collection view el after click on dom element the project is calendar where model is 1 day and collection contain all days from the month. The View is the same. So when i render my collection i have calendar on the screen. Now what i need, is to be able to set todo list in selected day. So i need another model,view and collection. My idea is that tasks from one day will be this day collection but - and there we go to the problem : how to set this new collection view "el" to element of the clicked day and its id. Each day has got the same class and unique id equal to  date -  like "2013.02.08"  I am not sure is it possible or maybe my approach is wrong and i should do this in another way. Edit - ok lets clarify :
I know that there in no collection of collections so how to do it ?
I have calendar on the screen - imagine 31 square divs.
I want a todo list in each of them - so it will be :
model of task
view of task {li element}
view of tasks {ul element}
collection of tasks {model:model}

in each of the squares. How to store all those collections ?


text:
Q: How do I refer to ASP.NET identity Usermanager inside of a static class? I want to create a new user during the seed method of the program but how do I call CreateAsync??
 public class DbInitializer
{
    private readonly UserManager<ApplicationUser> _userManager;

    public DbInitializer(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public static void Initialize(IApplicationBuilder app)
    {
        OneDbContext context = app.ApplicationServices.GetRequiredService<OneDbContext>();
        context.Database.EnsureCreated();

        //If there are no users, create a test user
        if (!context.Users.Any())
        {
            var user = new ApplicationUser { UserName = "test", Email = "test@test.com" };
            var result =  _userManager.CreateAsync(user, "test");
        }

error CS0120: An object reference is required for the non-static field, method, or property 'DbInitializer._userManager'


text:
Q: How can we call one route from another route with parameters in Flask? I am sending a POST request from one form with two inputs to a Flask route.
  <form action = "http://localhost:5000/xyz" method = "POST">

x <input type = "text" name = "x" />

y <input type = "text" name = "y" />

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

  </form>

The Flask code is like this.
@app.route('/xyz', methods = ['POST', 'GET'])
def xyz():
    if request.method == 'POST':
       x = request.form["x"]
       y = request.form["y"]
       callonemethod(x,y)
    return render_template('index.html', var1=var1, var2=var2)
       #abc(x,y) #can i call abc() like this .i want to call abc() immediately, as it is streaming log of callonemethod(x,y) in console.

@app.route('/abc', methods = ['POST', 'GET'])
def abc():
    callanothermethod(x,y)
    return render_template('index.html', var1=var3, var2=var4)
    #I want to use that x, y here. also want to call abc() whenever i call xyz()

How can I call one route from another route with parameters in Flask?

A: You have two options.
Option 1:
Make a redirect with the parameters that you got from the route that was called.
If you have this route:
import os
from flask import Flask, redirect, url_for

@app.route('/abc/<x>/<y>')
def abc(x, y):
  callanothermethod(x,y)

You can redirect to the route above like this:
@app.route('/xyz', methods = ['POST', 'GET'])
def xyz():
    if request.method == 'POST':
       x = request.form["x"]
       y = request.form["y"]
       callonemethod(x,y)
       return redirect(url_for('abc', x=x, y=y))

See also the documentation about redirects in Flask
Option 2:
It seems like the method abc is called from multiple different locations. This could mean that it could be a good idea to refactor it out of the view:
In utils.py
from other_module import callanothermethod
def abc(x, y):
  callanothermethod(x,y)

In app/view code:
import os
from flask import Flask, redirect, url_for
from utils import abc

@app.route('/abc/<x>/<y>')
def abc_route(x, y):
  callanothermethod(x,y)
  abc(x, y)

@app.route('/xyz', methods = ['POST', 'GET'])
def xyz():
    if request.method == 'POST':
       x = request.form["x"]
       y = request.form["y"]
       callonemethod(x,y)
       abc(x, y)


text:
Q: MySQL delete all but one record matching two column values I am cleaning up data in a MySQL database.
I would like to find rows that have the same "picture_id" value and a "date" value of "13-Jul-18". I would then like to delete all but ONE of the record matches for each picture_id.
Example:
id: 1 picture_id: 2 date: "13-Jul-18" followers: 4553
id: 2 picture_id: 2 date: "13-Jul-18" followers: 4552
id: 3 picture_id: 2 date: "13-Jul-18" followers: 4557
id: 4 picture_id: 2 date: "13-Jul-18" followers: 4577

id: 5 picture_id: 3 date: "13-Jul-18" followers: 4355
id: 6 picture_id: 3 date: "13-Jul-18" followers: 4351
id: 7 picture_id: 3 date: "13-Jul-18" followers: 4353
id: 8 picture_id: 3 date: "13-Jul-18" followers: 4374

would return:
id: 4 picture_id: 2 date: "13-Jul-18" followers: 4577
id: 8 picture_id: 3 date: "13-Jul-18" followers: 4374

It doesn't matter which of the records get deleted, only that there is one record left over after deleting for each picture_id.
Table Structure:
id
picture_id
date
followers

Here's what I have so far:
DELETE FROM `pictures` WHERE `date` = '13-Jul-18'

How can I accomplish this? Thanks!


text:
Q: Setting params on useEffect and getting the params it on createStackNav in React Navigation 5 I am working on an app where in I need to send or set a particular params of my state in an object.
Here's my object with its respected state:
   const [isGlutenFree, setIsGlutenFree] = useState(false);
    const [isLactoseFree, setisLactoseFree] = useState(false);
    const [isVegan, setIsVegan] = useState(false);
    const [isVegetarian, setIsVegetarian] = useState(false);

    const saveFilters = () => {
       const appliedFilters = {
          glutenFree: isGlutenFree,
          lactosFree: isLactoseFree,
          vegan: isVegan,
          isVegetarian: isVegetarian
       };
    };

These are all sitting on my FiltersScreen.js file. So on my useEffect I tried to use the CommonActions to set the params:
import { CommonActions } from '@react-navigation/native';

useEffect(() => {
    props.navigation.dispatch(CommonActions.setParams({ save: saveFilters }));
});

Then inside my Navigator.js file, I tried to receive this and console.log this on the screen to see that it has the data I need:
<FilterNav.Screen
                name="Filters"
                component={FiltersScreen}
                options={({ route }) => ({
                    title: 'Filters',
                    headerLeft: () => (
                        <HeaderButtons HeaderButtonComponent={HeaderButton}>
                            <Item
                                title='Menu'
                                iconName='ios-menu'
                                onPress={() => {
                                    navigation.toggleDrawer();
                                }}
                            />
                        </HeaderButtons>
                    ),
                    headerRight: () => (
                        <HeaderButtons HeaderButtonComponent={HeaderButton}>
                            <Item
                                title='Save'
                                iconName='ios-save'
                                onPress={() => {
                                    // CONSOLE LOG THE PARAMS SET >>
                                    console.log(route.params.save);
                                }}
                            />
                        </HeaderButtons>
                    )
                })}

            />
        </FilterNav.Navigator>

To be specific on this part:
 headerRight: () => (
                            <HeaderButtons HeaderButtonComponent={HeaderButton}>
                                <Item
                                    title='Save'
                                    iconName='ios-save'
                                    onPress={() => {
                                        // CONSOLE LOG THE PARAMS SET >>
                                        console.log(route.params.save);
                                    }}
                                />
                            </HeaderButtons>
                        )

But this doesn't work and doesn't return anything. Also it freezes all of my Switches.
Here's the complete code for FiltersScreen.js:
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Switch, Platform } from 'react-native';

import { CommonActions } from '@react-navigation/native';

import Colors from '../constants/colors';

const FiltersSwitch = props => {
    return(
    <View style={styles.filterContainer}>
        <Text>{ props.label }</Text>
        <Switch
            trackColor={{ true: Colors.primaryColor }}
            thumbColor={Platform.OS === 'android' ? Colors.primaryColor : ''}
            value={props.state}
            onValueChange={props.onChange} />
    </View>
    );
};

const FiltersScreen = props => {

    const [isGlutenFree, setIsGlutenFree] = useState(false);
    const [isLactoseFree, setisLactoseFree] = useState(false);
    const [isVegan, setIsVegan] = useState(false);
    const [isVegetarian, setIsVegetarian] = useState(false);

    // We will give this a connection with the
    // MealsNavigator in order to trigger this
    // function via useEffect
    const saveFilters = () => {
       const appliedFilters = {
          glutenFree: isGlutenFree,
          lactosFree: isLactoseFree,
          vegan: isVegan,
          isVegetarian: isVegetarian
       };
    };

    useEffect(() => {
        props.navigation.dispatch(CommonActions.setParams({ save: saveFilters }));
    });

    return (
        <View style={styles.screen}>
            <Text style={styles.title}>Available Filters / Restrictions</Text>
            <FiltersSwitch
                label="Glutten Free"
                state={isGlutenFree}
                onChange={newValue => setIsGlutenFree(newValue)} />

            <FiltersSwitch
                label="Lactose Free"
                state={isLactoseFree}
                onChange={newValue => setisLactoseFree(newValue)} />

            <FiltersSwitch
                label="Vegan"
                state={isVegan}
                onChange={newValue => setIsVegan(newValue)} />

            <FiltersSwitch
                label="Vegetarian"
                state={isVegetarian}
                onChange={newValue => setIsVegetarian(newValue)} />
        </View>
    );
}

const styles = StyleSheet.create({
    screen: {
        flex: 1,
        alignItems: 'center'
    },
    title: {
        fontFamily: 'poppins-bold',
        fontSize: 22,
        margin: 20,
        textAlign: 'center'
    },
    filterContainer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        width: '80%',
        marginVertical: 15
    }
});

export default FiltersScreen;

And here's the complete code for the navigation.js file:
const FilterNav = createStackNavigator();

const FiltersNavigator = () => {
    return (
        <FilterNav.Navigator
            mode="modal"
            screenOptions={{
                headerStyle: {
                    backgroundColor: Colors.primaryColor,
                },
                headerTintColor: '#fff',
                headerTitleStyle: {
                    fontSize: 17
                }
            }}
        >
            <FilterNav.Screen
                name="Filters"
                component={FiltersScreen}
                options={({ route }) => ({
                    title: 'Filters',
                    headerLeft: () => (
                        <HeaderButtons HeaderButtonComponent={HeaderButton}>
                            <Item
                                title='Menu'
                                iconName='ios-menu'
                                onPress={() => {
                                    navigation.toggleDrawer();
                                }}
                            />
                        </HeaderButtons>
                    ),
                    headerRight: () => (
                        <HeaderButtons HeaderButtonComponent={HeaderButton}>
                            <Item
                                title='Save'
                                iconName='ios-save'
                                onPress={() => {
                                    console.log(route.params.save);
                                }}
                            />
                        </HeaderButtons>
                    )
                })}

            />
        </FilterNav.Navigator>
    );
};

Please help how to solve this been stuck for a couple of time. I am using React Navigation 5.

A: I guess the "freeze" problem is that your useEffect is executing in every screen render, since it has no dependency array (read Tip: Optimizing Performance by Skipping Effects).
Your code should look something like this:
// useCallback, so it doesn't create a new saveFilters function in every render
const saveFilters = useCallback(() => {
  const appliedFilters = {
    glutenFree: isGlutenFree,
    lactosFree: isLactoseFree,
    vegan: isVegan,
    isVegetarian: isVegetarian
  };
}, [isGlutenFree, isLactoseFree, isVegan, isVegetarian]); // This function depends on those variables.

useEffect(() => {
  props.navigation.dispatch(CommonActions.setParams({ save: saveFilters }));
}, [saveFilters]); // It should change the parameterized function if it changes


text:
Q: aws-serverless-express connecting to mongo and get mongo document I am trying to make a Lambda proxy with express using the aws-serverless-express node module. However I keep getting the error 'Error: socket hang up' and I don't know why.
Here is my lambda code:
 const app = require('./app');
 const awsServerlessExpress = require('aws-serverless-express');
 const server = awsServerlessExpress.createServer(app);

 exports.handler = (event, context, callback) => {
  console.log('EVENT: ' + JSON.stringify(event));
  awsServerlessExpress.proxy(server, event, context);
}

and here is my express code:
MongoClient.connect("mongodb:/mongoUriGoesHere", function(err, db) {
if(err) { return console.dir(err); }

let collection = db.collection('collection');

app.get('/hello', (req, res) => {
 collection.find().toArray()
  .then((documents) => /* Handle success (console.log) */)
  .catch((err) => /* Handle error */)
 })
});

module.exports = app;

This is my response from the lambda
https://i.stack.imgur.com/Y0ybB.png
I know lambda functions are supposed to be stateless when creating a connection to a db, but I don't know how to get this to work. I've also tried using mongoose and no luck. I can get it to work when there is no code that attemps to connect to the db, but this is my problem at the moment. Any answers would be greatly appreaciated. Been at this for a while and still can't figure it out!

A: Lambda is a little strange in how it works under the hood and is not documented as well as it should be.
Lambda has hot and cold states. If it's not invoked for 15 minutes it goes cold otherwise it reuses certain parts of your code and your setup every time it is invoked and refreshes the hot state timeout.
Lambda will not re-execute the bits of your code that sit outside your handler function. Which means that the database connection code you defined will only run once and the code will try to re-use that connection for however long the lambda is hot.
So if there is a connection timeout on MongoClient then it's going to time out your connection but the connection code is not going to re-execute meaning you will get an error saying the expected connection cannot be utilized.
Why does all express code not work in this way?
It's because when you're defining your middleware e.g. app.get('/hello', (req, res) => {} this code is only instantiated inside of the lambda handler which means it will re-execute every time.
The only workaround for this problem that I could come up with is putting your connection command inside the express middleware like this:
app.use(async function (req, res, next) {
    await mongoose.connect(config.database.mongodb.url, dbConfig);

    res.on("finish", function () {
        if(mongoose.connection.readyState === 1){
            mongoose.connection.close();
        }
    });

    next();
});

This solution has drawbacks tho. If you have any asynchronous tasks running after you responded to the client then they'll fail because the db connection will be closed by then.
Have a look at https://mongoosejs.com/docs/lambda.html and see how they handle the connection. They reuse the same connection across all lambdas.

A: I think you have to return the awsServerlessExpress.proxy object


text:
Q: Change icon in Navigation Drawer on the fly I'm currently trying to change the icon in Navigation Drawer when some event occurs. Is it possible?? I mean that I change the icon - it's no problem:
    mDrawerToggle = new ActionBarDrawerToggle(
            this,
            mDrawerLayout,
            R.drawable.actionbar_settings,  /* my icon - all Ok! */
            R.string.text1,
            R.string.text2
    ) {};

I mean what to do if some event fires and I want to change this icon on another? If I repeat the code but with another icon - no success.
    mDrawerToggle = new ActionBarDrawerToggle(
            this,
            mDrawerLayout,
            R.drawable.new_icon_image,  /* bad news - nothing changes */
            R.string.text1,
            R.string.text2
    ) {};

Thanks a lot!

A:
Is it possible?

Yes, but you'll need to call DrawerLayout.setDrawerListener and ActionBarDrawerToggle.syncState to update the indicator and make sure it's synced.
Here's an example:
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
        R.drawable.new_icon_image, R.string.text1, R.string.text2);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();


text:
Q: Android phone not showing on Eclipse I've already looked at other questions with the same issue, but they all say to update the device drivers, well the driver for my phone is fully updated and it still won't show up in Eclipse, also my USB debugging IS activated. I also tried to make a virtual device but whenever I run the project the virtual device just stays on the shining android screen, but I would rather have the project run on my phone than in a virtual environment.
Used PDANet and this guide http://theunlockr.com/2009/10/06/how-to-set-up-adb-usb-drivers-for-android-devices/
Resolved the issue

A: I had also encountered that problem before but as installing Moborobo in my PC solved it.

A: try ---- first check ur phone is detect in DDMS if not then check ur mobile version then set mobile version to min target in android manifest ..


text:
Q: case insensitive for jTree I am kinda new in java because I mainly study autoIt language. I am trying to learn JTree and Action Listener. I have this code(actually came from internet: sorry I forgot the link.) which have a jTree sample and filtering for the search functionality. I tweaked a bit of the code so that I can understand it on my own. The code works perfectly fine. Tho, when I search, I need to input the exact word to be able to see the result. How can I make the search words case-insensitive(or I don't know what its called) to be able to search properly even if I did not input the exact word. I searched about toUpperCase and toLowerCase methods but I don't know how to implement it. Thanks in advance :D
Here's the code:
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public final class FilteredJTreeExample {

    public static void main(final String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

          @Override
          public void run() {
            createAndShowGUI();
          }
      });
    }
     private static void createAndShowGUI() {
        JFrame frame = new JFrame("I DONT KNOW IF THIS WILL WORK, BUT WHATEVER MAN!!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        addComponentsToPane(frame.getContentPane());

        frame.pack();
        frame.setVisible(true);
    }

    private static void addComponentsToPane(final Container pane) {
        pane.setLayout(new GridBagLayout());

        JTree tree = createTree(pane);
        JTextField filter = createFilterField(pane);

        filter.getDocument().addDocumentListener(createDocumentListener(tree, filter));
    }

    private static JTree createTree(final Container pane) {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("JTree");
        FilteredTreeModel model = new FilteredTreeModel(new DefaultTreeModel(root));
        JTree tree = new JTree(model);
        JScrollPane scrollPane = new JScrollPane(tree);
        GridBagConstraints c = new GridBagConstraints();
        c.weightx = 1;
        c.weighty = 1;
        c.fill = GridBagConstraints.BOTH;
        c.gridx = 0;
        c.gridy = 1;
        pane.add(scrollPane, c);
        createTreeNodes(root);
        expandTree(tree);

        return tree;
    }

    private static JTextField createFilterField(final Container pane) {
        JTextField filter = new JTextField();
        GridBagConstraints c = new GridBagConstraints();
        c.weightx = 0;
        c.weighty = 0;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;
        pane.add(filter, c);

        return filter;
    }

    private static DocumentListener createDocumentListener(final JTree tree, final JTextField filter) {
        return new DocumentListener() {

          @Override
          public void insertUpdate(final DocumentEvent e) {
            applyFilter();
          }

          @Override
          public void removeUpdate(final DocumentEvent e) {
            applyFilter();
          }

          @Override
          public void changedUpdate(final DocumentEvent e) {
            applyFilter();
          }

          public void applyFilter() {
            FilteredTreeModel filteredModel = (FilteredTreeModel) tree.getModel();
            filteredModel.setFilter(filter.getText());

            DefaultTreeModel treeModel = (DefaultTreeModel) filteredModel.getTreeModel();
            treeModel.reload();

            expandTree(tree);
          }
      };
    }

    private static void expandTree(final JTree tree) {
        for (int i = 0; i < tree.getRowCount(); i++) {
          tree.expandRow(i);
        }
    }

    private static void createTreeNodes(final DefaultMutableTreeNode node) {

        DefaultMutableTreeNode ojt1 = new DefaultMutableTreeNode("BOYSSS");
        ojt1.add(new DefaultMutableTreeNode("Rey"));
        ojt1.add(new DefaultMutableTreeNode("Regi"));
        ojt1.add(new DefaultMutableTreeNode("Geo"));
        ojt1.add(new DefaultMutableTreeNode("Jerome"));
        ojt1.add(new DefaultMutableTreeNode("Ryan"));
        ojt1.add(new DefaultMutableTreeNode("Leo"));
        ojt1.add(new DefaultMutableTreeNode("Ricardo"));
        node.add(ojt1);
        DefaultMutableTreeNode ojt2 = new DefaultMutableTreeNode("GIRLSS");
        ojt2.add(new DefaultMutableTreeNode("Neri"));
        ojt2.add(new DefaultMutableTreeNode("Chesca"));
        ojt2.add(new DefaultMutableTreeNode("Diane"));
        ojt2.add(new DefaultMutableTreeNode("Faye"));
        ojt2.add(new DefaultMutableTreeNode("Mimi"));
        ojt2.add(new DefaultMutableTreeNode("Shea"));
        ojt2.add(new DefaultMutableTreeNode("Shane"));
        ojt2.add(new DefaultMutableTreeNode("Lorraine"));
        node.add(ojt2);
  }
}

ohh btw, this is the FilteredTreeModel class:
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

public final class FilteredTreeModel implements TreeModel {

  private TreeModel treeModel;
  private String filter;

  public FilteredTreeModel(final TreeModel treeModel) {
    this.treeModel = treeModel;
    this.filter = "";
  }

  public TreeModel getTreeModel() {
    return treeModel;
  }

  public void setFilter(final String filter) {
    this.filter = filter;
  }

  private boolean recursiveMatch(final Object node, final String filter) {

    boolean matches = node.toString().contains(filter);

    int childCount = treeModel.getChildCount(node);
    for (int i = 0; i < childCount; i++) {
      Object child = treeModel.getChild(node, i);
      matches |= recursiveMatch(child, filter);
    }

    return matches;
  }

  @Override
  public Object getRoot() {
    return treeModel.getRoot();
  }

  @Override
  public Object getChild(final Object parent, final int index) {
    int count = 0;
    int childCount = treeModel.getChildCount(parent);
    for (int i = 0; i < childCount; i++) {
      Object child = treeModel.getChild(parent, i);
      if (recursiveMatch(child, filter)) {
        if (count == index) {
          return child;
        }
        count++;
      }
    }
    return null;
  }

  @Override
  public int getChildCount(final Object parent) {
    int count = 0;
    int childCount = treeModel.getChildCount(parent);
    for (int i = 0; i < childCount; i++) {
      Object child = treeModel.getChild(parent, i);
      if (recursiveMatch(child, filter)) {
        count++;
      }
    }
    return count;
  }

  @Override
  public boolean isLeaf(final Object node) {
    return treeModel.isLeaf(node);
  }

  @Override
  public void valueForPathChanged(final TreePath path, final Object newValue) {
    treeModel.valueForPathChanged(path, newValue);
  }

  @Override
  public int getIndexOfChild(final Object parent, final Object childToFind) {
    int childCount = treeModel.getChildCount(parent);
    for (int i = 0; i < childCount; i++) {
      Object child = treeModel.getChild(parent, i);
      if (recursiveMatch(child, filter)) {
        if (childToFind.equals(child)) {
          return i;
        }
      }
    }
    return -1;
  }

  @Override
  public void addTreeModelListener(final TreeModelListener l) {
    treeModel.addTreeModelListener(l);
  }

  @Override
  public void removeTreeModelListener(final TreeModelListener l) {
    treeModel.removeTreeModelListener(l);
  }
}

A: You are on the right track with the lowercase/uppercase idea.
Try this: boolean matches = node.toString().toLowerCase().contains(filter.toLowerCase())
Instead of: boolean matches = node.toString().contains(filter);
Note how we use .toLowerCase() on both strings that we want to match.


text:
Q: Нарушение прав доступа при записи по адресу C++ Выдает:

Вызвано исключение: нарушение доступа для записи.
_Left было 0xCCCCCCCC.

в строке getline(cin, book.id.strId);
Код программы:
struct product {
    string name;
    short type;
    union idVal{
        idVal() {};
        ~idVal() {};

        string strId;
        int intId;
    } id;
};

void a15() {
    product book;
    book.name = "Имя";
    cout << "Введите тип ID для продукта " << book.name << endl;
    cout << "0 - string; 1 - integer." << endl;
    cin >> book.type;

    cout << "Введите ID продукта: ";
    string input;
    switch (book.type)
    {
    case 0:
        getline(cin, book.id.strId);
        break;
    case 1:
        cin >> book.id.intId;
        break;
    }

    switch (book.type) {
    case 0:
        cout << book.id.strId << endl;
        break;
    case 1:
        cout << book.id.intId << endl;
    }
}

Как я понимаю, проблема именно в использовании объединения, чем можно заменить для корректной работы?
Upd.:
заменил код с первым свитчем на такой:
string input;
switch (book.type)
{
case 0:
    getline(cin, input);
    new (&book.id.strId) string(input);
    break;
case 1:
    cin >> book.id.intId;
    break;
}

Ну и в конце программы удаляю: book.id.strId.~basic_string();

A: 2 варианта:
switch (book.type)
{
case 0:
    new (&book.id.strId) std::string();
    std::cin.get();
    std::getline(std::cin, book.id.strId);
    break;
case 1:
    std::cin >> book.id.intId;
    break;
}

При использовании getline после cin не забывайте про то, что в буфере cin остается '\n', который и считывает geltine, возвращая пустую строку
switch (book.type)
{
case 0:
    std::cin.get();
    std::getline(std::cin, input);
    book.id.strId = input;
    break;
case 1:
    std::cin >> book.id.intId;
    break;
}

По поводу разрушения union-а, состоящего из неинтегральных типов можно прочитать тут (так же там есть и пример кода)


text:
Q: Pyinstaller - invalid syntax I am trying to use pyinstaller to package my script into an exe.
All sources indicate that the correct syntax is: pyinstaller FullClientCreator.py
When I issue this command, I get a syntax error:
pyinstaller FullClientCreator.py
  File "C:\Users\DAVIDM~1\AppData\Local\Temp/ipykernel_7368/3509825318.py", line 1
    pyinstaller FullClientCreator.py
                ^
SyntaxError: invalid syntax

I also tried it with the full path for the file, and I still get the same error:
pyinstaller "D:\Projects\ZZNew Client CreatorZZ\FullClientCreator.py"
  File "C:\Users\DAVIDM~1\AppData\Local\Temp/ipykernel_7368/546891165.py", line 1
    pyinstaller "D:\Projects\ZZNew Client CreatorZZ\FullClientCreator.py"
                ^
SyntaxError: invalid syntax

I am at a complete loss as to why this could be, so if anyone has any suggestions, I would greatly appreciate them.

A: Try another shell
I dont know which shell are you using but if you're using python shell sometimes its not working for python shell so try it on your cmd

pyinstaller --onefile file.py


text:
Q: In math mode, I have access to \veebar, but not \barvee? Why? As the title notes, I have access to \veebar, but \barvee produces an undefined control sequence error. These are the math related packages I am loading:
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amsfonts}
\usepackage{amssymb}

A: LuaTeX, XeTeX
Package unicode-math (requires LuaTeX or XeTeX) provides a \barvee (U+22BD NOR):
\tracinglostchars=2 % report, if a font misses a glyph
\documentclass{article}
\usepackage{unicode-math}
\begin{document}
  % Latin Modern
  \[ \veebar \barvee \]
  %
  \setmathfont{Asana-Math.otf}
  \[ \veebar \barvee \]
  %
  \setmathfont{xits-math.otf}
  \[ \veebar \barvee \]
  %
  \setmathfont{texgyrepagella-math.otf}
  \[ \veebar \barvee \]
  \setmathfont{texgyretermes-math.otf}
  \[ \veebar \barvee \]
\end{document}

Constructed solution
The following example constructs a \barvee from \vee and \minus with using the dimensions of \veebar:
\documentclass{article}
\usepackage{amssymb}
\usepackage{graphicx}

\makeatletter
\providecommand*{\barvee}{%
  \mathbin{%
    \mathpalette\@barvee{}%
  }%
}
\newcommand*{\@barvee}[2]{%
  % #1: math style
  % #2: unused
  \sbox0{$#1\veebar\m@th$}%
  \sbox2{%
    \hbox to \wd0{%
      \hss
      \resizebox{1.05\wd0}{\height}{$#1-\m@th$}%
      \hss
    }%
  }%
  \sbox4{%
    \resizebox{\wd0}{.7\ht0}{$#1\vee\m@th$}%
  }%
  \sbox6{$#1\vcenter{}$}
  \ht2=\ht6 %
  \vbox to \ht0{%
    \copy2 %
    \vss
    \copy4 %
  }%
}
\makeatother

\begin{document}
  \[ \veebar\barvee^{\veebar\barvee^{\veebar\barvee}} \]
\end{document}

Very poor man's solution using accent
There is an \bar accent that can be put over \vee. However the line is thinner and smaller than the line in \veebar:
\documentclass{article}
\usepackage{amssymb}

\begin{document}
  \[ \veebar \bar\vee \]
\end{document}

Poor man solution using \overline
1010011010 suggested to use \overline. An additional \mathbin is needed, because \overline strips this property from its contents.
\documentclass{article}
\usepackage{amssymb}

\providecommand*{\poorbarvee}{%
  \mathbin{%
    \overline{\vee}%
  }%
}

\begin{document}
  \[ a \veebar b \]
  \[ a \poorbarvee b \]
\end{document}

It also classifies as "poor man's solution", because

*

*the line is now too long, because it also covers the side bearings.

*As in the previous solution, the \vee part is too large, the gap too small

*and the line does not have round line caps.


text:
Q: How to ensure that the hibernate version number stays immutable in a javascript client? I have a Rest backend with Java and Hibernate and im using Optimistic Locking with the version property.
For concurrency control, this version property must go to the client and again to the server with post request.
But, in a javascript client i lose control over the integrity of this property, for example:

*

*A client "A" requests the resource 1.

*A client "B" requests the same resource.

*The server responds with resource 1 version 1 to both clients (in their respective responses)

*The client "A" modifies the resource and makes a post to save the changes.

*The server processes the post request and Hibernate checks version number. 1 = 1 so the resource is modified.

*The client B plays with javascript and modifies the version property to 2 and makes a post request.
The server processes the post request and now 2 = 2, so the resource is modified and the changes made by client A are lost.

Remember that is a Rest backend, therefore i can't save in the server the version number of the objects that were delivered to each user, o something like that.
So, if this is a valid question like i think it is, how can i ensure that the version stays immutable in the client?

A: Personally, I would rethink doing this, as I see little to no motivations for a client to do that and by definition you can NOT control what a client sends to your REST service.
However, if you really do have a business case, then one semi-solution is to make the version property a GUID.  That way, you can only submit if you have the newest GUID, which client B would not have, and it makes the versioning case more complicated because you cannot just increment by 1 until the request succeeds.
However, even there you are not entirely safe, as client B could theoretically do a separate request to get the updated GUID from the resource and then resubmit the failed request with the updated GUID.
But since client B could have done an edit on the updated version to revert what client A did and add their own, this is essentially the same as doing that, and since they have authority to do that, we are back to asking ourselves why we are worrying about that case in the first place again.

A: Use a constructor that hides the number behind a read-only getter:
var MyObject = function(version) {
    var _version = version;

    this.getVersion = function() { return _version; }
}

Or, use a getter and setter pair that allows for the variable to be set only once:
var MyObject = function() {
    var self = this;

    var _tripwire = false;

    var _value = null;

    self.setValue = function(val) {
        if (_tripwire==false)
            _tripwire = true;
        else
            throw "Value is read-only";

        _value = val;
    };

    self.getValue = function() {
        return val;
    }
};

JSFiddle
Depending on how you want it to fail, you could replace the throw statement with a return that silently eats the property set, but for API code, when the caller does something profoundly unsafe, it's better to die loudly and proudly.
Note that, if you prefer the property-style access method, you can also accomplish the same design pattern with property accessors:
function setOnceProp(o, name) {
    var _value = null;

    var _tripwire = false;

    Object.defineProperty(o, name, {
        get: function() {
            return _value;
        },
        set: function(newValue) {
            if (_tripwire==false)
                _tripwire = true;
            else
                throw "Value is read-only";

            _value = newValue;
        },
        enumerable: true
    });
}

var MyObject = function() {
    var self = this;

    setOnceProp(self, 'value');
};

This does require that your clients are using relatively recent browsers.


text:
Q: Get every 100th record starting from the top I have a table earnings with 4436 records with two columns - no_id (which is unique) and payments.
I want to extract a query which will give a row of start & end column with a gap of 100. the gap of hundred can be varied depending upon user input and can be anything between 1-250.
Original Table
no_id, payments

4436, 7540

4435, 7900

4434, 8000

4433, 4500
'
'
'
'

1,2000

I am expecting the output something like this-
start, end
4436,4337

4336,4237

4236,4137

4136,4037

I writing a join statement. I am looking to check where I am wrong and what I need to correct.
SELECT (table2.no_id*100)-100+1 as start, table1.no_id as end,
table1.payments FROM earnings as table1, earnings as table2
WHERE (table1.no_id= table2.no_id*100 AND table2.no_id>MOD(t2.max_no,100))

JOIN

(SELECT max(t2.no_id) as max_no FROM  earnings as t2)

A: You could join on querying the max(no_id), like you did, and check the difference between it and the row's no_id. Assuming the gap is 100:
SELECT   no_id AS `start`, no_id - 100 + 1 AS `end`
FROM     my_table
JOIN     (SELECT MAX(no_id) AS max_no_id
          FROM   my_table)
         ON (max_no_id - no_id) % 100 = 0
ORDER BY no_id DESC


text:
Q: I have a button in my index.html ,open that html and want to perform on click action using the button and redirect it to different page If the button inside index.html has id, then how to call onclick on that button inside java application using that id.
Here is the Java Code:
public class Abcd extends Application {

  public static void main(String[] args) {
    launch(args);
  }

  @Override
  public void start(Stage primaryStage) {
    primaryStage.setTitle("fdg");
    StackPane root = new StackPane();

    webView = new WebView();
    webEngine = webView.getEngine();
    URL urlHello = getClass().getResource("/2/index.html");
    webEngine.load(urlHello.toExternalForm());
    root.getChildren().add(webView);
    scene = new Scene(root);
    primaryStage.setScene(scene);
    primaryStage.show();
  }
}


text:
Q: How to detect a rectangle (whiteboard) in an image using opencv? I have the following image. I want to detect and perspective transform the rectangular whiteboard.

I want to detect these 4 boundaries/corners and apply a perspective transformation to it. Have a look at the below image:

I am not able to detect the boundaries of the rectangle. Here's what I have tried:
import cv2, os
import numpy as np
from google.colab.patches import cv2_imshow

image = cv2.imread("img.jpg")
orig1 = image.copy()
# 1) Grayscale image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# cv2_imshow(gray)
# 2) Erosion
kernel = np.ones((5, 5), np.uint8)
erosion = cv2.erode(gray, kernel, iterations = 1)
# cv2_imshow(erosion)

# 3) Thresholding (OTSU)
blur = cv2.GaussianBlur(erosion, (5,5),0)
ret3, thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# cv2_imshow(thresh)

# 4) Contours
copy = thresh; orig = image;
cnts = cv2.findContours(copy, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
area = -1; c1 = 0
for c in cnts:
    if area < cv2.contourArea(c):
        area = cv2.contourArea(c)
        c1 = c
cv2.drawContours(orig,[c1], 0, (0,255,0), 3)

epsilon = 0.09 * cv2.arcLength(c1,True)
approx = cv2.approxPolyDP(c1,epsilon,True)

if len(approx) != 4:
    # Then it will fail here.
    pass
cood = []
for i in range(0, len(approx)):
    cood.append([approx[i][0][0], approx[i][0][1]])

# 5) Perspective Transformation
def reorder(myPoints):
    myPoints = np.array(myPoints).reshape((4, 2))
    myPointsNew = np.zeros((4, 1, 2), dtype=np.int32)
    add = myPoints.sum(1)
    myPointsNew[0] = myPoints[np.argmin(add)]
    myPointsNew[3] =myPoints[np.argmax(add)]
    diff = np.diff(myPoints, axis=1)
    myPointsNew[1] =myPoints[np.argmin(diff)]
    myPointsNew[2] = myPoints[np.argmax(diff)]
    return myPointsNew

pts1 = np.float32(reorder(cood))
w = 1000; h = 1000; m1 = 1000; m2 = 1000
pts2 = np.float32([[0, 0], [w, 0], [0, h], [w, h]])
matrix = cv2.getPerspectiveTransform(pts1, pts2)
result = cv2.warpPerspective(orig1, matrix, (m1, m2))
cv2_imshow(result)

I have also gone through Microsoft's research, but not sure how to implement it.
I am not able to detect and perspective transform the board. It would be great if anyone of you can help me out. Also, do let me know if my question requires more details.

A: I manage to get the 4 coordinates of the whiteboard. I have used adaptive thresholding to detect the edges rather than canny-edge detection, not sure whether the methodology is correct or not, but it is giving the required results.
Here's the code for the same.
import ...
img = cv2.imread("path-to-image")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 199, 5)
cv2_imshow(thresh)

# finding contours and applying perspective
try:
    copy = thresh.copy(); orig = img.copy()
    cnts = cv2.findContours(copy, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    area = -1; c1 = 0

    for c in cnts:
        epsilon = 0.01 * cv2.arcLength(c,True)
        approx = cv2.approxPolyDP(c,epsilon,True)
        if len(approx) == 4 and area < cv2.contourArea(c):
            area = cv2.contourArea(c)
            c1 = c; approx1 = approx

    warped = four_point_transform(orig, approx1.reshape(4, 2))
    cv2_imshow(warped)
except:
    print("Image cannot be transformed!!\n")

# four point transform
def order_points(pts):
    # https://www.pyimagesearch.com/2016/03/21/ordering-coordinates-clockwise-with-python-and-opencv/
    xSorted = pts[np.argsort(pts[:, 0]), :]
    leftMost = xSorted[:2, :]
    rightMost = xSorted[2:, :]
    leftMost = leftMost[np.argsort(leftMost[:, 1]), :]
    (tl, bl) = leftMost
    D = dist.cdist(tl[np.newaxis], rightMost, "euclidean")[0]
    (br, tr) = rightMost[np.argsort(D)[::-1], :]
    return np.array([tl, tr, br, bl], dtype="float32")

def four_point_transform(image, pts):
    # https://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/
    rect = order_points(pts)
    (tl, tr, br, bl) = rect
    widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
    widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
    maxWidth = max(int(widthA), int(widthB))
    heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
    heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
    maxHeight = max(int(heightA), int(heightB))
    dst = np.array([
        [0, 0],
        [maxWidth - 1, 0],
        [maxWidth - 1, maxHeight - 1],
        [0, maxHeight - 1]], dtype = "float32")
    M = cv2.getPerspectiveTransform(rect, dst)
    warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
    return warped

Here's the warped image:


text:
Q: SurfaceView crashes on close My custom SurfaceView class crashes when i try to end the application. When pressing "home" or "back" the application will end, but notifying me: "'game' has crashed"
how do i end a surfaceview properly?
Thanks in advance
logcat:
02-12 23:51:07.661: D/OpenGLRenderer(32561): Enabling debug mode 0
02-12 23:51:09.450: W/dalvikvm(32561): threadid=11: thread exiting with uncaught exception (group=0x41eaeb90)
02-12 23:51:09.450: E/AndroidRuntime(32561): FATAL EXCEPTION: Thread-1321
02-12 23:51:09.450: E/AndroidRuntime(32561): Process: com.ochs.x, PID: 32561
02-12 23:51:09.450: E/AndroidRuntime(32561): java.lang.NullPointerException
02-12 23:51:09.450: E/AndroidRuntime(32561):    at android.view.SurfaceView.dispatchDraw(SurfaceView.java:343)
02-12 23:51:09.450: E/AndroidRuntime(32561):    at android.view.View.draw(View.java:14436)
02-12 23:51:09.450: E/AndroidRuntime(32561):    at android.view.SurfaceView.draw(SurfaceView.java:334)
02-12 23:51:09.450: E/AndroidRuntime(32561):    at com.ochs.x.GameView.draw(GameView.java:109)
02-12 23:51:09.450: E/AndroidRuntime(32561):    at com.ochs.x.GameThread.run(GameThread.java:25)
02-12 23:51:09.575: W/IInputConnectionWrapper(32561): showStatusIcon on inactive InputConnection

And this is my drawing method:
public void draw(Canvas canvas) {
    super.draw(canvas);
    Paint textPaint = new Paint();
    textPaint.setColor(Color.BLACK);
    textPaint.setTextSize(30);
    canvas.drawColor(Color.WHITE);
    canvas.drawText("mX: " + mx, 10, 30, textPaint);
    canvas.drawText("mY: " + my, 10, 70, textPaint);
    canvas.drawText("calX: " + calibrationX, 10, 110, textPaint);
    canvas.drawText("calY: " + calibrationY, 10, 150, textPaint);

}

I already had the same problem some months ago but I forgot how to properly close an activity containing a custom surfaceview...


text:
Q: Object fixed below certain point This is my first post here, before this I have had tremendous help from this forum and all the users previous posts. The question I have now I cannot find the answer to. So:
I have an object (button) which when pressed smoothscrolls the user up to top of the page. Im successful in making it fixed to the top of the screen, however, lets say youre at the bottom of the page and you press the "smoothscroll button", its starts scrolling you upwards to the top. But when your "near" the top I want the button to stop and the scrolling to continue...
Im not sure how to describe it better, but if you go from the top of the page, or when at the top of the page, you dont see the button and when you start scrolling down, youll see the button as any object on the screen "climbing upwards" and when the button reaches the top of the screen it stays there fixed.
Im sure this is common on ads for example..
How would you achieve this? Any help appreciated..
Thx,
Layman

A: It seems like this is what you want to achieve.
http://stickyjs.com/
if you are still not impressed.. here is a link to the treasure of plugins that would do what you need with very little code.
http://jquery-plugins.net/tag/sticky-scroll

A: One of my coworkers wrote a plugin that hides a button as the page is being scrolled to the top. You may be able to use similar logic. It would be something like this:
btt.revealPosition = 300;
$(window).scroll(function(){
        if($(window).scrollTop() >= btt.revealPosition){
            //Add a class here that lets the button scroll with the page
        }else{
            //Add a class here that fixes the button to the top of the page

        }
    });

It basically watches the scroll position as you're scrolling back to the top of the page. Upon reaching the revealPosition of the button, you could add a class or modify the css with jquery to change how the button is acting.
This logic was taken from the following plugin:
jquery-backtotop


text:
Q: dropdown value changed by javascript is not coming in codebehind I have a dropdown list whose value is changed based on other controls in the UI using javascript.
I used the following code to change the dropdown list,
document.getElementById("ddlchkStsID").options[2].selected = true;
 document.getElementById("ddlchkStsID").value = "3";
But in the code-behind, the ddlchkStsID.SelectedValue is still coming as first option's value.
This the control in aspx page.
<asp:DropDownList ID="ddlchkStsID"  runat="server" TabIndex="10"  CssClass="meta">
 <asp:ListItem Text="TBD" Value="1" />
 <asp:ListItem Text="Yes" Value="2" />
 <asp:ListItem Text="No" Value="3" />
</asp:DropDownList>

Could someone help me how to get the changed value in the code-behind.
thanks in advance :)

A: Since the control is running at the server, you should be referencing the control using the ClientID, like this:
document.getElementById("<%=ddlchkStsID.ClientID%>").options[2].selected = true;

Is your JavaScript code actually working?


text:
Q: insert data in mongodb with python this is my first shot at using dbs and I'm having some trouble with the basics. Tried to look online but couldnt find answers to simple questions. When I try to add some info to my db, I get a whole bunch of errors.
import pymongo

def get_db():
    from pymongo import MongoClient
    client = MongoClient("mongodb://xxxxxx:xxxxxx@ds029735.mlab.com:29735/xxxxxxx")
    db = client.myDB
    return db

def add_country(db):
    db.countries.insert({"name": "Canada"})

def get_country(db):
    return db.contries.find_one()

db = get_db()
add_country(db)

I got this error message:
File "/Users/vincentfortin/Desktop/Python_code/mongo.py", line 21, in <module>
    add_country(db)
  File "/Users/vincentfortin/Desktop/Python_code/mongo.py", line 11, in add_country
    db.countries.insert({"name": "Canada"})
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymongo/collection.py", line 2212, in insert
    check_keys, manipulate, write_concern)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymongo/collection.py", line 535, in _insert
    check_keys, manipulate, write_concern, op_id, bypass_doc_val)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymongo/collection.py", line 516, in _insert_one
    check_keys=check_keys)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymongo/pool.py", line 239, in command
    read_concern)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymongo/network.py", line 102, in command
    helpers._check_command_response(response_doc, None, allowable_errors)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymongo/helpers.py", line 205, in _check_command_response
    raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: not authorized on myDB to execute command { insert: "countries", ordered: true, documents: [ { _id: ObjectId('579a6c6ed51bef1274162ff4'), name: "Canada" } ] }

A: *

*Check twice if your xxxxxxx from ds029735.mlab.com:29735/xxxxxxx is equal to myDB from db = client.myDB. I mean if your connection string is mongodb://username:password@ds029735.mlab.com:29735/xyz then your code should be db = client.xyz and not db = client.zyx (or other names).

*Check in mLab control panel if your user is Read-Only http://i.imgur.com/It32S1d.png
Both of these issues returns errors like your so I don't know with which one you have faced.

A: from pymongo import MongoClient

#import json

client = MongoClient('localhost', 27017)
mydb = client.db_University

def add_client(student_name, student_age, student_roll, student_branch):
    unique_client = mydb.students.find_one({"name":student_name}, {"_id":0})
    if unique_client:
        return " already exists"
    else:
        mydb.students.insert(
                {
                "name" : student_name,
                "age" : student_age,
                "roll no" : student_roll,
                "branch" : student_branch,

                })
        return "student added successfully"

student_name = raw_input("Enter stuent Name: ")
student_age = raw_input("Enter student age: ")
student_roll = raw_input("Enter student roll no: ")
student_branch = raw_input("Enter student branch: ")

print add_client(student_name,student_age,student_roll,student_branch)

def view_client(student_name):
    user = mydb.students.find_one({"name":student_name}, {"_id":0})
    if user:
        name = user["name"]
        age = user["age"]
        rollno = user["roll no"]
        branch = user["branch"]

        return {"name":name,"age":age,"roll no":rollno,"branch":branch}
    else:
        return "Sorry, No such student exists"

user = raw_input("Enter student name to find: ")
user_data = view_client(user)

print user_data


text:
Q: Bootstrap : Is there a relatively simple way to make my pages workable on mobile? I am working on my first "handmade" (i.e. not WordPress) site. Building it with Django/Python and Bootstrap 4. Even though I wrote in the contract that I am not obligated to make the site mobile friendly, the client is demanding that it work on mobile (client... amirite?).
I am looking for some fairly simple ways to make the site work better on mobile.
I am going to focus on one page, our login screen. It's kind of hard to describe, so I am including a few screenshots to show you what happens as the viewport gets smaller.

So... I feel that there's a solution to be had between (1) making the top navbar switch to a mobile-style navbar at some break point and (2) programming it to preserve the padding at the top of the main div, so that the navbar "pushes the content down" rather than covers it over.
Can you help?
Here is the pertinent code:

/*navbar:*/
.brand {
 margin-bottom: 0px;
}

h5.brand {
 color: #e3f2fd;
 font-family: "Arial";
}

.navbar {
 background-color: #2c3b4b;
}

a.nav-link {
 color: white;
}

a.active {
 color: #808080;
}

.navbar .navbar-nav li a:hover {
 color: #808080;
}

/*Main container*/

.container-fluid {
 background-color: #fffef7;
 padding: 0;
}

/*Form:*/
#form-container h3 {
 color: black;
}

#form-container {
 padding: 30px;
   max-width: 350px;
   width: 100%;
   background-color: #fffef7;
   margin: 0 auto;
   border-radius: 4px;
   box-shadow: 8px 8px 5px #36454f;
   overflow: hidden;
   margin-bottom: 80px;
}

.panel-heading {
 text-align: center;
}

.panel-default {
 padding-bottom: 50px;
}

.login-links {
 padding-top: 20px;
}

.login-links a {
 font-size: 16px;
}

.btn-reg {
 margin-top: 40px;
}

/*Footer:*/
footer {
 background-color: #2c3b4b;
 padding-top: 30px;
 padding-bottom: 4px;
 padding-left: 30px;
}

.footer-row {
 margin: 0;
}

#footer-container {
 padding: 0;
}

.container2 {
 text-align: center;
}

.container2 p {
 color: white;
}

.container1 h5 {
 color: white;
}

.container1 h4 {
 color: white;
}

.container1 p {
 color: white;
}

.footer-links li a:hover {
    text-decoration: none;
    /*border-bottom: 6px solid white;*/
}

.footer-links li a h5:hover {
    color: #808080;
    /*border-bottom: 3px solid white;*/
}
{% extends 'public_base.html' %}
{% load static %}

{% block load_css %}
    <link rel="stylesheet" type="text/css" href='{% static "css/login.css" %}'>
{% endblock %}

{% block header %}

Houston Chamber Music Network

                    WELCOME

                    REGISTER AS MEMBER

                    REGISTER AS COACH

                    LOGIN

{% endblock %}

{% block main_content %}

                            <form role="form" action="{% url 'users:login_handler' %}" id="form-container" method="post">
                                {% csrf_token %}

MEMBER LOG IN

                                            <input type="text" name="email" id="email" class="form-control input-sm" placeholder="Email" value="{{ old_data.email }}">

                                            <input type="password" name="password" id="password" class="form-control input-sm" placeholder="Password">

                                            <input type="submit" value="LOGIN" class="btn btn-reg btn-info btn-block">

                                            Forgot Password?

                            </form>

{% endblock %}

A: Try this:
<meta name="viewport" content="width=device-width, initial-scale=1">

The grid manager should do most of the work for you if not I use media queries where there are options for the different orientations that a cell phone would provide.
here is an example:
@media screen only and (max_width: 350px), (orientation: portrait or landscape) {
 #Your ID or tag {

  }
}

The grid managers should provide most of the functionality to getting your layout in the right place. If this does not work also try specifying more column sizes.
class="col-xl-6 col-lg-6 col-md-6 col-sm-6"

I understand that if you just specify the medium column size that it could make the element responsive but being more specific with what you want to do with your layout at specific pixels sizes can make all the difference.
Hope this helped :)

A: As Braiden said, using the col classes from the Bootstrap library will help you.
A basic rundown and layout would look something like this

Some html in here perhaps a form

Some other html in here

Essentially each row div consists of 12 columns. 2 col-md-6 will result in a 50/50 split of 2 divs within the parent row. col-sm col-md col-lg etc have different defining characteristics for sizing as it pertains to padding and height etc. You will still need to create your own hamburger menu using a similar css layout as provided in the answer above (@media) as well as font sizes and paddings, but overall the row col setup should help with keeping things together as far as mobile layouts go


text:
Q: Figure eight shaped head I'm desperately trying to find a book series I had gotten as a kid in the early-mid 90's. This is all that I can remember about them:

*

*The books were paperback, all with dark or black covers

*Most likely young adult horror

*There are illustrations at the back of the monsters/aliens in the book. One I remember has an eight shaped head and is also described as such in the book

*There is also a monster that resembles a "Gremlin" (the ugly green version, not the cute cuddly version) and I think he/it is the host of the book series


text:
Q: Qual a melhor opção para escapar uma string antes de inserir na base de dados. addslashes() ou mysql_real_scape_string()? Estou a desenvolver um projeto que envolve palavras pass entre outras infomações importante que preciso de inserir na base de dados mysql.
A minha dúvida é qual a opção que devo usar para escapar esses dados contra sql injection. Neste momento estou a usar uma expressão regular que retira os caractéres indesejados. Estou a usar o PDO.

A: mysql_real_scape_string() deve ser descartada por ser obsoleta, removida do php7 e por necessitar de uma conexão mysql_*.
Deixe que o PDO se encarregue de escapar os caracteres utilizando prepared statements.
Leitura recomendada:
Usar o addslashes contra injeção de SQL é seguro?
Como prevenir injeção de código SQL no meu código PHP
Usar PDO é a maneira mais segura de se conectar a um BD com PHP?


text:
Q: How to create docker images for a system with multiple applications I have installed and configured a system in EC2s using Ansible. It is 1 EC2 master with a few EC2 workers. Sometimes when I use ansible to update or reinstall configuration, it fails because either some package has been removed from open-source repositories, or the package is updated so not compatible with some other packages. And I learned that using docker-container can resolve these kind of configuration problems.
However, according to what I learned, each docker image will create image of one application (I guess one application means one process). But mine is a system which has airflow master webserver, airflow worker webserver, flower webserver, rabbitmq, airflow celery, several configuration files, etc. how can I create docker images for that? Should I create one docker image for each process? How do I know which linux folder should I go to create each docker image? How do I know which applications/processes I need to create? And how to combine these images to make them work together as a system?
Or maybe in my case I should not use docker image, Instead I should just create an EC2 image?

A: Use docker-compose.

Compose is a tool for defining and running multi-container Docker applications

https://docs.docker.com/compose/

each docker image will create image of one application (I guess one application means one process)

That is basically correct. You should create one docker-container per application. In theory you can have multiple process per container, but that doesn't matter in this case.

how can I create docker images for that?

In your case you should make one docker-container for airflow master webserver, one for airflow worker webserver, one for flower webserver, etc. And the you use a docker-compose.yml to link them all together.

Should I create one docker image for each process?

generally yes. (It may depend on your exact setup though)

And how to combine these images to make them work together as a system?

docker-compose.

How do I know which linux folder should I go to create each docker image?

I don't understand that question

How do I know which applications/processes I need to create?

You could create a deployment-diagram and then start from there.


text:
Q: Multipart upload of streaming voice to S3 I've managed to use webrtc to capture voice from the browser, MP3 encode client side, and stream over websocket to Ruby/Faye/Puma on heroku.  This is nice because there is no upload step after taking a long recording.
Now I want to stream to S3 as the recording is in progress.  You can't append to an S3 file but there are plenty of suggestions that you can send 5MB chunks, one-by-one, in a multipartupload.
I can't make sense of the docs or source for Aws-sdk-ruby V2.  It seems to want a whole file and to manage chunks under the hood.
Any clues?

A: I managed to figure it out but seems a little wonky. The object hierarchy is all over the shop.  No doubt I'm doing it wrong.
@s3 = Aws::S3::Resource.new()
@bucket = @s3.bucket(bucket_name)
@object = @bucket.object(file_name)
@upload = @s3.client.create_multipart_upload({bucket: bucket_name, key: @object.key})

part1 = {data: "my 1st 5MB chunk", part_number: 1}
part1[:output] = @s3.client.upload_part(body: part1[:data], bucket: bucket_name, key: @object.key, part_number: part1[:part_number], upload_id:@upload.upload_id)
part1[:etag] = part[:output][:etag]

part2 = {data: "my final chunk of any size", part_number: 2}
part2[:output] = @s3.client.upload_part(body: part2[:data], bucket: bucket_name, key: @object.key, part_number: part2[:part_number], upload_id:@upload.upload_id)
part2[:etag] = part[:output][:etag]

@object.multipart_upload(@upload.upload_id).complete(compute_parts: true)


text:
Q: Why isn't my Wordpress menu working correctly? I'm actually following along with a Lynda.com video about building a Wordpress website from scratch using Underscores.
We're designing the drop-down menu in the style.css.
The default code looked like this and worked fine:
.main-navigation ul ul {
    box-shadow: 0 3px 3px rgba(0, 0, 0, 0.2);
    float: left;
    position: absolute;
    top: 1.5em;
    left: -999em;
    z-index: 99999;
}

but, since we needed to change the look, he instructs us to change it to this code, instead:
.main-navigation ul ul {
    position: absolute;
    left: 0;
    z-index: 99999;
    display: none;
    float: left;
    padding: 0;
    background: #4d4d4d;
    background: hsl(0, 0%, 30%);
}

Suddenly, the drop-downs are non-responsive.
I think I pinpointed the problem to the "display: none;" but taking that out just causes a mess. I tried just adding the background color like this:
.main-navigation ul ul {
    box-shadow: 0 3px 3px rgba(0, 0, 0, 0.2);
    background: #4d4d4d;
    background: hsl(0, 0%, 30%);
    float: left;
    position: absolute;
    top: 1.5em;
    left: -999em;
    z-index: 99999;
}

but it ends up looking like this:

Obviously, I want this drop down below the links, not in front. Can anyone tell me how to fix this issue?
EDIT: I appreciate the people who tried answering so far but neither of the answers were correct. Thanks to David, I put my code into jsfiddle.net: http://jsfiddle.net/DMDesigns/5g9kbf9s/2/
Please let me know if one of you can figure it out, using this! Thank you!

A: with left: -999em; and display: none; contents are disappearing
.main-navigation ul ul {
    box-shadow: 0 3px 3px rgba(0, 0, 0, 0.2);
    background: #4d4d4d;
    float: left;
    position: fixed;
    top: 1.5em;
    left: 1.5em;
    z-index: 99999;
}

A: Use the left position's value used in the original code:
.main-navigation ul ul {
box-shadow: 0 3px 3px rgba(0, 0, 0, 0.2);
background: #4d4d4d;
background: hsl(0, 0%, 30%);
float: left;
position: absolute;
top: 1.5em;
left: 0;
z-index: 99999;

}

and not:
.main-navigation ul ul {
box-shadow: 0 3px 3px rgba(0, 0, 0, 0.2);
background: #4d4d4d;
background: hsl(0, 0%, 30%);
float: left;
position: absolute;
top: 1.5em;
left: -999em;
z-index: 99999;
}

A: I'm still not sure why his code was breaking the site but I did solve the problem I was having. I thought I should post it, just in case anyone else has a similar issues.
I left the code as it was, but added the background color and changed "top" from 1.5em to 3em to have it load correctly.
.main-navigation ul ul {
box-shadow: 0 3px 3px rgba(0, 0, 0, 0.2);
float: left;
position: absolute;
top: 3.0em;
left: -999em;
z-index: 99999;
background: #9adcfd;

}
Thanks for everyone who tried!


text:
Q: Reduce objects to objects and arrays when Express query returns multiple objects on a many to many query I have some SQL queries that I'm running return multiple objects when we have a many to many mapping in express, I'm trying to find a tool to reduce common objects to have nested arrays of objects.
ie.
SELECT *
FROM User
LEFT JOIN UserAddress ON UserAddress.user_id = User.user_id
LEFT JOIN Address ON Address.address_id = UserAddress.address_id;

we get a response of
[
  {
    "user_id": 1,
    "name": "test name",
    "address_id": 1,
    "address": "1234 address way"
  },
  {
    "user_id": 1,
    "name": "test name",
    "address_id": 2,
    "address": "5678 new address"
  },
  {
    "user_id": 2,
    "name": "diff name",
    "address_id": 1,
    "address": "1234 address way"
  }
]

and I would like to use a tool in javascript that will reduce the array of objects to look like this
[
  {
    "user_id": 1,
    "name": "test name",
    "address": [
      {
        "address_id": 1,
        "address": "1234 address way"
      },
      {
        "address_id": 2,
        "address": "5678 new address"
      }
    ]
  },
  {
    "user_id": 2,
    "name": "diff name",
    "address_id": 1,
    "address": "1234 address way"
  }
]

but I'm not sure what that is called or if any tool exists that can do this?

A: Here's a solution that is a little generic, allowing you to specify what you're trying to collate and into what.  It uses a Map object in order to help with the collation of the target key (user_id in your case):
function collate(sourceArray, keyName, collectionName, collectionFields) {
    let collection = new Map();
    for (let item of sourceArray) {
        let targetObj = collection.get(item[keyName]);
        if (!targetObj) {
            targetObj = Object.assign({}, item);
            // remove the properties we are collecting
            for (let field of collectionFields) {
                delete targetObj[field];
            }
            targetObj[collectionName] = [];
            collection.set(item[keyName], targetObj);
        }
        let collectedObj = {};
        // copy over the fields we are collecting
        for (let field of collectionFields) {
            collectedObj[field] = item[field];
        }
        targetObj[collectionName].push(collectedObj);
    }
    // now convert Map to the final array
    return Array.from(collection.values());
}

Because I think it makes a lot more sense for whoever is using the resulting data, it always puts the address fields into an array, even if there is only one address and thus its an array of length 1.  This will make it a lot easier for whoever is iterating this data to use it without all sorts of special conditions for reading it as the data is consistently located whether there is one or more than one address.  The reader can always get the length of the array to see for themselves  how many addresses there are.
And, you could use it on your data like this:

let data = [
  {
    "user_id": 1,
    "name": "test name",
    "address_id": 1,
    "address": "1234 address way"
  },
  {
    "user_id": 1,
    "name": "test name",
    "address_id": 2,
    "address": "5678 new address"
  },
  {
    "user_id": 2,
    "name": "diff name",
    "address_id": 1,
    "address": "1234 address way"
  }
];

function collate(sourceArray, keyName, collectionName, collectionFields) {
    let collection = new Map();
    for (let item of sourceArray) {
        let targetObj = collection.get(item[keyName]);
        if (!targetObj) {
            targetObj = Object.assign({}, item);
            // remove the properties we are collecting
            for (let field of collectionFields) {
                delete targetObj[field];
            }
            targetObj[collectionName] = [];
            collection.set(item[keyName], targetObj);
        }
        let collectedObj = {};
        // copy over the fields we are collecting
        for (let field of collectionFields) {
            collectedObj[field] = item[field];
        }
        targetObj[collectionName].push(collectedObj);
    }
    // now convert Map to the final array
    return Array.from(collection.values());
}

let result = collate(data, "user_id", "address", ["address", "address_id"]);
console.log(result);

Or, if you really don't want the one element array, you can post process that out at the end:

let data = [
  {
    "user_id": 1,
    "name": "test name",
    "address_id": 1,
    "address": "1234 address way"
  },
  {
    "user_id": 1,
    "name": "test name",
    "address_id": 2,
    "address": "5678 new address"
  },
  {
    "user_id": 2,
    "name": "diff name",
    "address_id": 1,
    "address": "1234 address way"
  }
];

function collate(sourceArray, keyName, collectionName, collectionFields) {
    let collection = new Map();
    for (let item of sourceArray) {
        let targetObj = collection.get(item[keyName]);
        if (!targetObj) {
            targetObj = Object.assign({}, item);
            // remove the properties we are collecting
            for (let field of collectionFields) {
                delete targetObj[field];
            }
            targetObj[collectionName] = [];
            collection.set(item[keyName], targetObj);
        }
        let collectedObj = {};
        // copy over the fields we are collecting
        for (let field of collectionFields) {
            collectedObj[field] = item[field];
        }
        targetObj[collectionName].push(collectedObj);
    }
    // now convert Map to the final array
    let result = Array.from(collection.values());

    // remove single element arrays and copy back to main object
    for (let item of result) {
        let array = item[collectionName];
        if (array.length === 1) {
            // remove the array
            delete item[collectionName];
            // copy the fields from the one array element back to the main object
            Object.assign(item, array[0]);
        }
    }
    return result;
}

let result = collate(data, "user_id", "address", ["address", "address_id"]);
console.log(result);


text:
Q: Why is my Twitter web request bombing out? I've been working my way through Tim Heuer's Silverlight tuturial, in which you set up a basic interface to search Twitter. I started on the tutorial yesterday, completing through Step 3. It all was working fine. Now, though, I can't call Twitter without getting a "System.Security.SecurityException" error in the OpenReadCompleted handler. This applies to running Heuer's own code, as well. I would assume that it's a Cross-Domain Access issue, but that shouldn't be the case with Twitter's search API.
Using Web Development Helper, I see 2 failed GETs to http://search.twitter.com/clientaccesspolicy.xml, followed by a successful read of http://search.twitter.com/crossdomain.xml. That seems normal to me, since the first file exists, and the second doesn't. I'm totally stuck, and being new to Silverlight, don't know what else to try. I'd appreciate any help.
The Twitter call is as follows:
WebClient proxy = new WebClient();
proxy.OpenReadCompleted += OnReadCompleted;
proxy.OpenReadAsync(
    new Uri( @"http://search.twitter.com/search.atom?q=abc&since_id=0" ) );

These are the error details:
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
   at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
   at System.Net.WebClient.OpenReadAsyncCallback(IAsyncResult result)

A: It looks like twitter has changed the client access policy on their search domain to no longer allow requests from other domains. The current file looks like:
<?xml version="1.0" encoding="UTF-8"?>
<cross-domain-policy xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.adobe.com/xml/schemas/PolicyFile.xsd">
  <allow-access-from domain="twitter.com" />
    <allow-access-from domain="api.twitter.com" />
    <allow-access-from domain="search.twitter.com" />
    <allow-access-from domain="static.twitter.com" />
    <site-control permitted-cross-domain-policies="master-only"/>
  <allow-http-request-headers-from domain="*.twitter.com" headers="*" secure="true"/>
</cross-domain-policy>

Which means unless you are coming from one of those *.twitter.com domains listed, then you can't access it.
Update Just read on twitter that they've relaxed the restrictions again. The new crossdomain.xml is much better:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
       <allow-access-from domain="*" />
</cross-domain-policy>

So now your code should start working.


text:
Q: Use results from a query in another I'm using Wordpress and the plugin WPForms which stores form entries in my database like so:
(Doesn't seem like the most logical / best database design to me, but I have no choice).

Considering the table above. I need to select the entry ID's of the rows where meta_value contains the word 'Houd'.
I wrote this query which does that nicely:
SELECT entry_id
AS entries
FROM `wp_wpforms_entrymeta`
WHERE `meta_value`
LIKE '%Houd%'

Now, I would need to select to get the email adresses (which is entries_for_wpforms_field_id_8). Where the entry_id is equal to one of the id's fetched by the query above.
SELECT meta_value
FROM `wp_wpforms_entrymeta`
WHERE `meta_key` = 'entries_for_wpforms_field_id_8'
AND `entry_id` = <result of other query>;

How do I use the list of ID's of the previous query in my where in the other query?
I tried using a cross-join, like so:
SELECT entry_id
AS entries
FROM `wp_wpforms_entrymeta`
WHERE `meta_value`
LIKE '%Houd%'
CROSS JOIN (
    SELECT `meta_value`
    FROM `wp_wpforms_entrymeta`
    WHERE `meta_key` = 'entries_for_wpforms_field_id_8'
);

It resulted in a syntax error:

Error in used syntax near 'CROSS JOIN (SELECT meta_value FROM wp_wpforms_entrymeta WHER' in line 6.

A: you can use exists
SELECT `meta_value`
FROM `wp_wpforms_entrymeta` q
WHERE `meta_key` = 'entries_for_wpforms_field_id_8' and exists (
   SELECT 1
   FROM `wp_wpforms_entrymeta` qin
   WHERE `meta_value`  LIKE '%Houd%' and q.entry_id = qin.entry_id
)

A: Based on your first hunch you could also use a self-join to do it:
SELECT
    t1.meta_value
FROM wp_wpforms_entrymeta AS t1
JOIN wp_wpforms_entrymeta AS t2
     ON t1.entry_id = t2.entry_id
WHERE t1.meta_key = 'entries_for_wpforms_field_id_8'
     AND t2.meta_value LIKE '%Houd%';

Try it here.