text:
Q: Backbone Views listening to collection events is firing multiple times I'm facing a very weird problem using ListenTo on subviews.
Basically I've a main view that contains multiple subviews.
Those subviews are initialized when their parent view is also initialized.
Some of those subviews are listening to the same global collection.
One of those views is a form that allow me to insert new entries into the collection
The second one is a list of all those entries contained into the collection.
So, basically it looks like this
$('button').on('click'....
   app.views.MyMainView = new MyMainView()
   //launch new modal window
   //with html body = app.views.MyMainView.el

var MyMainView = Backbone.view.extend({
     initialize: function(){
          // new Form_View()
          // new List_View()
     }
});

var Form_View = Backbone.view.extend({
      //get input value
      // create new entrie into the collection
});

var List_View = Backbone.view.extend({
     initialize: function(){
          // listenTo(this.collection, 'add', this.addOne)
          // new List_View()
          this.addAll();
     },
     addAll: function(){...},
     addOne: function(model){ .... }
});

The problem is the following:
When the user launch the modal for the first time and we add a new entry to the collection
the listenTo add on the List_View fires as expected.
If I close the modal and the user clicks on 'button' to launch the modal window once again if I add a new entrie the view will fire 2 times the function that is listening to the collection add event.
If i close the modal again and re-open it the function will fire 3 times and so on.
This is weird because I'm creating a new instance of the view and their subviews everytime the user clicks on the 'button'. That's why it doesn't make sense to me.
Any help?
EDIT
    I also checked my collection by listening to the 'add' event inside of it.
var MyCollection = Backbone.View.extend({
    initialize: function(){
      this.listenTo( this, 'add', doSomething );
    },
    doSomething: function( model ){
        //do something fires as it should be firing the event: 1 time per each item inserted
    }
})

EDIT 2
var MyMainView = Backbone.View.extend({
.....
close_modal: function(e){

                if(e){
                    e.preventDefault();
                }

                var viewsLen = this.views.length,
                    _that = this;

                _.each(this.views, function(view, key){

                    view.remove();

                    if(key + 1 == viewsLen )
                        _that.dialog.close();
                })

            }
...
})

EDIT 3:
ALL CODE
//initialize modal
$('button').on('click', function(){
     app.views.storePayment_View = new StorePayment_View();
})
var TMPL_StorePayment = '
'
                                + '
'
                                    + '

'
                                    + '

'
                                + '
'
                                + '

'
                                + '

'
                                + '
'
                                + '
'
                            + '
';

    var StorePayment_View = Backbone.View.extend({
        views: {},
        wrappers: {},
        collections: {},
        events: {
            "click .back": "close_modal",
            "click .finish-payment": "finish_payment"
        },
        initialize: function(){
            var _that = this;
            this.dialog = new BootstrapDialog({
                title: appLang["h67"],
                message: this.$el,
                closable: true,
                onhide: function(dialogRef){
                    _that.remove();
                }
            });

            this.dialog.realize();
            this.dialog.getModalFooter().hide();
            this.dialog.open();

            this.$el.html('').append( TMPL_StorePayment );
            this.wrappers.$client = this.$el.find('.client');
            this.wrappers.$status = this.$el.find('.status');
            this.wrappers.$payment_form = this.$el.find('.payment-form');
            this.wrappers.$payment_list = this.$el.find('.payment-list');
            this.wrappers.$form_actions = this.$el.find('.x-form-actions');
            this.render()
        },
        render: function(){

            this.views.StorePaymentForm_View = new StorePaymentForm_View();
            this.wrappers.$payment_form.html('').append( this.views.StorePaymentForm_View.el  );

            this.views.StorePaymentList_View = new StorePaymentList_View();
            this.wrappers.$payment_list.html('').append( this.views.StorePaymentList_View.el  );

        },
        close_modal: function(e){

            if(e){
                e.preventDefault();
            }

            var viewsLen = this.views.length,
                _that = this;

            _.each(this.views, function(view, key){

                view.remove();

                if(key + 1 == viewsLen ){
                    _that.dialog.close();
                }

            })

        }

    })

    var StorePaymentForm_View = Backbone.View.extend({
        error_tmpl: _.template('
<%= message %>
') ,
        template: _.template('

 <input type="text" class="montant form-control" value="<%= restant %>">

 <select name="payment-type"><% _.each(paymentTypeList, function(paymentType){ %>  <option value="<%= paymentType.typeMode %>"><%= paymentType.libelle %></option> <% }) %></select>

Add newRemove All

'),
        events:{
            "click .add-new": "add_new",
            "click .remove-all": "remove_all"
        },
        initialize: function(){
            this.collection = app.collections.StorePaymentList;

            this.listenTo( this.collection, 'add', this.render )
            this.listenTo( this.collection, 'destroy', this.render )
            this.listenTo( this.collection, 'change', this.render )
            this.listenTo( this.collection, 'reset', this.render )
            this.render()
        },
        render: function(){
            console.log("RENDER FIRED ON STOREPAYMENTFORM")
            var restant = this.collection.getRestant();
            if ( restant <= 0){
                restant = 0;
            }
            this.$el.html('').append( this.template( { "restant" : restant, "paymentTypeList": app.collections.PaymentTypeList.toJSON() } ) )

            var _that = this;
            setTimeout(function(){
                _that.$el.find('select').selectBoxIt({
                    native: true,
                    autoWidth: false
                })

                _that.$el.find('input').focus();
            }, 50 )
        },
        add_new: function(e){

            console.log("add_new");

            if(e){
                e.preventDefault();
            }

            var _that = this,
                input_val = this.$el.find('input').val(),
                select_val = this.$el.find('select :selected').val(),
                libelle = this.$el.find('select :selected').text(),
                wasNaN = false;

                input_val = parseInt(input_val);
                if (isNaN(input_val)){
                    wasNaN = true;
                    input_val = 0;
                }

                if (wasNaN){
                    _that.$el.find('.error_placeholder').html( _that.error_tmpl( { "message": appLang["h69"] } ) );
                } else {
                    if ( input_val <= 0 ){
                        _that.$el.find('.error_placeholder').html( _that.error_tmpl( { "message": appLang["h70"] } ) );
                    } else {
                        this.collection.add( new StorePaymentModel( { "libelle": libelle , "paymentId": select_val, "montant": input_val  } ) )
                    }
                }
        },
        remove_all: function(e){
            if(e){
                e.preventDefault();
            }
            var _that = this;
            //dialog are you sure?
            var dialog = new BootstrapDialog({
                title: "Do you want to continue",
                message: "Do you really want to empty your current list of payments?",
                buttons: [{
                        label: appLang["a187"], //cancel
                        action: function(dialog) {

                            dialog.close();
                        }
                    }, {
                        label: appLang["a1621"], //ok
                        cssClass: 'btn-primary',
                        action: function(dialog) {
                            _that.collection.reset([]);
                            dialog.close();
                        }
                }]
            })

            dialog.realize();
            dialog.open();
        }
    })

    var StorePaymentListItem_View = Backbone.View.extend({
        events:{
            "click .remove": "remove_item",
            "click .save": "save"
        },
        template: _.template( '<%= libelle %> <%= montant %>  ' ),
        tagName: 'li',
        className: 'list-group-item',
        initialize: function(){
            this.render()
            //console.log("StorePaymentListItem_View initialized")
            this.listenTo( this.model, 'hide', this.remove )
        },
        render: function(){

            this.$el.html('').append( this.template( this.model.toJSON() ) )

        },
        edit: function(){
            this.render_edit();
        },
        save: function(e){
            if (e){
                e.preventDefault(); e.stopPropagation();
            }
            this.render();
        },
        remove_item: function(e){
            if (e){
                e.preventDefault(); e.stopPropagation();
            }

            this.model.destroy();
        }
    })

    var StorePaymentList_View = Backbone.View.extend({
        $wrapper: $('
', {'class': 'list-group' }),
        initialize: function(){
            this.$el.html('');
            this.collection = app.collections.StorePaymentList;

            this.listenTo( this.collection , 'add', this.addOne );
            this.listenTo( this.collection , 'change', this.render );
            this.listenTo( this.collection , 'reset', this.render );
            this.render()

        },
        render: function(){
            var totalItems = this.collection.length;
                this.$wrapper.html('')

            if (totalItems == 0){
                this.appendToRoot();
            } else {
                this.addAll()
            }
        },
        addAll:function(){
            var _that = this,
                totalItems = this.collection.length;

            this.collection.forEach(function(model, key){
                _that.addOne(model)

                if (totalItems == key + 1)
                    _that.appendToRoot();
            })
        },
        addOne:function( model ){

            var storePaymentListItem_View = new  StorePaymentListItem_View({ model: model });

            this.$wrapper.append( storePaymentListItem_View.el );

        },
        appendToRoot:function(){
            this.$el.html('').append( this.$wrapper );
        }
    })

A: My guess is closing the modal doesn't call view.remove, and so we end up with a zombie view that is removed from the DOM but still lives in memory listening to events.
Another guess is you never remove the List_View instance, so they are the zombies.
In other words, this is likely to be related to insufficient garbage collection.
This is a guess - it's impossible to tell without seeing the relevant parts of the code.


text:
Q: How To Use Ads With Chrome Extension? I'm trying to inject 1 ad in the popup created by my extension. How could I do so? Because when I try to add direct code provided by adsense, it shows "Refuse to execute script because of CPP".
Is there any way? I'm inserting ad on page and looks like it is allowed by chrome.

redpajama_set_name: RedPajamaStackExchange


text:
Q: angularjs google map zoom map after max zoom exceeded I want to zoom the google map after it exceeds it maximum zoom level. I google it and didn't find any solution. I am building a rooftop app any one can please help me on this.

A: The Google Maps API docs show that the google.maps.MapOptions object has a property called maxZoom that you can set when creating the map to set the maximum amount the map can be zoomed.
You can also set minZoom in the same way. So as long as your users don't need to be able to zoom very far out in order to move around effectively (e.g. if your app moves the map programmatically somehow) then you may even want to set the minZoom to a realistic value to ensure that people don't accidentally zoom too far out when trying to scroll down the page (I personally do that all the time with embedded google maps and it drives me crazy). But be careful with this: you don't want to ruin the user experience by removing your users' ability to navigate the map efficiently.
One thing you'll notice when reading the description of the maxZoom and minZoom parameters is that the docs don't specify the range of acceptable numbers. So how are you to figure out what numbers to pass in? And how do you change the max zoom after creating the map?
If the Map object is bound to a variable called map, then you can get the current zoom with map.getZoom() and you can set the current zoom with map.setZoom(zoom) where zoom is floating-point Number such that zoom >= 0. (Note: These methods get and set the "zoom" property of the Map object, but making changes directly to map.zoom will not cause the map to change, so be sure to use the getter and setter methods).
The most-zoomed-out level for the zoom property is 0, but the most-zoomed-in level will actually vary depending on where in the world the map is focused.  (This makes sense, since street-level in some places could be a mile underground in others depending on elevation.) And at some zoom level, Google will no longer have (usable) satellite images.
Enter the MaxZoomService Class. This object's constructor can be found at google.maps.MaxZoomService. The instances of this class have only one useful method: getMaxZoomAtLatLng which takes a LatLng instance or a LatLngLiteral as its first parameter and a callback function to handle the result as its second.
A LatLng instance can be created with the google.maps.LatLng constructor, and a LatLngLiteral is just a normal object literal that has a lat property and a lng property. But since you'll probably be passing in a LatLng object from another method like map.getCenter(), you shouldn't have to worry about it.
Here's an example showing how to find out the maximum zoom available on the Satellite View at the center of the map's current view.
var mzs = new google.maps.MaxZoomService();       // Create a MaxZoomService instance
var mapCenterLatLng = map.getCenter();            // Get a LatLng instance
var handleMaxZoom = function(res) {               // Callback Function accepting MaxZoomResult instance
     if (res.status === "OK") {
         // handle success
         console.log("Max Zoom: " + res.zoom);    // Print max possible zoom
         map.setZoom(res.zoom);                   // Set the zoom to the max possible
     } else {
         // handle failure
         console.log("Oops");
     }
};
mzs.getMaxZoomAtLatLng(mapCenterLatLng, handleMaxZoom);
// => Max Zoom: [Number]

Edit:
If you really want to exceed the maximum zoom level (not just the default maximum zoom level as described above) your only real option is going to be using css transforms. Depending on how complicated the page layout is, this could end up being pretty difficult to get perfect.
I should note that this is typically not a good idea even if you can manage to get the layout to look good and the images to not be blurry. It carries all the same problems as using CSS to transform canvas elements (and some additional problems on top because it's not as simple as dealing with just a single DOM element). One notable problem is that applying CSS transforms will not affect the internal coordinates of the map (like those contained in click events) so you'll have to transform those every time you want to use them. Additionally, since the primary map div (the one returned by map.getDiv()) has to sit inside a container, this method will often cause it to overflow its container and you'll have to deal with that added complexity.
If you still want to do it, then here are some pieces of the puzzle that may help:
var mapCanvas = map.getDiv();            // The "main" div element that contains the map
var container = mapCanvas.parentElement; // You'll need some sort of container here
var scalingFactor = 1.5;                 // => Set a scaling factor (ex: 1.5 means scale it to 150% normal size)
/* Use CSS zoom property and/or vendor transforms to scale the map (though you could do this in straight CSS instead) */
mapCanvas.style.zoom = scalingFactor;
mapCanvas.style.MozTransform = 'scale(' + scalingFactor + ')';
mapCanvas.style.WebkitTransform = 'scale(' + scalingfactor + ')';
/* Then try to fit the scaled map back into its container, which will depend on how you're displaying it */
mapCanvas.style.width = "calc(100% / " + scalingFactor + ")"; // The CSS 'calc()' method might be useful here


text:
Q: Click event implementation for HeaderView I have a navigation drawer. I've successfully populated ListView items programatically and assigned click listeners to it.
The problem occurs when I add an item in the list using headerView function. I'm adding it like this
View headerView = View.inflate(this, R.layout.listview_item_row, null);
((ImageView) headerView.findViewById(R.id.imageViewIcon)).setImageDrawable(getResources().getDrawable(R.drawable.myimage));
((TextView) headerView.findViewById(R.id.textViewName)).setText("Text");
mDrawerList.addHeaderView(headerView);

Now, technically the headerview element should execute on position 0 in the following code:
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    Fragment fragment = null;
    switch(position){
        case 0:
            fragment = new Fragment1();
            break;
        case 1:
            fragment = new Fragment2();
            break;
        case 2:
            fragment = new Fragment3();
            break;
    }
}

But the last element's case is not working and gives an ArrayOutOfBoundsException.
I'm creating ListView items this way:
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[3];
drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_speedometer, mNavigationDrawerItemTitles[0]);
drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_place, mNavigationDrawerItemTitles[1]);
drawerItem[2] = new ObjectDrawerItem(R.drawable.ic_price, mNavigationDrawerItemTitles[2]);

Where am I going wrong? How can I make a click event that works for HeaderView as well as last ListView item?
PS: newbie alert!

A: Implement separate click listener for headderview like this
View headerView = View.inflate(this, R.layout.listview_item_row, null);
((ImageView) headerView.findViewById(R.id.imageViewIcon)).setImageDrawable(getResources().getDrawable(R.drawable.myimage));
((TextView) headerView.findViewById(R.id.textViewName)).setText("Text");
mDrawerList.addHeaderView(headerView);
headerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // code to execute
            }
        });

A: Even if you add a headerview or a footerview to the ListView, the Android system handles it as a child internally. But to the developer, the first item(0th position) is the listview's first item(0th position). There is a different class in Android HeaderListViewAdapter.


text:
Q: Why does the #[inline] attribute stop working when a function is moved to a method on a struct? I have the function get_screen that's specified in a separate module from main.rs. It takes two 2D vectors (one that's 1920x1080 and called screen and another one that's even larger called world) and maps a portion of the world vector to the screen vector. This is the function signature when I first made it:
pub fn get_screen(
    screen: &mut Vec<Vec<[u8; 4]>>,
    world: &Vec<Vec<Chunk>>,
    camera_coords: (isize, isize),
    screen_width: usize,
    screen_height: usize,
    chunk_width: usize,
    chunk_height: usize,
)

I had serious issues with execution time, but I optimized it from 14ms down to 3ms by using #[inline].
I then moved the world vector to its own struct (alongside some other related variables like chunk width/height) and made the get_screen function into a method in the new world struct. This is what the function signature looked like after that change:
pub fn get_screen(
    &self,
    screen: &mut Vec<Vec<[u8; 4]>>,
    camera_coords: (isize, isize),
    screen_width: usize,
    screen_height: usize,
)

Then the execution time increases back to 14ms. I've tried enabling lto=true in Cargo.toml and switching to #[inline(always)] to enforce it, but it seems like the compiler refuses to optimize this function the way it used to.
I attempted to remove the get_screen method from the struct and run it as its own function like before and that seems to fix it, but only if I don't pass anything from the struct. If I attempt to pass even a usize from the world struct to the separate get_screen function, then the execution time increases from 3ms back to 14ms.
To show an example of what I mean, if I pass nothing directly from the world struct and instead pass it a cloned version of the 2D struct in world and the hardcoded chunk_width/chunk_height:
gen::get_screen(
    &mut screen.buf,
    &cloned_world_data,
    camera_coords,
    SCREEN_WIDTH,
    SCREEN_HEIGHT,
    CHUNK_WIDTH,
    CHUNK_HEIGHT,
);

It runs in 3.3ms. When I pass the usize fields chunk_width/chunk_height directly from the world struct:
gen::get_screen(
    &mut screen.buf,
    &cloned_world_data,
    camera_coords,
    SCREEN_WIDTH,
    SCREEN_HEIGHT,
    world.chunk_width,
    world.chunk_height,
);

it takes 14.55ms to run
What's up here? How can I get my get_screen function to compile inline while using my World struct? Preferably I'd like to be able to re-add it to my World struct as a method instead of keeping it separate.
Here is a minimal example:
use std::time::Instant;

const SCREEN_HEIGHT: usize = 1080; //528;
const SCREEN_WIDTH: usize = 1920; //960;
const CHUNK_WIDTH: usize = 256;
const CHUNK_HEIGHT: usize = 256;

const GEN_RANGE: isize = 25; //how far out to gen chunks

fn main() {
    let batch_size = 1_000;
    struct_test(batch_size);
    separate_test(batch_size);
}

fn struct_test(batch_size: u32) {
    let world = World::new(CHUNK_WIDTH, CHUNK_HEIGHT, GEN_RANGE); //generate world
    let mut screen = vec![vec!([0; 4]; SCREEN_WIDTH); SCREEN_HEIGHT];
    let camera_coords: (isize, isize) = (0, 0); //set camera location

    let start = Instant::now();
    for _ in 0..batch_size {
        get_screen(
            &mut screen,
            &world.data,
            camera_coords,
            SCREEN_WIDTH,
            SCREEN_HEIGHT,
            world.chunk_width,
            world.chunk_height,
        ); //gets visible pixels from world as 2d vec
    }
    println!(
        "struct:   {:?} {:?}",
        start.elapsed(),
        start.elapsed() / batch_size
    );
}

fn separate_test(batch_size: u32) {
    let world = World::new(CHUNK_WIDTH, CHUNK_HEIGHT, GEN_RANGE); //generate world
    let cloned_world_data = world.data.clone();
    let mut screen = vec![vec!([0; 4]; SCREEN_WIDTH); SCREEN_HEIGHT];
    let camera_coords: (isize, isize) = (0, 0); //set camera location

    let start = Instant::now();
    for _ in 0..batch_size {
        get_screen(
            &mut screen,
            &cloned_world_data,
            camera_coords,
            SCREEN_WIDTH,
            SCREEN_HEIGHT,
            CHUNK_WIDTH,
            CHUNK_HEIGHT,
        ); //gets visible pixels from world as 2d vec
    }
    println!(
        "separate: {:?} {:?}",
        start.elapsed(),
        start.elapsed() / batch_size
    );
}

///gets all visible pixels on screen relative camera position in world
#[inline(always)] //INLINE STOPPED WORKING??
pub fn get_screen(
    screen: &mut Vec<Vec<[u8; 4]>>,
    world: &Vec<Vec<Chunk>>,
    camera_coords: (isize, isize),
    screen_width: usize,
    screen_height: usize,
    chunk_width: usize,
    chunk_height: usize,
) {
    let camera = get_local_coords(&world, camera_coords, chunk_width, chunk_height); //gets loaded coords of camera in loaded chunks
    (camera.1 - screen_height as isize / 2..camera.1 + screen_height as isize / 2)
        .enumerate()
        .for_each(|(py, y)| {
            //for screen pixel index and particle in range of camera loaded y
            let (cy, ly) = get_local_pair(y, chunk_height); //calculate chunk y and inner y from loaded y
            if let Some(c_row) = world.get(cy) {
                //if chunk row at loaded chunk y exists
                (camera.0 - screen_width as isize / 2..camera.0 + screen_width as isize / 2)
                    .enumerate()
                    .for_each(|(px, x)| {
                        //for screen pixel index and particle in range of camera loaded x
                        let (cx, lx) = get_local_pair(x, chunk_width); //get loaded chunk x and inner x from loaded x
                        if let Some(c) = c_row.get(cx) {
                            screen[py][px] = c.data[ly][lx];
                        }
                        //if chunk in row then copy color of target particle in chunk
                        else {
                            screen[py][px] = [0; 4]
                        } //if target chunk doesn't exist color black
                    })
            } else {
                screen[py].iter_mut().for_each(|px| *px = [0; 4])
            } //if target chunk row doesn't exist color row black
        });
}

///calculates local coordinates in world vec from your global position
///returns negative if above/left of rendered area
pub fn get_local_coords(
    world: &Vec<Vec<Chunk>>,
    coords: (isize, isize),
    chunk_width: usize,
    chunk_height: usize,
) -> (isize, isize) {
    let (wx, wy) = world[0][0].chunk_coords; //gets coords of first chunk in rendered vec
    let lx = coords.0 - (wx * chunk_width as isize); //calculates local x coord based off world coords of first chunk
    let ly = (wy * chunk_height as isize) - coords.1; //calculates local y coord based off world coords of first chunk
    (lx, ly)
}

pub fn get_local_pair(coord: isize, chunk: usize) -> (usize, usize) {
    (coord as usize / chunk, coord as usize % chunk)
}

///contains chunk data
#[derive(Clone)]
pub struct Chunk {
    //world chunk object
    pub chunk_coords: (isize, isize), //chunk coordinates
    pub data: Vec<Vec<[u8; 4]>>,      //chunk Particle data
}

impl Chunk {
    ///generates chunk
    fn new(chunk_coords: (isize, isize), chunk_width: usize, chunk_height: usize) -> Self {
        let data = vec![vec!([0; 4]; chunk_width); chunk_height];
        Self { chunk_coords, data }
    }
}

pub struct World {
    pub data: Vec<Vec<Chunk>>,
    pub chunk_width: usize,
    pub chunk_height: usize,
}

impl World {
    pub fn new(chunk_width: usize, chunk_height: usize, gen_range: isize) -> Self {
        let mut data = Vec::new(); //creates empty vec to hold world
        for (yi, world_chunk_y) in (gen_range * -1..gen_range + 1).rev().enumerate() {
            //for y index, y in gen range counting down
            data.push(Vec::new()); //push new row
            for world_chunk_x in gen_range * -1..gen_range + 1 {
                //for chunk in gen range of row
                data[yi].push(Chunk::new(
                    (world_chunk_x, world_chunk_y),
                    chunk_width,
                    chunk_height,
                )); //gen new chunk and put it there
            }
        }
        Self {
            data,
            chunk_width,
            chunk_height,
        }
    }
}

A: Probably, when you use world.chunk_width and world.chunk_height as parameters the compiler does not consider these parameters as constants and then actually generates division and modulus operations.
On the other hand, when you provide constants for these parameters, they can be propagated in the algorithm (constant folding) and some expensive operations (division, modulus) are not performed (or transformed into bit-shifts/masks).
Copying/pasting your code in godbolt (compiler explorer), making separate_test() and struct_test() public, and compiling with -C opt-level=3 confirms this since div instructions are present in the generated code for struct_test() but not for separate_test().


text:
Q: Stimulsoft Report require to Refresh after Save button When I click on Save for PDF report then again I am not able to click on Save. I require to refresh the page.
Is this is default behavior?
Save Button Image
Please help me.


text:
Q: White space on right side - Bootstrap 4 I'm making a website in Bootstrap 4, but while creating one section I've ended up with the annoying white space on the right that causes unwanted horizontal scrolling.
Been playing with Inspector for ages, but can't figure out where's the problem.
Full code with the relevant section here: https://jsfiddle.net/dusset/aq9Laaew/284067/

O produkte

Preskúmajte nepreskúmané

Birthday Capsule je najoriginálnejší a najosobnejší narodeninový darček, aký môžte dať osobe, na ktorej Vám záleží.

Či je to babka, kamarátka alebo priateľ, život každého z nás má i nepreskúmanú stránku. Teda, donedávna nepreskúmanú…

Aký vek by mal na Marse? Koľkokrát sa už nadýchla? Čo iné je na dátume jeho narodenia výnimočné? To, i omnoho viac sme preskúmali, a dali do knižky, aby ste to mohli podarovať.

Any help with removing it is much appreciated!

A: Your .row class has margin-left: -15px and margin-right: -15px. This is the cause of your problem.
Add this to your CSS and it's fixed:
.row {
  margin:0px;
}

Here's an updated JSFiddle

If you don't want to override all row classes then add an id to the line below and add a CSS style for that independently.

   ...

And the CSS:
#something {
   margin:0px;
}

A: Use the "no-gutters" class with the offending "row". See: https://getbootstrap.com/docs/4.0/layout/grid/#no-gutters

A: Check you external css files. might be there is a overlapped content beyond the edges.


text:
Q: Django: how to pass form variable to simple tag in template I am trying to do some custom things in Django comments form. I have simple tag named "get_flatpage_by_id" that returns flatpage model data as array. This is working I expected:
{% get_flatpage_by_id 14 as page %}
It's returning flatpage that ID is 14. But this is not working, if I try to pass {{ form.object_pk.data }} (that returns 14). This is how it should look like:
{% get_flatpage_by_id form.object_pk.data as page %}
Simple tag receives value "form.object_pk.data" (string), not 14. I don't know how to tell Django that "form.object_pk.data" is variable, not a string!

A: Nevermind, my friend showed solution...
In filter I can read all data passed to template, so I received form object and data I needed.


text:
Q: SPFx SharePoint 2016 on premise - Issue I've installed Feature Pack 2 and developed simple "HelloworldwebPart".
I created two sites in my WebApp
Example :
Team Site : https://<Domain>/Sites/Test
App Catalog : https://<Domain>/Apps/Catalogs
Upload the SPFx webpart to App catalog site -- no error and issue.
Didn't see apps when I try to add the Webpart to main site
 (https://<Domain>/Sites/Test  >> Site content >> Add an apps).
Any Suggestions please ?

A: Have you done the full setup for apps in your on-premises farm? At a high level, this includes:

*

*Creating the forward lookup zone and CNAME alias in DNS

*Configuring the Subscription Settings and App Management service applications

*Setting up app URLs in Central Administration

If so, have you also granted access to the App Catalog to the user who is attempting to add the app and can't currently see it?

A: Here is what I have to do to see the webpart. Uses a keyword which returns noly your webpart, it will return something like below,
We didn't find a match here, but check out the SharePoint Store.
We didn't find a match here, but search across all your apps.
Click on "Search across all your apps". You will see your app.
However, I can't add it. It says "Sorry, apps are turned off. If you know who runs the server, tell them to enable apps."
Do I really need to install App service? SPFx is not running on App domain, it runs on page's context.

A: SPFX webparts don't need full setup of apps! Just type in a fictional URL in the app URL's central administration section and wait a few moments.


text:
Q: Why does dynamically adding a QTreeWidget to a QStackedWidget reset the font style? I have a script (modeled by dialog.py) which contains a stacked widget that embeds a custom widget module (modeled by widget_1.py) into the first page. The user clicks the 'Switch Page' button to add another page to the stacked widget and embed it with a different widget (using widget_1.py here again since it is easy to see the problem later). Everything works out except the style guide for some of the items are ignored in the added page while others are not. Why?

First page of stacked widget with correct font styling.

Second page of stacked widget with default font styling.
dialog.py
from PyQt5 import QtCore, QtGui, QtWidgets

from widget_1 import widget_1_UI

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.resize(640, 480)
        Dialog.setWindowTitle("I'm a cat. I'm a kitty cat.")
        self.addPage2 = False

        self.verticalLayout = QtWidgets.QVBoxLayout(Dialog)

        self.stackedWidget = QtWidgets.QStackedWidget(Dialog)

        self.page_1 = widget_1_UI()
        self.page_1.setupUi(self.page_1)
        self.stackedWidget.insertWidget(0, self.page_1)
        self.stackedWidget.setCurrentIndex(0)

        self.verticalLayout.addWidget(self.stackedWidget)

        self.btn_nextPage = QtWidgets.QPushButton(Dialog)
        self.btn_nextPage.setText("Switch Page")
        self.verticalLayout.addWidget(self.btn_nextPage)
        self.btn_nextPage.clicked.connect(self.addSecond)
        self.btn_nextPage.clicked.connect(self.nextPage)

    def nextPage(self):
        num = self.stackedWidget.currentIndex()
        if num == 0:
            self.stackedWidget.setCurrentIndex(1)
        else:
            self.stackedWidget.setCurrentIndex(0)

    def addSecond(self):
        if not self.addPage2:
            self.page_2 = widget_1_UI()
            self.page_2.setupUi(self.page_2)
            self.stackedWidget.insertWidget(1, self.page_2)
            self.addPage2 = True

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

widget_1.py
from PyQt5 import QtCore, QtGui, QtWidgets

class widget_1_UI(QtWidgets.QWidget):
    def setupUi(self, Form):
        Form.resize(614, 411)
        Form.setWindowTitle("Main Dialog")

        self.verticalLayout = QtWidgets.QVBoxLayout(Form)

        self.label = QtWidgets.QLabel(Form)
        font = QtGui.QFont()
        font.setFamily("Arial Narrow")
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setText("Cat Type")
        self.verticalLayout.addWidget(self.label)

        self.treeWidget = QtWidgets.QTreeWidget(Form)
        font = QtGui.QFont()
        font.setFamily("Arial Narrow")
        font.setPointSize(12)

        self.treeWidget.setFont(font)
        self.treeWidget.header().setVisible(False)
        self.catTypes = ["Happy", "Sleepy", "Hangry", "Needy", "Kneedy"]
        self.catSubtype = ["Orange", "Black", "Brown", "White"]
        for index in range(len(self.catTypes)):
            item_0 = QtWidgets.QTreeWidgetItem(self.treeWidget)
            item_0.setText(0, self.catTypes[index])
            for count in range(len(self.catSubtype)):
                item_1 = QtWidgets.QTreeWidgetItem(item_0)
                item_1.setText(0, self.catSubtype[count])
        self.verticalLayout.addWidget(self.treeWidget)


text:
Q: Thumbnail for music files in android I want to get thumbnail for music files from there path or id .How can i achieve this?. I know that there is a default directory in android with thumbnails of all music files ,is there a way to find the thumbnail of a music file from there using either file path or id?.

A: You can easily parse mp3 files, in you read The MP3 Tag Standard: http://id3.org/ <-- this is the best way
Other good way is obtain album/artist name and title, then ask some third-party service for cover. For example, lastfm have good API.
You also can take look at https://developer.android.com/reference/android/media/MediaMetadataRetriever.html

A: Here is the code that worked for me
 public  Bitmap coverpicture(String path) {

        MediaMetadataRetriever mr = new MediaMetadataRetriever();

        mr.setDataSource(path);

        byte[] byte1 = mr.getEmbeddedPicture();
        mr.release();
    if(byte1 != null)
            return BitmapFactory.decodeByteArray(byte1, 0, byte1.length);
    else
        return  null;

}


text:
Q: Как заставить работать пакет npm Новичок в npm, и появился вопрос, к примеру я установил Vue JS через npm, все нормально встало, в package.json Vue отобразился, но Vue код не работает, полез гуглить, установил browserify, в файле с js  написал var _Vue = require('vue'); и изменил все New Vue({}) на New _Vue({}). Потом ввел browserify js/main.js -o js/main.vue.js -d, подключил новый созданный файл, но все равно ничего не работает, в чем может быть проблема? Когда устанавливал таким способом jquery, то все работало
var _Vue = require('vue');
_Vue.component('assortment-card', {
    props: ['props'],
    template: `
        <div class="card" :class="{cardBottom: props.cardPositionBottom}">

        </div>
    `
});
let assortment = new _Vue({
    el: '#assortment',
    data: {
        cardInfo: [
            {
                cardId: '1',
                cardName: 'Lasagna',
                cardDesc : 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
                cardPrice: '200',
                cardImgSrc: 'img/shutterstock_91005374.png',
                cardImgSrcWebp: 'img/shutterstock_91005374.webp',
                cardPositionBottom: false,
            },
            {
                cardId: '2',
                cardName: 'pizza',
                cardDesc : 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
                cardPrice: '399',
                cardImgSrc: 'img/shutterstock_294636281.png',
                cardImgSrcWebp: 'img/shutterstock_294636281.webp',
                cardPositionBottom: false,
            },
            {
                cardId: '3',
                cardName: 'IDLIS',
                cardDesc : 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
                cardPrice: '99',
                cardImgSrc: 'img/shutterstock_139456373.png',
                cardImgSrcWebp: 'img/shutterstock_139456373.webp',
                cardPositionBottom: true,
            },
            {
                cardId: '4',
                cardName: 'BURGER',
                cardDesc : 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
                cardPrice: '129',
                cardImgSrc: 'img/shutterstock_361890518.png',
                cardImgSrcWebp: 'img/shutterstock_361890518.webp',
                cardPositionBottom: true,
            }
        ],
    },
});


text:
Q: How to pass data to Codeigniter Template I'm using Phil Sturgeon's Template library (http://philsturgeon.co.uk) and I'm having trouble passing data to a partial.
I can set a title by doing $this->template->title('some title')
I'd like to set other attributes such as the meta description and the meta keywords, but I'm not sure how to pass it to the partial.

A: try to build the template and pass to it all the data you need, for example:
$this->data->myTitle = "Your title";
$this->data->myKeyword = "key1, key2";
$this->template->build('your/view',$this->data);

then try to use it into your view with:
$myTitle and $myKeyword


text:
Q: Complete set coset representatives of a subgroup $H$ in a group $G$ Let $G$ be a group and $H$ be a finite subgroup of index $n$ in $G$. Is there any systematic way of finding a complete set of coset representatives(That is a set of coset representatives for all conjugates of $H$ in $G$) for $H$ in $G$?
I have a group $G$ of order 24 inside $S_6$ and a subgroup $H$ of order 4 inside $G$ whose conjugacy class of subgroups has 3 elements. I want to find a complete set of coset representatives for it. Is there any way to do it?

A: Generally, the way for computing all the (right) cosets of a (finite) group $G$ is as follows:

To compute all the right costs of a subgroup $H$ in a finite group $G$, first write $H$, then choose any $a \in G$ such that $a \notin H$, and compute $Ha$. Next, choose any $b \in G$ such that $b \notin H \cup Ha$, and compute $Hb$. Continue in this way until all elements of $G$ have been exhausted.

Hope this helps you.

A: It is not true in general that there exists a single set of size $n$ that forms a complete set of (right) coset representatives for $g^{-1}Hg$ in $G$ for all $g \in G$. For example this is not possible in a subgroup $H$ of order $2$ in $G = A_4$.


text:
Q: Find unused tty in the shell like bash? Is there a generic way to find unused tty in the shells like bash?
The following seem to work, but I suppose there must be a better way?
$ used=$({ find /proc/{0..9}*/fd/0 -printf '%l$\n' | grep tty;} 2> /dev/null)
$ unused=$(find /dev/ -name 'tty*' | grep -ve "$used")

A: Assuming you mean Linux virtual terminals, there is the VT_OPENQRY ioctl() to get the first free virtual terminal (as used by openvt for instance), but you would need a file descriptor to a console device for that already. Alternatively, you could do (as root):
comm -23 <(printf '%s\n' /dev/tty[1-9]*) \
         <(lsof -Fn /dev/tty[1-9]* | sed -n 's/^n//p' | sort -u)

Which you could generalise to other types of tty devices like serial ones.
That would be more robust in that it would only consider those device paths and not have issues with filenames with regexp operators or newlines, but like in your approach, that would not work properly if the tty devices are open by any other path that the /dev/ttyxx ones.
Another approach would be to rely on device numbers instead of their canonical path.
With GNU stat:
find -L /proc/[1-9]*/fd/. ! -name . -prune -type c -exec  stat -Lc '%t %T' {} + |
  awk '$1 == "4" {seen[$2]}
       END {
         for (i=1; i<=63; i++)
           if (!(sprintf("%x", i) in seen))
             print "/dev/tty" i
       }'


text:
Q: Combine results of different tables to create an alphabetic list I did my homework but couldn't find any answer on the question below...
I'd like to create an "alphabetic index" made of the results of two (or more) tables of my MySQL-database.
TABLE 1 is "search_words", with fields to use: id - search_word
TABLE 2 is "categories", with fields to use: id - category_name
So what I need is an alphabetically sorted list with the results of these two tables, the mixed output of the fields "search_word" AND "category_name", but sorted alphabetically. As they have no relationship, these tables are not joinable, I guess.
Is there a possibility or is the answer simply "No, there isn't!"?
Thanks in advance for any reply, help or redirect to previously posted topics cocerning this issue.

A: Try this:
SELECT id, test
FROM (SELECT id,search_word AS test
      FROM search_words
      UNION
      SELECT id,category_name AS test
      FROM categories
     ) AS a
ORDER BY test;`

A: SELECT id,search_word AS word FROM search_words
UNION
SELECT id,category_name AS word FROM categories
ORDER BY word

A: With a WHERE
SELECT email AS emailList
                         FROM tableA
                        WHERE tableA.email LIKE "'. mysql_real_escape_string($_REQUEST['term']) .'%"
                        UNION
                       SELECT email AS emailList
                         FROM tableB
                        WHERE tableB.email LIKE "'. mysql_real_escape_string($_REQUEST['term']) .'%"


text:
Q: Statsmodels ztest: Which variance is used in proportions_ztest? I'm trying to understand how proportions_ztest works
As I understand it when I run
stat, pvalue = proportions_ztest(count = 40, nobs = 20000, value = 0.003, alternative = "smaller")
pvalue

it should give the same result for the p-value as
stats.norm.cdf(40, 60, np.sqrt(20000* 0.003*(1-0.003)))

but it does not. My assumption is, there is a different variance used, but I didnt find any documentation on this.

A: statsmodels proportions_ztest uses by default the variance based on the estimated proportion and not the variance base on the null proportion.
One interpretation of this is that the default is a Wald test and not a score test.
see answer and comments here
https://stats.stackexchange.com/questions/447462/why-does-the-proportions-ztest-function-in-statsmodels-produce-different-values


text:
Q: React 18 reactStricMode Yields Incorrect Behavior for useReducer Hook In React 18 useReducer is seeing different states between the two renders imposed by reactStrictMode, even though my reducer function is completely pure.
When I use the state variable in reducer, the first argument passed to the reducer function, (ie the application state when dispatch action is first called) my application doesn't work. If I disable reactStricMode ie reactStricMode: false in next.config.mjs then the app works as expected and the page updates correctly as a result of dispatching the toggleFlag action.
I found a workaround where I put state in a context, StateContext, and wrap <MineSweeper/>  in <StateContext.Provider>. Then before calling dispatch, from within the GameCell JSX component, I get the state from the StateContext with useContext(StateContext), and then do all the computations to work out what the new state should be, from within the GameCell component and pass that newState as the value for action.payload ie: dispatch({ type: 'toggleFlag', payload: newlyComputedState }). In the past, with Redux, I've always done this computation in the reducer and used the state variable there without issue; although this was before React v18.
This workaround does work but it feels like an egregious Redux/useReducer anti-pattern.
From researching this issue, it seems that React renders each component twice when reactStricMode: true starting from React v18. And that the state can be different between these two renders if the reducer is not a pure function. But my reducer is pure. It only depends on the state and action arguments passed into it, and nothing else external.
It appears that every time I try to use the state variable in the reducer function reducer(state, action) my application state is different between these two renders, and then the view shown in the browser isn't correct.
How should I go about correcting this issue?
React v18.2.0
Next.js v13.0.2
ORIGINAL/STANDARD APPROACH: (https://github.com/currenthandle/mine-sweeper/tree/add-reducer)
src/utils/reducer.ts
const reducer = (state: State, action: Action) => {
  const board = [...state.board]
  const cell = { ...action.payload }

  switch (action.type) {
    case 'toggleFlag': {
      if (cell.shown) {
        return state
      }

      const y = cell.position[0]
      const x = cell.position[1]

      const boardCell = (board[y] as Cell[])[x] as Cell
      boardCell.flagged = !cell.flagged
      return { ...state, board }
    }
    default: {
      return state
    }
  }
}

src/components/GameCell.tsx
const GameCell = ({ cell }: { cell: Cell }): JSX.Element => {
  const dispatch = useContext(Context)

  const handleClick = (e: React.MouseEvent<HTMLElement>) => {
    e.preventDefault()

    // if holding shift
    if (e.shiftKey) {
      dispatch({ type: 'toggleFlag', payload: cell })
    }
  }

  const getInnerHtml = () => {
    if (cell.flagged) {
      return ''
    }
   // ...
  }
  return (
    <div
      className={`border border-black w-10 h-10 items-center justify-center grid ${getBackgroundColor()}`}
      onClick={handleClick}
    >
      {getInnerHtml()}

  )
}
export default GameCell

src/components/MineSweeper.tsx
const MineSweeper = ({
  initalBoard,
  minePositions,
}: {
  initalBoard: Board
  minePositions: Position[]
}) => {
  const [state, dispatch] = useReducer(reducer, {
    board: initalBoard,
    minePositions,
    flags: 0,
    gameOn: true,
    alive: true,
  })
  return (

      <Context.Provider value={dispatch}>
        <GameBoardGrid board={state.board}></GameBoardGrid>
      </Context.Provider>

  )
}

WORKAROUND USING CONTEXT: (https://github.com/currenthandle/mine-sweeper/tree/context-workaround)
src/utils/reducer.ts:
const reducer = (state: State, action: Action) => {
  switch (action.type) {
    case 'toggleFlag': {
      const board = action.payload as Board
      return { ...state, board }
    }
    default: {
      return state
    }
}

src/components/GameCell.tsx
const GameCell = ({ cell }: { cell: Cell }): JSX.Element => {
  const state = useContext(StateContext)
  const dispatch = useContext(DispatchContext)

  const handleClick = (e: React.MouseEvent<HTMLElement>) => {
    e.preventDefault()
    if (cell.shown) {
      return
    }

    const y = cell.position[0]
    const x = cell.position[1]

    const board = state.board
    const boardCell = (board[y] as Cell[])[x] as Cell
    boardCell.flagged = !cell.flagged
    // if holding shift
    if (e.shiftKey) {
      dispatch({ type: 'toggleFlag', payload: board })
    }
  }
  // ...
}

src/components/MineSweeper.tsx
const MineSweeper = ({
  initalBoard,
  minePositions,
}: {
  initalBoard: Board
  minePositions: Position[]
}) => {
  const [state, dispatch] = useReducer(reducer, {
    board: initalBoard,
    minePositions,
    flags: 0,
    gameOn: true,
    alive: true,
  })

  return (

      <StateContext.Provider value={state}>
        <DispatchContext.Provider value={dispatch}>
          <GameBoardGrid board={state.board}></GameBoardGrid>
        </DispatchContext.Provider>
      </StateContext.Provider>

  )
}

SAME IN BOTH APPROACHES:
next.config.mjs
!process.env.SKIP_ENV_VALIDATION && (await import('./src/env/server.mjs'))

/** @type {import("next").NextConfig} */
const config = {
  reactStrictMode: false,
  swcMinify: true,
  i18n: {
    locales: ['en'],
    defaultLocale: 'en',
  },
}
export default config


text:
Q: Powershell script to delete oldest files I DO NOT want to "delete files older than X days." If I wanted to do this, I'd just pick one of the thousands of scripts out there that have already been written for that purpose, and I wouldn't bother asking such a trivial question on ServerFault.
I DO want to delete all but the most recent N files in a particular folder.
I found a script that does what I need, but it works in a specific folder.
Here is the script:
# Defines how many files you want to keep?
$Keep = 2

# Specifies file mask
$FileMask = "*.bak"

# Defines base directory path
$Path = "D:\example\"

# Creates a full path plus file mask value
$FullPath = $Path + $FileMask

# Creates an array of all files of a file type within a given folder, reverse sort.
$allFiles = @(Get-ChildItem $FullPath) | SORT Name -descending

# Checks to see if there is even $Keep files of the given type in the directory.
If ($allFiles.count -gt $Keep) {

    # Creates a new array that specifies the files to delete, a bit ugly but concise.
    $DeleteFiles = $allFiles[$($allFiles.Count - ($allFiles.Count - $Keep))..$allFiles.Count]

    # ForEach loop that goes through the DeleteFile array
    ForEach ($DeleteFile in $DeleteFiles) {

        # Creates a full path and delete file value
        $dFile = $Path + $DeleteFile.Name

        # Deletes the specified file
        Remove-Item $dFile
    }
}

I wonder if there is any way for me to make this script work on an entire disk.
For example, it scans Disk D, and enters each subfolder and deletes files, keeping the two most recent ones.
Deleting only files and not folders.


text:
Q: Prepopulate form in an iFrame using string data I have a scenario where one form leads to another and the second one is inside an iFrame. I wanted to figure out how to pass string data onto the form within the iFrame. I've tried a few JavaScript codes I found online but none are working

A: You cannot view/modify within an iframe. Even if you set CORS most browsers block a lot of functionality today.
if you have control of both sites you can use post messages.

A: if your iframe's id is 'if', this will give you the inner doc
var innerDoc = document.getElementById("if").contentDocument;

then you can find your element from there.


text:
Q: set/reset GPIO though command line is not working as expected I am trying to set/reset the GPIO value through sysfs. I took this document as reference.
At one point I am little confused, the scenario is given below
exported gpio 200 to test
mx6q:/sys/class/gpio/gpio200# echo "out" > direction   <-- set the direction as write(out)
mx6q:/sys/class/gpio/gpio200# cat direction            < -- just to verify
out
mx6q:/sys/class/gpio/gpio200# echo 1 > value           < -- set value as 1(high)
mx6q:/sys/class/gpio/gpio200# cat value
1
mx6q:/sys/class/gpio/gpio200# echo 0 > value           < -- set value Low again
mx6q:/sys/class/gpio/gpio200# cat value
0
mx6q:/sys/class/gpio/gpio200# cat direction
out
mx6q:/sys/class/gpio/gpio200# echo "in" > direction      < -- change the direction to read the pin
mx6q:/sys/class/gpio/gpio200# cat direction
in
mx6q:/sys/class/gpio/gpio200# cat value                 < -- what i am expecting here is 0 (last set value)
1

So regardless the value i Set before , i am always reading a high value. is this really expected behavior?
I am confused at two points,

*

*why  the previously set value is not persisting after i change the direction?

*what does the "Direction" really means, if i can cat for the value in both "in" and "out" case?

Please suggest a proper document to read to get a clear idea about GPIO operations.
Thanks in advance

A:
what does the "Direction" really means, if i can cat for the value in both "in" and "out" case?

This question is a little unclear, but maybe this helps:
If direction is out, then the data in value defines the logic level you want to set on the GPIO pin.
If the direction is in, then the data in value is the logical level currently being read from the GPIO pin.

why the previously set value is not persisting after i change the direction?

Imagine that you have the pin tied to ground.
If you set direction to out and write 1 to value, then of course when you read back value you will see 1 because that's what you just requested.
If you were then set to set direction to in, value would now read 0 because you have the pin tied to ground, so you are currently reading a logical 0 from the pin.


text:
Q: Does memoryless property imply identical distribution of inter-arrival CDF's in a poisson process? This is my result from finishing a problem in a stochastic process workbook:
"Since a Poisson process has the property of stationary increments, this implies that the inter-arrival times $Z_n=T_n-T_{n-1}$ are identically distributed without regard to the starting value of n.  That is:
$$\Pr(Z_{n-1} \le z) = \Pr(Z_n \le z)$$
$$F_{Z_{n-1}}(z) = F_{Z_{n}}(z)$$
For inter-arrival times of a Poisson Process, the CDF of step n-1 equals CDF for step n

How does this property relate to the memoryless property for exponential random variable, namely:

*

*A RV X is memoryless if X is positive, and for all real $t>0$ and $s >0$, then:
$P[X > t +s] = P[X>t]~P[X>s]$

*A RV X is memoryless if for any s and t, we have:
$P(X > t+s~|~X > t) = P(X>s)$
I was just curious... because CDF and memoryless properties seem similar to each other ... but the sign is backwards...


text:
Q: Noether/Hilbert energy-momentum tensor In chapter 4 of Carroll's book Spacetime and geometry he finds using the Hilbert action that the energy-momentum tensor for a scalar field is (see eq. (4.79))
$$T_{\mu\nu}^{\phi}=\nabla_\mu\phi\nabla_\nu\phi+g_{\mu\nu}\left(-\frac{1}{2}g^{\alpha\beta}\nabla_\alpha\phi\nabla_\beta\phi-V\right).\tag{4.79}$$
In the same chapter, he recalls Noether's theorem from which we have (see eq. (4.80))
$$T^{\mu\nu}=\frac{\delta\mathcal{L}}{\delta(\partial_\mu\phi)}\partial^\nu\phi-\eta^{\mu\nu}\mathcal{L}.\tag{4.80}$$
The issue is that when I use this second expression for the energy-momentum tensor and try to find it for a scalar field with Lagrangian density $$\mathcal{L}=-\frac{1}{2} \partial_\mu\phi\partial^\mu\phi-V,\tag{1.148}$$
with sign convention $(-,+,+,+)$, I got the same as $T_{\mu\nu}^\phi$ except for an overall minus sign. Maybe I just made a mistake but would appreciate any assistance on this, at least a confirmation that both definitions are equivalent in this case.

A: OP is right: Carroll's book has a sign mistake in eq. (4.80). The $T^{00}$-component should be bounded from below, and $V$ should appear with a plus sign in $T^{00}$. Eq. (4.79) satisfies this but not eq. (4.80).
References:

*

*Sean M. Carroll, Spacetime and Geometry: An Introduction to General Relativity, 2003.


text:
Q: Why does my WCF Web Service have Two Different SOAP Bindings? I am creating the web service in c#.I have written two simple methods.when I publish my web service it will generate two binding in WSDL file.
1st

binding name="MyWebServiceSoap" type="tns:MyWebServiceSoap"
  2nd
binding name="MyWebServiceSoap12" type="tns:MyWebServiceSoap"

The rest content is same

A: One is a SOAP 1.1 binding, one is a SOAP 1.2 binding.


text:
Q: How do I implement that if a checkbox is clicked then dropdown field doesnot need to have value This is php question. Please see image below. If user clicks on "Click A", then user do not need to select year/month from dropdown. I am trying to implement that logic in server side validation.
I have two variables of the dropdown that are getting the values correctly.
    $expiry_year1 = $advert->getRegoExpiryYear();
    $expiry_month1 = $advert->getRegoExpiryMonth();

Unfortunately I do not get any values of whether clicked on "Click A".
But, if $exprity_year == empty && $expirty_month== empty, then we know that user have clicked on "Clicked A" which is kinda not accurate but that is how it should be.. Can you help me to implement the case?
    $expiry_year1 = $advert->getRegoExpiryYear();
    $expiry_month1 = $advert->getRegoExpiryMonth();
    // don't send the rego expiry
    if (!$expiry_year1 || !$expiry_month1) {
        $regoexpirydate = '';
    } else {
        $regoexpirydate = date("Y-m-t", strtotime((!empty($expiry_year1) ? $expiry_year1 : '') . '-' . (!empty($expiry_month1) ? $expiry_month1 : '')));
    }

if($regoexpirydate is anything but "" or a value then do something..
How do I say that in php?

A: If you want the checkbox to control the select boxes if they are needed to be processed or not, you can also use jquery to control their states as disabled/or not disabled. When they are disabled they will not be included in the process. Consider this example:
<?php
if(isset($_POST['submit'])) {

    // this is not defined if its not checked
    $checked = isset($_POST['click_a']) ? true : false;
    $month = isset($_POST['select1']) ? $_POST['select1'] : null;
    $year = isset($_POST['select2']) ? $_POST['select2'] : null;
    if($checked) {
        // if its checked and select boxes are empty do not process them
        echo 'checkbox a is checked';
    } else {
        // process them
        echo 'checkbox a is NOT checked';
        echo $month . ' - ' . $year;
    }
}

?>

<form method="POST" action="index.php">

    <input type="checkbox" name="click_a" id="click_a" /> Click A

    Registration Expiry:

        <select name="select1" id="select1">
            <option selected disabled>Month</option>
            <option>Jan</option>
        </select>
        <select name="select2" id="select2">
            <option selected disabled>Year</option>
            <option>3000</option>
        </select>

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

</form>


text:
Q: Access 365 and accdr file EDIT:
I have tried 32 and 64 bits accdr and accde files.  They work great on my Office 2016 installation but I still get the "unrecognized format" error.
Any more clues?  I think I saw that a special switch was needed to start Access 365 in runtime mode.  Does that ring a bell to anyone?
I have an accdr file that is used by a bunch of clients (non profit orgs).  One of them has Office 365 Business edition and it just won't open the accdr file, giving the "Unrecognized Database Format" error.
Can that be fixed through a switch in the command line?  Do I need to create the accdb in O365 (it was created in 2016)?  Can O365 be 32 bits?  The accdr was done on an x64 office installation.

A: Make sure that the file is not corrupted and that it's working on another machine. If the file is OK, then download and install Microsoft Access 2016 Runtime, and the file will work.
Download the right edition for your OS. 32-bit or 64-bit.
Microsoft Access 2016 Runtime
Note: If the file was created with Access 64-bit it cannot work on 32-bit OS.


text:
Q: Error using the feather format package I am having trouble using the feather format to export data. I have installed the package using:
conda install feather-format -c conda-forge

however, when I use pd.to_feather() I get an error telling me to install the package (which is already installed).

ImportError: the feather-format library is not installed
  you can install via conda
  conda install feather-format -c conda-forge
  or via pip
  pip install -U feather-format

I also tried using pyarrow, but I am getting another error, saying

ImportError: cannot import name 'cpu_count'

Can you please tell what am I doing wrong?
Thank you

A: Feather has found a new home in the pyarrow module, so no need to install Feather anymore.
I can recommend you to have a look at Feather format update: Whence and Whither?, that explains why and in general is a nice little walk through of the changes plus a benchmark between the pyarrow and legacy feather module - interesting since we all use the format for performance reasons :-)


text:
Q: Yii2 REST API IIS Object Moved I am using Yii2 REST with ActiveController to create a new Pessoa(), on Apache works fine , but on IIS 8 an error occurs.
Does anyone know of any configuration in IIS?

REQUEST

Request URL:http://10.192.1.145/api/pessoa
Request Method:POST
Status Code:201 Created
Remote Address:10.192.1.145
Referrer Policy:no-referrer-when-downgrade

RESPONSE

<title>Document Moved</title>

Object Moved
This document may be found
here{"id":"21"}

A: I had a similar issue to this. It seems to be related to FastCGI. Not sure about it. I know it happens when setting response headers to 201 http status code (this line in source code) which get changed by IIS later. If you have access to server try those solutions:

W7 Pro IIS 7.5 overwrites PHP Location: Header (solved)

In my case I had only FTP access to server so I overridden the Create Action by something like what follows to force a 200 status code instead of 201:
public function actions()
{
    $actions = parent::actions();
    unset($actions['create']);
    return $actions;
}

public function actionCreate() {
    $model = new Pessoa();
    $model->load(Yii::$app->getRequest()->getBodyParams(), '');
    if ($model->save() === false && !$model->hasErrors()) {
        throw new ServerErrorHttpException('Failed to update the object for unknown reason.');
    }
    return $model;
}

A: Just in case somebody else needs to keep the status code and remove only the response part added by IIS, this is what I did to solve my problem. You may need adapt it to your needs, though:

<outboundRules>
    <rule name="Remove the tag HEAD" preCondition="isStatus201">
        <match filterByTags="None" pattern="^\<head\>.*?$" />
        <action type="Rewrite" value="" />
    </rule>
    <rule name="Remove the tag BODY" preCondition="isStatus201">
        <match filterByTags="None" pattern="^\<body\>.*?\</body\>" />
        <action type="Rewrite" value="" />
    </rule>
    <preConditions>
        <preCondition name="isStatus201">
            <add input="{RESPONSE_STATUS}" pattern="^201$" />
        </preCondition>
    </preConditions>
</outboundRules>

Tested in IIS 8.5;
Hope it helps somebody else.

A: In fact, I was able to optimize the RegEx so that a single rule catches all the lines up the closing body tag:
<outboundRules>
  <rule name="Remove injected 201 content" preCondition="Status 201">
    <match filterByTags="None" pattern="^(?:.*[\r\n]*)*.*</body>" />
    <action type="Rewrite" value="" />
  </rule>
  <preConditions>
   <preCondition name="Status 201" patternSyntax="Wildcard">
     <add input="{RESPONSE_STATUS}" pattern="201" ignoreCase="false" />
   </preCondition>
  </preConditions>
</outboundRules>


text:
Q: when i add margin to my row of fluid container my one div shifts down how to prevent that? image

    yo

    bo

    so

    ko

//////////////////////CSS/////////////////////////////////
    .col-lg-3{
    background-color: red;
    margin: 1px;
  }

even if i add margin as small as 1px my last div shifts in one row down how to prevent that? help i am stuck for many hours

A: It is happening because you're using 4 col-lg-3 which 3*4=12 which takes the whole row and when you even add 1px margin it gets bigger than the scope of the row and it goes to the next row.
I don't know what you are trying to do but maybe you can use col-lg-2


text:
Q: gradlew clean deployNodes - QUASAR WARNING: Quasar Java Agent isn't running When I run "gradlew clean deployNodes" or "gradlew deployNodes", I get a warning on Quasar library:
QUASAR WARNING: Quasar Java Agent isn't running. If you're using another instrumentation method you can ignore this message; otherwise, please refer to the Getting
 Started section in the Quasar documentation.
How can i fix this warning ?
I upgraded Corda to 4.1

A: you'll want to double-check the intellij settings.

Navigate to Build, Execution, Deployment -> Build Tools -> Gradle ->
  Runner (or search for runner) Windows: this is in "Settings" MacOS:
  this is in "Preferences" Set "Delegate IDE build/run actions to
  gradle" to true Set "Run test using:" to "Gradle Test Runner" If you
  would prefer to use the built in IntelliJ JUnit test runner, you can
  run gradlew installQuasar which will copy your quasar JAR file to the
  lib directory. You will then need to specify -javaagent:lib/quasar.jar
  and set the run directory to the project root directory for each test.

As mentioned in the comments from manish, make sure to try cleaning the gradle cache as well: ./gradlew clean build deployNodes.
Joel has a good answer for a similar quasar issue on this StackOverflow question: Error when running Corda flow tests from IntelliJ


text:
Q: Mysql database design currently Im working on a project that, at first glance, will require many tables in a database. Most of the tables are fairly straightforward however I do have an issue. One of the tables will be a list of members for the website, things like username, password, contact info, bio, education, etc will be included. This is a simple design, however, there is also a need for each member to have their availability entered and store in the database as well. Availability is defined as a date and time range. Like available on 4/5/2011 from 1pm to 6pm EST, or NOT available every friday after 8pm EST. For a single user, this could be a table on its own, but for many users, Im not sure how to go about organizing the data in a manageable fashion. First thought would be to have code to create a table for each user, but that could mean alot of tables in the database in addition to the few I have for other site functions. Logically i could use the username appended to Avail_ or something for the table name ie: Avail_UserBob and then query that as needed. But im curious if anyone can think of a better option than having the potential of hundreds of tables in a single database.
edit
So general agreement would be to have a table for members, unique key being ID for instance. Then have a second table for availability (date, start time, end time, boolean for available or not, and id of member this applies to). Django might sound nice and work well, but i dont have the time to spend learning another framework while working on this project. The 2 table method seems plausable but Im worried about the extra coding required for features that will utilize the availability times to A) build a calender like page to add, edit, or remove entered values, and B) match availabilities with entries from another table that lists games. While I might have more coding, I can live with that as long as the database is sound, functional, and not so messy. Thanks for the input guys.

A: Not to sound like a troll, but you should take a look into using a web framework to build most of this for you. I'd suggest taking a look at Django. With it you can define the type of fields you wish to store (and how they relate) and Django builds all the SQL statements to make it so. You get a nice admin interface for free so staff can login and add/edit/etc.
You also don't have to worry about building the login/auth/change password, etc. forms. all that session stuff is taken care of by Django. You get to focus on what makes your project/app unique.
And it allow you to build your project really, really fast.
djangoproject.org
I don't have any other framework suggestions that meet your needs. I do... but I think Django will fit the bill.

A: Create a table to store users. Use its primary key as foreign key in other tables.

A: The databases are written to hold many many rows in a table. There are not optimized for table creation. So it is not a good idea to create a new table for each user. Instead give each user an unique identifier and put the availability in a separate table. Provide an additional flag to make an entry valid or invalid.

A: Create a table of users; then create a table of availabilities per user. Don't try to cram availabilities into the user table: that will guarantee giant grief for you later on; and you'll find you have to create an availabilities table then.
Google database normalization to get an idea why.
Take it as truth from one who has suffered such self-inflicted grief :-)


text:
Q: Migrate data between search services I am trying to move a Azure Search service from standard pricing tier to basic. I can't seem to find a way to do that otherwise than create another and manually move data between. I am about to create a temp console project that selects all data from source service and uploads to the destination service. Is there no data migration tool for this?

A: Unfortunately, we do not yet have migration support between tiers in Azure Search and it does require re-creating the index in a new service.  Please know that we understand the importance of this and have it high on our priority list.
Also, when you do this migration of your index, please keep in mind that there are some things you will need to keep in mind.
First off, when you export the data, you will likely be using our paging (skip and top), but note that this paging is limited to 100K documents.  As a result, if you have more than 100K docs, you will need to have some sort of filtering.  Perhaps if you have a State or Province field you could search and $filter where State = 'WA'
If you happen to have the original data for the index in a different location (such as SQL), you will find it easier to do this re-loading from there.
Finally, taking into account all of the above, I have been working on a sample here that shows how to do the exporting and reloading of the schema and data which hopefully will help for smaller indexes (less than 100K docs) but ultimately it is really important to make sure that all of the documents are successfully migrated.
Also, it would be great if you could vote for this feature.


text:
Q: Why is there an ActiveRecord::RecordNotFound in PinsController#show for a link on my pin? I have a link on my footer. It works on every page except when you click it while viewing a pin, it returns the following Error:
ActiveRecord::RecordNotFound in PinsController#show
Extracted source (around line #61):
Couldn't find Pin with 'id'=terms
private
    def set_pin
    @pin = Pin.find(params[:id])
    end

    def correct_user

Why does it encounter this bug only when someone clicks to try to view the link on the footer while on the pin page?
Here are more relevant details:
pins_controller.rb
class PinsController < ApplicationController
before_action :set_pin, only: [:show, :edit, :update, :destroy, :bid]
before_action :correct_user, only: [:edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]

def index
@pins = Pin.all.order("created_at DESC").paginate(:page => params[:page], :per_page => 9)
end

def bid
 Bid.where(user_id: current_user.id, pin_id: @pin.id).each do |bid|
  bid.cancel!
end

bid = Bid.new
bid.user = current_user
bid.pin = @pin
bid.price = params[:price].to_f
bid.quantity = params[:quantity] ? params[:quantity].to_i : 1
bid.save
render json: {
    success: true
}
   end

def show
@existing_bid = @pin.bid_for(current_user)
end

def new
@pin = current_user.pins.new
end

def edit
end

def create
@pin = current_user.pins.new(pin_params)
if @pin.save
  redirect_to @pin, notice: 'Listing was successfully created.'
else
  render action: 'new'
 end
end

def update
if @pin.update(pin_params)
  redirect_to @pin, notice: 'Pin was successfully updated.'
else
  render action: 'edit'
 end
end

def destroy
@pin.destroy
redirect_to pins_url, notice: 'Pin was successfully destroyed.'
end

private
  def set_pin
  @pin = Pin.find(params[:id])
 end

def correct_user
  @pin = current_user.pins.find_by(id: params[:id])
     redirect_to pins_path, notice: "Not authorized to edit this listing." if      @pin.nil?
end

def pin_params
  params.require(:pin).permit(:description, :image, :image2, :image3, :image4, :image5, :manufacturer, :model)
 end
 end

And here is the terms.html.erb

Company

Terms & Conditions

The terms and conditions will be defined in the listing.

Rake routes gives:
auction GET    /auction(.:format)             pages#auction
terms GET      /terms(.:format)               pages#terms
pins GET       /pins(.:format)                pins#index
new_pin GET    /pins/new(.:format)            pins#new
edit_pin GET   /pins/:id/edit(.:format)       pins#edit
pin GET        /pins/:id(.:format)            pins#show

routes.rb
get "about" => "pages#about" #creates about_path
get "contact" => "pages#contact" #creates contact_path
get "auction" => "pages#auction" #creates auction_path
get "terms" => "pages#terms" #creates terms_path
post 'send_mail', to: 'contact#send_mail'
get 'contact', to: 'contact#show'

How can I resolve this error so people can view the terms and conditions when they are already viewing the pin?
Many thanks!

A: I can propose you have a relative link to the terms like href="terms" so clicked in the /pins/1 it gets to /pins/terms, so to fix it you should make it look like href="/terms"


text:
Q: PBS Script: Multiple Jobs, Node Counts, Variables Between unique jobs in the PBS job array, is it possible to manipulate the number of nods used and/or the value of variables used by the program itself?
For example, one script might run my program as different job submissions on 1 node, then 2 nodes, then 3 nodes, etc etc. While another script could change the value of an in program variable incrementally.

A: There isn't a native way to submit this, but it could be accomplished using qalter. You'd want something like:
qsub script.sh -t 1-10
# for ease we'll assume this returned 0[]
for ((i=1; i<=10; i++)); do
  qalter 0[$i] -l nodes=$i

As far as a variable for each job, each array subjob would have $PBS_ARRAYID defined that would tell you the index of the job.
NOTE: this answer assumes TORQUE 2.5 or higher.


text:
Q: Unable to highlight/select textField after filling it with a value using pdf-lib I want to dynamically update fields inside some pdf files and use them. For the sake of user experience, I want the fields to be able to be highlighted so it's easier to copy/paste so I don't have to input the values later manually... but I have been unsuccessful in finding a solution.
Here's my code that fills out the textFields using pdf-lib:
const pdf = await PDFLib.PDFDocument.load(filedata);
const form = pdf.getForm();

var textField = form.getTextField(TEXTFIELD_NAME);

textField.setMaxLength(20);

textField.setText("Some value");

textField.enableReadOnly();
const pdfToBytes = await pdf.save();

And then I create a file using "pdfToBytes", but when opening the PDF using any PDF viewer, I'm unable to highlight/select the value inside the textField.
I have tried textField.disableReadonly, but I actually want the field to be read only, and it doesn't really work in all PDF viewers when doing so anyways.


text:
Q: Conversion failed when converting datetime from character string hi
i have a problem on converting datetime from character string on createddate and leavestartdate column.....
Table structure   createdby varchar(30),createddate datetime, leavetype varchar(30), leavestartdate varchar(30), status varchar(30)
ALTER Procedure [dbo].[sp_SearchLeave]
@createdby      varchar(30) = null ,
@createddate    DateTime    = null ,
@leavetype      varchar(30) = null ,
@leavestartdate varchar(30) = null ,
@status         varchar(30) = null

As
Begin

if @createddate is not null and Len(@createddate) = 0 set @createddate = null
if @leavetype = 'Select' set @leavetype = null
if @leavestartdate is not null and Len(@leavestartdate) = 0 set @leavestartdate = null
if @status = 'Select' set @status = null

Select leaverequestid,leaveenddate,leavetype,leavestartdate,status
from LeaveRequest
where
       (@createdby is null or createdby like '%' + @createdby + '%')
  and  (@createddate is null or createddate like '%' + @createddate + '%')
  and  (@leavetype is null or leavetype like '%' + @leavetype + '%')
  and  (@leavestartdate is null or leavestartdate like '%' + @leavestartdate + '%')
  and  (@status is null or status like '%' + @status + '%')
End

when i execute this sp as a input like
exec sp_SearchLeave '','','','12/15/2010',''
it displays the error message like
Msg 241, Level 16, State 1, Procedure sp_SearchLeave, Line 26
Conversion failed when converting datetime from character string.

A: The reason is likely the like statement.  You're treating a datetime parameter (@createddate) as a string by appending % to it, which you cannot do.


text:
Q: How should I interpret the analog switch states of the ADG788? After reading the datasheet, this is how I interpret the switch states of the ADG788 analog switch:

This interpretation is based on the "Truth table" in the datasheet:

Nevertheless, it feels a bit counter-intuitive. It is weird that the B-poles are connected when the inputs are 0. Wouldn't it be more "intuitive" if the A-poles would be connected at input zero?
I'm a bit worried. It wouldn't be the first time a datasheet makes an error.

A: It would not only be more intuitive if zero activated the first pole, but also more traditional (see the CD4053). And the ADG786 in the same datasheet works that way.
However, the datasheet is unambiguous, and explicitly shows in the image on page 1 that the ADG786 and ADG788 have opposite polarities:

Also, the datasheet got its fourth revision years ago, so it is extremely unlikely that this would be an error that somehow was not detected.
If this does not remove your doubts, you have to test it yourself.


text:
Q: pygeoprocessing - raster calculator I am new in pygeoprocessing and I am trying to do a really simple raster calculation. I would like to calculate element-wise average over several rasters.
I first though pygeoprocessing could handle it the same way R's Raster package does it (stack of rasters and then apply a function) but couldn't find a way to do it so I am trying with the raster calculator.
I have 2 ratsers R1.tif and R2.tif and would like to calculate the raster Rmean.tif with same extent as R1 and R2. Here is what I tried:
import pygeoprocessing.geoprocessing as geop

listraster_uri = [('R1.tif',1),('R2.tif',1)]
rasterout_uri='R.tif'

def avg(r1,r2):
   result_avg=(r1+r2)/2.
   return result_avg

geop.raster_calculator(base_raster_path_band_list=listraster_uri,
            local_op=avg,
            target_raster_path=rasterout_uri,
            datatype_target(np.float32,1),
            nodata_target=-1,
            calc_raster_stats=False)

but I get this error :
TypeError: in method 'Driver_Create', argument 6 of type 'GDALDataType'
because I don't know how to specify the "desired GDAL output type of the target raster"m beside the fact that I don't know if I am doing the right thing here...
Is there a way to stack the ratsers and apply a numpy function like pandas does over dataframes ?

A: You're passing a numpy dtype not a GDAL data type constant as the datatype_target
Try gdal.GDT_Float32 instead:
geop.raster_calculator(base_raster_path_band_list=listraster_uri,
            local_op=avg,
            target_raster_path=rasterout_uri,
            datatype_target=gdal.GDT_Float32,
            nodata_target=-1,
            calc_raster_stats=False)


text:
Q: UsageError: Line magic function `%%bigquery` not found I am very new to Big query. I am trying to load data from a Big query table to pandas dataframe. I followed the syntax given in the documentation here.
Unfortunately, I am getting below error.

I read a stackoverflow solution here, and followed its solution but I got this.

Then, I tried separating the code lines, but I get a new error UsageError: Line magic function %%bigquery not found.

I have been trying for a couple of hours to resolve this. Even restarting the kernel is not working. This works the very first time you run it but not if you run it twice. I have no clue what's going on. Any thoughts?

A: Make sure you have run:
%load_ext google.cloud.bigquery

in a separate cell.
(And don't put comments before the line with %%bigquery in it, as the other answer says.)

A: This can be solved by removing the comments
#-----------------------
#Loading the bigquery ..
#-----------------------

and just retaining the %%bigquery magic syntax as shown below
%%bigquery personas_raw
SELECT * FROM `project-id.dataset.table`

Here is the screenshot of my testing using a sample public dataset WITH COMMENTS  and got the same error message  as your post.

And here is the screenshot of the same syntax when the comment is removed.


text:
Q: bash: syntax error near unexpected token `"firsttry.c"' My code---
#include <stdio.h>

int main(void)
{
    printf("hello, world\n");
}

and I get bash: syntax error near unexpected token `"firsttry.c"'

A: That's a C program, not a shell script. You have to compile it, which gets you an executable you can run.
On a modern Unix/Linux type system, the simplest way to do that is:
$ make firsttry

That only works if your local make(1) installation has rules built into it to make it understand that it can make the firsttry executable from firsttry.c without needing explicit rules in a Makefile.
On systems without that bit of smarts built in, you can do it the old-fashioned way:
$ cc firsttry.c -o firsttry

Either way, then you can run it:
$ ./firsttry
hello, world


text:
Q: Using simplehtmldom (php) to retrieve site images not working on some sites how to fix? I'm trying to retrieve images from any site that has images I'm using simplehtmldom lib in php to scrap the HTML page that the user chose and get only the images of that site ,
some site the lib manage to get the images bug allot of sites it doesn't.it just
get empty result for example this site : http://www.outfitfashion.com/
I'm trying to get this image :
http://www.outfitfashion.com/images/lifestyle/SS12/home.jpg
and its never get it
$url = $urlname;
    $html = file_get_html($url);
    $counter = 0;
    $strTmp ="";
    foreach($html->find('img') as $element) {
        $strTmp = url_to_absolute($url, $element->src);
        $pattern0 = "/\.(?=jpg|gif|png|jpeg|bmp)/i";

        if(preg_match($pattern0,$strTmp))
        {
            $user_albums_photos[$counter] = $strTmp;
            $counter++;
        }

    }
    $comma_separated = implode(",", $user_albums_photos);

Is there a better way? May be other libs in php that can handle complex HTML pages.

A: It is not picking it up because the image is set as a CSS background property to the <div> and not within an <img /> tag. So there is no src="" attribute.
If you want to pick up backgrounds you should look inside the <head> tags for the style sheets then check through them.


text:
Q: How can I troubleshoot this JSON method in DataTables gem? I'm trying to implement the Railscast 340 that demos how to use DataTables, which looks like an awesome gem for my project.
My model is different, of course; but the datatables class the Mr Bates builds (very quickly), in order to do server-side processing, is rather complicated to follow. I got the source code, and basically attempted to follow along. My view comes up with zero records (but there are > 10,000 records), but does not break.
However, here is what the error message output from the rails server says just before it stops:
NameError (undefined local variable or method `genotypes' for #<GenotypesDatatable:0xa9e852c>):
  app/datatables/genotypes_datatable.rb:12:in `as_json'
  app/controllers/genotypes_controller.rb:8:in `block (2 levels) in index'
  app/controllers/genotypes_controller.rb:6:in `index'

Just before this, there appears to be this JSON error, which starts:
Started GET "/genotypes.json?sEcho=1&iColumns=8&sColumns=&iDisplayStart=0&iDisplayLength=10&mDataProp_0=...

The relevant part of the genotypes controller looks like this:
  def index
     respond_to do |format|
      format.html
      format.json { render json: GenotypesDatatable.new(view_context) }
    end
  end

And my genotypes model looks like:
class Genotype < ActiveRecord::Base
  attr_accessible :allele1, :allele2, :run_date
  belongs_to :gmarkers
  belongs_to :gsamples

end

My datatables class is given below. This is from Mr Bates code, modified (most likely incorrectly) to replace his Products model with my Genotypes model:
class GenotypesDatatable
  delegate :params, :h, :link_to, to: :@view

  def initialize(view)
    @view = view
  end

  def as_json(options = {})
    {
      sEcho: params[:sEcho].to_i,
      iTotalRecords: Genotype.count,
      iTotalDisplayRecords: genotypes.total_entries,
      aaData: data
    }
  end

private

  def data
    genotypes.map do |genotype|
      [
        link_to(genotype.name, genotype),
        h(genotype.category),
        h(genotype.released_on.strftime("%B %e, %Y")),
        genotype.run_date
      ]
    end
  end

  def Genotypes
    @Genotypes ||= fetch_Genotypes
  end

  def fetch_genotypes
    genotypes = Genotype.order("#{sort_column} #{sort_direction}")
    genotypes = genotypes.page(page).per_page(per_page)
    if params[:sSearch].present?
      genotypes = genotypes.where("name like :search or category like :search", search: "%#{params[:sSearch]}%")
    end
    genotypes
  end

  def page
    params[:iDisplayStart].to_i/per_page + 1
  end

  def per_page
    params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
  end

  def sort_column
    columns = %w[gmarker gsample allele1 allele2 run_date]
    columns[params[:iSortCol_0].to_i]
  end

  def sort_direction
    params[:sSortDir_0] == "desc" ? "desc" : "asc"
  end
end

Any hints on how to troubleshoot (or fix!) this error much appreciated! (Getting this working for my project would be awesome!)
TIA,
rixter

A: I'm not sure if this is it, but your class has a Genotype method with capital G, it should be all lowercase.


text:
Q: Not able to compile Qt Project - Qt Speech I am trying to compile the project present at Link
While compiling from the main folder I am getting the error:
:-1: error: Project ERROR: qtspeech/examples/speech/qmlspeech/qmlspeech.pro is lacking an install target.

I tried adding following text in the qmlspeech.pro file:
target.path += /home/harshmittal/build
INSTALLS += target

I got the following error:
:-1: error: Project ERROR: /qtspeech/examples/speech/qmlspeech/qmlspeech.pro installs target to unexpected location.

If I try to open the project Individually and try to compile it, I receive the following error:

:-1: error: Project ERROR: You cannot build examples inside the Qt source tree, except as part of a proper Qt build.

I want to compile this project, original youtube link: Video
Qt Version: 5.15
OS: Linux


text:
Q: Generating a slug after Active Record object creation in rails I'm trying to generate a unique slug for an object after the object is created using the after_commit callback.
after_commit :create_slug, on: :create

def create_slug
    self.slug = generate_slug
    self.save
end

When I try to save the object I get a "stack level too deep" error.  I'm assuming because I'm saving the object and it's called the after_commit callback again and again.
What's the best way to generate and save the unique slug in this situation?

A: I recommend using the after_validation callback on create rather than the after_commit.  You will be calling multiple transactions, which is not the intention of this callback.  What I would do is this:
after_validation(on: :create) do
  self.slug = generate_slug
end

Also make sure there are no save actions going on inside the generate_slug.  That method should simply be returning a value to insert into the slug attribute.

A: Use a method that does not trigger callbacks like: update_column
def create_slug
    update_column('slug ', generate_slug)
end


text:
Q: Understanding Call-By-Name in Scala I am new to scala language, therefore I will be grateful if someone could explain me this code-snippet :
object C  {

  def main(args: Array[String]) = {
    measure("Scala"){
      println("Hello Back")
    }
  }

  def measure(x: String)(y: => Unit){
   println("Hello World " + x)
  }
}

Console output :
Hello World Scala

My question is why the program didn't print Hello Back as well? Also is the function/object ;whose body is the instruction println("Hello Back"); stored somewhere on the heap?

A: What distinguishes by-name parameters from normal ones is that the argument expression is evaluated whenever the parameter is used. So if you use it twice, the expression is evaluated twice. And if you don't use it at all, it's never evaluated.
So in your case "Hello Back" is not printed because you never use y.

Also is the function/object ;whose body is the instruction println("Hello Back"); stored somewhere on the heap?

The generated code for by-name parameters is the same as for functions, so it will create a function object on the heap.

A: {
      println("Hello Back")
}

this is a code block, equal to:
def f = {println("Hello World")}
measure("Scala")(f)

so for measure method, you need to explicitly call:
  def measure(x: String)(y: => Unit){
   println("Hello World " + x)
   y
  }


text:
Q: PHP: Select from mysql where 1 week's left to datetime? I have a datetime field in MYSQL database.
They look like this:
2017-02-28 00:15:07

I need to select and return all the results from this field that has 1 week let to that date using PHP...
Is there any built in PHP feature to do this?
something like:
SELECT * FROM tableName WHERE 1 week left to (column name)

any help would be appreciated.

A: You can use interval like the following:
SELECT *  FROM tableName
WHERE NOW() BETWEEN (column_date - INTERVAL 1 WEEK) AND column_date;

That will let you know if now is between the column date - 1 week and the column date.

A: Could be using date_sub and date_create_from_date_string
this is for php
date_sub($date,date_interval_create_from_date_string("7 days"));

http://php.net/manual/en/dateinterval.construct.php
for a select query
select *  FROM tableName
WHERE your_column_date BETWEEN DATE_SUB(NOW(), INTERVAL 1 week) AND NOW();


text:
Q: How do I exclude posts from custom taxonomy from a custom post type archive? I am trying to exclude posts from a custom taxonomy from displaying on a specific custom post type archive. How can I accomplish that? Today, I do this on a per post basis which is not practical. Thanks so much!
    function exclude_taxonomy_from_archive($query) {
        if ($query->is_archive('my-post-type') && $query->is_main_query()) {
            $query->set('post__not_in', array('108747', '105590', '105592', '105594', '105596' ));
        }
    }
    add_action('pre_get_posts', 'exclude_taxonomy_from_archive');

A: Several things to consider so let's look at each one individually:
Preserve Admin Screens
As written, your function affects every page for that post-type, including your admin screens which will hide your filtered posts from all post listings.
Test to see if an admin screen has fired the post type query with is_admin() and return early if so.  Your function is hooked to pre_get_posts and will fire several times on every page load so the concept of returning early and avoiding additional code is important to avoid performance problems.
Post Type Archive
Your use of is_archive() is not doing what you expect it to.  There are no parameters available for is_archive() so the my-post-type is ignored. https://developer.wordpress.org/reference/functions/is_archive/
Using is_post_type_archive( 'my-post-type' ) is the correct way to test if the query is your CPT archive page.  Return early if the query is not (!).
https://developer.wordpress.org/reference/functions/is_post_type_archive/
Exclude Taxonomy
Adding a tax query argument to the main query using the "NOT EXISTS" operator will eliminate any post that has any term for your taxomomy. NOTE: Taxonomy query arguments are an array of array by design.
Tax query documentation: https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters
Don't forget to update my-post-type and my-taxonomy with your actual slugs.
Putting it all together we get:
function wpse_exclude_mytaxonomy_from_archive( $query ) {

    // Three conditions that we want to exit early for
    if ( ( is_admin() ) || ( ! is_post_type_archive( 'my-post-type' ) ) || ( ! $query->is_main_query() ) ) {
        return;
    }

    // Modify the query to exclude posts with any My Taxonomy term
    $taxquery = array(
        array(
            'taxonomy' => 'my-taxonomy',
            'operator' => 'NOT EXISTS',
        )
    );

    $query->set( 'tax_query', $taxquery );

}

add_action('pre_get_posts', 'wpse_exclude_mytaxonomy_from_archive');


text:
Q: Task_InternalError Cannot index into a null array in SSIS Deploy VSTS task run on deployment group phase I am working DevOps with VSTS. Currently I worked on SSIS package deployment through VSTS release for that I used the "SSIS Deploy" task but right now this extension is not available in VSTS market place.
Configuration of SSIS Deploy task at VSTS release level:

The SSIS Deploy task will be worked if I run this task using Agent phase with the Private Agent. But whenever the same task run using Deployment group phase with specified tags, at that time I am facing the issue like

Task_InternalError Cannot index into a null array.

For suppose, If I used SSISDeployPackage task instead of SSIS Deploy task then how to pass the project parameters.
Can anyone suggest me how to resolve the above issue?

A: To trouble shooting the issue for deploy with deployment group, please check with below aspects:

*

*Make sure the target machine of the deployment group is the local machine where your SQL Server database located.

*Make sure the service for the deployment group is logged with the same user name which you can access to your database.
As below example, the user name to log on the service for deployment group target machine is NT AUTHORITY\SYSTEM, you should change the account as your user name instead (such as domain\username), and then restart the service.

A: I had the same problem, the SSIS Deploy task is attempting to access your Integration Service Catalogs. If you have none created, the task throws a 'Cannot index into a null array' error.
To fix this just create an Integration Service Catalog called SSISDB in your target SQL Server before running the SSIS Deploy task.


text:
Q: how to calculate the average temperature of each band of a .grd file? I am having a GRD file in which the temperature at different longitude and latitude are given in a 32x35 array for one day(band),i am having 365 such bands and want to calculate the average of all individual bands.

A: You can use GDAL to convert each band to an array and get the mean of the array with Numpy.
import gdal, numpy

ds = gdal.Open("yourRaster.tif")

bandCount = 1
while bandCount <= ds.RasterCount:
    band = ds.GetRasterBand(bandCount)
    bandArray = band.ReadAsArray()
    print numpy.mean(bandArray)
    bandCount += 1