text:
Q: INCREMENTAR EL VALOR DE UNA VARIABLE PHP PRESIONANDO UN BOTON TIPO SUBMIT
*

*Disculpen tengo un formulario html e hice un reporte en pdf donde tengo una variable PHP llamada Numero. Quisiera saber como se puede hacer para que al momento que presione un boton en mi formulario html en mi otro archivo php donde tengo el pdf que hice la variable que muestro se vaya incrementando n veces.
ejemplo: presiono mi boton en mi HTML en mi pdf se muestre Numero: 10001, vuelvo presionar mi boton y en mi pdf se muestre Numero: 10002 y asì sucesivamente.

Por dar un ejemplo tengo el siguiente Codigo:
+
<!doctype html>

<meta charset="utf-8">
<title>Documento sin título</title>

<?php
if (isset($_POST['genera_do'])){
//Incrementamos el valor
$contador = 1000;
$conta = $_POST["conta"]+1;

}
else{
//Valor inicial
$conta = 1;
}
?>

...

<form name="f1" method="post">

<input type="text" name="conta" value="<?php echo $conta?>">

<button type="submit" class="btn btn-primary"  name="genera_do"> Reporte</button>
</form>

...

*

*El codigo que muestro me funciona pero solo me incrementa de 1 en 1, es decir presiono mi boton y me imprime 1, vuelvo a presionar y me imprime 2 quisiera que empezara a contar desde el 1000, que cuando presione me muestre 1002 y asi sucesivamente

enter image description here

A: Podrías guardar el valor de tus visitas en un archivo.
De esa manera siempre se incrementarán tus visitas.
Esta función podrías adaptarla a tu código.
<?php
   function contarvisitas() {
        $archivo = "contadorvisitas.txt";
        $f = fopen($archivo, "r");
        if($f) {
            $contador = fread($f, filesize($archivo));
            $contador = $contador + 1;
            fclose($f);
        }
        $f = fopen($archivo, "w+");
        if($f) {
            fwrite($f, $contador);
            fclose($f);
        }
        return $contador;
    }
    echo contarvisitas();
?>


text:
Q: Printing contents of a featherlight lightbox which are loaded by ajax
*

*Bootstrap 3.3.6

*jquery 1.12.3

*Featherlight 1.7.9

My web page contains a number of anchors like this:
More info

When a user clicks the "More info" anchor it opens a Featherlight lightbox and populates the contents via an ajax call.
The markup inside the lightbox is fairly simple. It contains a button to "Print this page" which is intended to print the contents inside the lightbox:

Foo

Bar

     <button onclick="printWindow()" class="btn btn-primary">Print this page</button>

There is some js inside the lightbox to handle printWindow():

And some CSS to avoid printing the "print this page" and Featherlight "close" buttons:

This works ok in terms of populating the lightbox, triggering the Print function, and avoiding printing the buttons.
However... If the contents of the page are over 1 page long, it will only print the first page. This is occurring in different browsers and on different machines and operates in a consistent way.
I can't understand why this is occurring because I haven't added any CSS which would make that happen. Why is it cutting off after the first page?
This is how it appears in the print preview after clicking "Print this page". I have deliberately set the length of the content such that it would take 3 pages of A4 paper. It will only print page 1, and if I try and enter a number of pages beyond 1 (i.e. 2, 3, 2-3) it gives an error saying:

Out of bounds page reference, limit is 1

I've mentioned I'm using Bootstrap in case there are some conflicts or reasons this would cause this behaviour. There is no application-specific CSS in place that targets media print or equivalent. The only CSS that targets .ajax-training (where the content resides) is to style the heading and add some padding:
.ajax-training {
    padding: 10px;
}
.ajax-training h3 {
    font-weight: bold;
    color: #022169;
}

The screenshot shows the "two sided" box checked; I have tried it with both checked and unchecked and it makes no difference.

A: To load CSS for print you have to specific that either the entire file is specifically for print or that a section of the code is for print with a media query. Examples of both solutions below:
Entire file:
<link rel="stylesheet" type="text/css" media="print" href="print.css">

Media query:
@media print {
    background: red;
}

So for you it would proberly just be to create a duplicate link to the bootstrap and add the media="print" to it :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where did this value variable come from? I was reading through an example of how to use metaprogramming to make attribute accessors, and I'm a bit confused on where this value variable came from:
class AttrAccessorObject
  def self.my_attr_accessor(*names)
    names.each do | name |
      define_method(name) {
        self.instance_variable_get("@#{name}".to_sym)
      }
      define_method("#{name}=") do | value |
        self.instance_variable_set("@#{name}".to_sym, value)
      end
    end
  end
end

I understand that the instance_variable_set method needs both the instance variable and the value to set the instance variable's new value, but where did this value variable in the code come from? Also, since it's using a "do/end" loop to use the value, I'm assuming that the "define_method("#{name}=") evaluates to an array of values, is that correct?

A: If you think of what a 'normal' method definition looks like:
def some_name=(value)
  @some_name = value
end

The |value| part is the same as (value) - it declares the arguments that are accepted by the method you're defining. So if I wanted to make a method that takes 3 args:
define_method(:some_method) do |arg1, arg2, arg2|
  [arg1, arg2, arg3]
end

Also, since it's using a "do/end" loop to use the value, I'm assuming that the "define_method("#{name}=") evaluates to an array of values, is that correct?

No, blocks are not just used with arrays. Think of a block like an anonymous function that is used as a parameter for another function. The function you call (e.g. each) may internally invoke the anonymous function 0, 1, or any number of times. In the case of each, it calls it N times (one time for each array element):
def my_each(array, &blk)
  for elem in array do
    blk.call(elem)
  end
end

but in the case of tap, it calls it only once:
def my_tap(obj, &blk)
  blk.call(obj)
  obj
end

A: value is part of method signature you are defining.
define_method can be explained as adding a "label" to the block of code and saving it's reference in the class for later consumption.
define_method("print_two_values") do | value1, value2 |
    puts "first: #{value1}, second: #{value2}"
end

Can be rewritten as
def print_two_values(value1, value2)
    puts "first: #{value1}, second: #{value2}"
end

A: It should not go unsaid that there are some weaknesses with the referenced code.

*

*There is no need to convert the first argument of Object#instance_variable_get and Object#instance_variable_set to a symbol.

*(Picky) There is no need for self. to precede instance_variable_get and instance_variable_set, as self is the implied receiver when a method is invoked without an explicit receiver.

*(Mainly) The method is unnecessarily complex as it is much easier to use Ruby's method Module#attr_accessor, which is purpose-built to create getter and setter methods:

class AttrAccessorObject
  def self.my_attr_accessor(*names)
    attr_accessor(*names)
  end
end

AttrAccessorObject.my_attr_accessor "pig", "owl"
  #=> ["pig", "owl"]
AttrAccessorObject.instance_methods(false)
  #=> [:pig, :pig=, :owl, :owl=]
inst = AttrAccessorObject.new
  #=> #<AttrAccessorObject:0x00005661152d6ed8>
inst.owl = 'hoot'
  #=> "hoot"
inst.owl
  #=> "hoot"


text:
Q: WPF Datagrid Row Editing "ENDED" event I know that WPF datagrid has "RowEditEnding" event , but I need to fire the event on after the Row has comitted to check if the newly added row is duplicated and merge the duplicated row. My datagrid has "CanUserAddRow" property set to True.
I am using EntityObservableCollection that extends ObservableCollection to synchronize my entity with the collection. So, i considered OnCollectionChanged event, but the "InsertItem" event is raise once user click on the new item place holder row, which means the object is still empty and I cant check for duplicate.
Is there anyway that I can raise the RowEditEnded event?
Thanks...

A: You can use UpdateSourceTrigger=PropertyChanged on the binding of the property member for the datagrid. This will ensure that when CellEditEnding is fired the update has already been reflected in the observable collection.
see this post https://stackoverflow.com/a/27239243/9285072

A:     private void dgrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
    {
        if (this.dgrid.SelectedItem != null)
        {
            (sender as DataGrid).RowEditEnding -=dgrid_RowEditEnding;
            (sender as DataGrid).CommitEdit();
            (sender as DataGrid).Items.Refresh();
            (sender as DataGrid).RowEditEnding += dgrid_RowEditEnding;
        }
        else Return;

       //then check if the newly added row is duplicated
    }

A: I found an answer to your question usingVS2010
condition if (e.EditAction == DataGridEditAction.Commit) in the RowEditEnding will fulfill ur requirement
Please see the below code.
private void dataGrid1_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
    if (e.EditAction == DataGridEditAction.Commit)
    {
        MessageBox.Show("asd");
    }
}

This is the Xaml Behind.
<DataGrid AutoGenerateColumns="False" CanUserAddRows="True" Height="241"
    RowEditEnding="dataGrid1_RowEditEnding" HorizontalAlignment="Left"
    Name="dataGrid1" VerticalAlignment="Top" Width="573" >
    <DataGrid.Columns>
        <DataGridTextColumn Header="name" Binding="{Binding id}"
            Width="300">
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

A: Taking from @MaherBenIssa's answer, I used this to avoid add and remove delegate:
    private bool locker = true;

    private void dgArticles_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
    {
        if (locker)
        {
            try{
                locker = false;
                (sender as DataGrid).CommitEdit(DataGridEditingUnit.Row, false);
                ((sender as FrameworkElement).DataContext as ViewModel)?.Edit(e.Row.DataContext);
            }
            finally{
               locker = true; //enable editing again
            }
        }
    }

A: Try setting the CommitEdit() function for your datagrid. I used it here:
private void DataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
    this.MyDataGrid.CommitEdit(DataGridEditingUnit.Row, false);
}

A: VB.NET solution to the solution of @MaherBenIssa
Private Sub dgLayer_RowEditEnding(sender As Object, e As DataGridRowEditEndingEventArgs)

    Dim d As DataGrid
    d = DirectCast(sender, DataGrid)

    RemoveHandler d.RowEditEnding, AddressOf dgLayer_RowEditEnding

    dgLayer.CommitEdit()
    sender.Items.Refresh()

    AddHandler d.RowEditEnding, AddressOf dgLayer_RowEditEnding

End Sub

A: Maybe you can use the event "CurrentCellChanged". This fires when you start editing a cell too, but maybe you can find a way to not always do everything you want to do in your method.
I had same problem when i wanted to check if the changes in the datagrid are actually changes to the original values. This event is working for my needs.
Hope i could tell you something new.

A: I wonder why you are finding the way to raise the RowEditEnded event;
if you Implement the RowEditEnding event of datagrid; whenever you edited a row and change the focus from that row, the row will be committed and RowEditEnding will be raised;
so after the Row has committed RowEditEnding will be raised and work just as RowEditEnded;
Did I understand something wrong from your text?


text:
Q: Porting Movino on symbian H all,
I have downloaded the movino for symbian from http://movino.org
But, i 've been facing may build error while building the app for symbian 3rd edition.
Is anyone successfully done this?
Or
Any suggestions  on this?
Thanks,
KB

A: What about the Java ME version of Movino?


text:
Q: How to build a Visual Studio 9.0 solution from Cygwin and get build output? I am trying to set up an automated build system on Windows using Cygwin. Among other things, it needs to be able to build several Visual C++ solutions.  I have a script which sets up the environment variables needed for devenv, and if I type 'devenv' in bash it brings up the Visual Studio IDE.  No problems so far.
I am also able to build a solution from cygwin's bash prompt by typing

$ devenv mysolution.sln /build Debug

The problem is that it is not showing me the build output.  In fact, it does not even tell me whether or not the build succeeded.  The command simply finishes, and I get back the prompt.  Then I can go into the output directory, and check whether or not the executable was created, but for a build system I want to be able to grep for errors.
What am I doing wrong?  I can see the debug output when I run devenv in the windows shell, but not in cygwin.  Where is it being sent, and how do I get it back?

A: Have you considered using MSBuild?  You can use msbuild to build VS solutions without any modifications and it spits output out the stdout.  The command would look something like:
msbuild mysolution.sln /t:Build /p:"Configuration=Debug" /p:"Platform=Win32"

MSBuild is the tool that MS designed to do automated builds, so it may fit your problem a little better than running the devenv.exe.

A: I found a workaround.

devenv mysolution.sln /build Debug /out mylog.txt

will dump the build output into mylog.txt, which is even more convenient for automated builds.  I am still curious why the output doesn't show up on the screen, though.

A: Will cygwin find and run .com files?
There are 2 devenv executables, one is devenv.com which is a console mode application that handles stdin, stdout and stderr proxying for the other executable, devenv.exe, which is a GUI mode application.  If devenv.exe is what cygwin is loading then there will be no stdin/stdout stuff.  If devenv.com is being loaded, it should launch devenv.exe while proxying the stdout stuff to the console.
Maybe if you explicitly specify that devenv.com should be run?

A: last I heard, msbuild in vs 2008 couldn't handle c++ projects.  I think it can in vs 2010.


text:
Q: Ajax load more - hide button if no more content I have a WordPress query (custom post type) and want the user to load more articles with a "load more" button (Ajax). To hide the load more button when there are no more posts I added an "else if" function:
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
$('.loading').hide();
jQuery(function($) {
$('body').on('click', '.loadmore', function(e) {
    $('.loadmore').hide();
    $('.loading').show();
    var data = {
        'action': 'load_posts_by_ajax',
        'page': page,
        'security': '<?php echo wp_create_nonce("load_more_posts"); ?>'
    };

    $.post(ajaxurl, data, function(response) {
        if(response != '') {
            $('.ajax-posts').append(response);
            $('.loadmore').show();
            $('.loading').hide();
            page++;
        } else if(response == 0) {
            $(".ajax-posts").append("No More Records Found");
            $('.loading').hide();
        }
    });
});
});

The problem is that the button only hides on click:
} else if(response == 0) {

But I want to hide the button automatically when there are no more posts to load. So I have to do something like
} else if(response == 'last posts to load') {

Any idea how to do this?
EDIT - this is the query:
add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax',
'load_posts_by_ajax_callback');

function load_posts_by_ajax_callback() {
check_ajax_referer('load_more_posts', 'security');
$date_now = date('Y-m-d H:i:s');
$paged = $_POST['page'];
$args = array(
    'posts_per_page'    => 2,
    'post_type'         => 'termin',
    'meta_query'        => array(
        'key'           => 'end_date',
        'compare'       => '>=',
        'value'         => $date_now,
        'type'          => 'DATETIME'
    ),
    'orderby'           => 'end_date',
    'order'             => 'ASC',
    'meta_type'         => 'DATE',
    'post_status'       => 'publish',
    'paged' => $paged,
);
$my_posts = new WP_Query( $args );
if ( $my_posts->have_posts() ) :
    ?>
    <?php while ( $my_posts->have_posts() ) : $my_posts->the_post(); ?>

    <?php include(get_template_directory().'/termine-ajax.php'); ?>

    <?php endwhile; ?>
    <?php
endif;

wp_die();
}

A: Wordpress has a max page number function. You can use that. But first you'll need to repeat the loop args on the page with the button. Step 1 set up just your args as a function, without the paged part (otherwise it'll come up with an error).
function ajax_args() {
$date_now = date('Y-m-d H:i:s');
$paged = $_POST['page'];
$args = array(
'posts_per_page'    => 2,
'post_type'         => 'termin',
'meta_query'        => array(
    'key'           => 'end_date',
    'compare'       => '>=',
    'value'         => $date_now,
    'type'          => 'DATETIME'
),
'orderby'           => 'end_date',
'order'             => 'ASC',
'meta_type'         => 'DATE',
'post_status'       => 'publish',
'paged' => $paged,
);

return $args;
}

Step 2 - adjust your load_posts_by_ajax_callback() function to load the previous function and add the paged part to it
function load_posts_by_ajax_callback() {

check_ajax_referer('load_more_posts', 'security');

$paged = $_POST['page'];
$args = ajax_args();
$args += array('paged' => $paged,);

$my_posts = new WP_Query( $args );
if ( $my_posts->have_posts() ) :
?>
<?php while ( $my_posts->have_posts() ) : $my_posts->the_post(); ?>

<?php include(get_template_directory().'/termine-ajax.php'); ?>

<?php endwhile; ?>
<?php
endif;

wp_die();

}

Then step 3 - with where your ajax code is, you can call the original loop again (without repeating yourself, which is why we set it up as a separate function) and get the max page from that with $loop->max_num_pages; and impliment it into the ajax with an if statement with the page variable. eg if(page == max_num_pages; ?>) inside the response and before the page++
<?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

$args = ajax_args();

$args  += array(
    'paged' => $paged,
);

$loop = new WP_Query($args);
$last_page = $loop->max_num_pages;
?>

var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
$('.loading').hide();
jQuery(function($) {
$('body').on('click', '.loadmore', function(e) {
$('.loadmore').hide();
$('.loading').show();
var data = {
    'action': 'load_posts_by_ajax',
    'page': page,
    'security': '<?php echo wp_create_nonce("load_more_posts"); ?>'
};

$.post(ajaxurl, data, function(response) {
    if(response != '') {
        $('.ajax-posts').append(response);
        $('.loadmore').show();
        $('.loading').hide();

if(page == <?php echo $last_page; ?>) {

            $('.loadmore').hide();
  }
        page++;

    } else if(response == 0) {
        $(".ajax-posts").append("No More Records Found");
        $('.loading').hide();
    }
  });
 });
});


text:
Q: New line options for braces for properties I know that Visual Studio 2005 did not support new line options for braces for properties, but I am trying to find out if Visual Studio 2012 does. Does anyone know if there is native support for this or of a free extension (i.e., not Resharper) that adds support for this?
Thanks for your help :)

A: No, still there is no options for this.


text:
Q: ObjectArrayArguments class I try to write parametrized test in JUnit 5
@ParameterizedTest
@ArgumentsSource(TwoParameters.class)
public void test(int a, int b){
    //some assert
}

static class TwoParameters implements ArgumentsProvider {

    @Override
    public Stream<? extends Arguments> provideArguments(ExtensionContext extensionContext) throws Exception {
        return Stream.of(
                ObjectArrayArguments.create(1, 2),
                ObjectArrayArguments.create(3, 4));

    }
}

As you can see, there is test function which takes 2 parameters.
I saw one method with @CsvSource and this
I Try to use method above, but I cant return stream contains 2 parameters for the test.
ObjectArrayArguments cannot be resolve.
How to import this class?
I tried import org.junit.jupiter.params.provider.ObjectArrayArguments; but it does not work (Intelij says 'Cannot resolve symbol ObjectArrayArguments')

A: ObjectArrayArguments is not a member of JUnit.
You need to provide a stream of Arguments. You may use the factory method Arguments.of(Object...) to create such instances:
    return Stream.of(
        Arguments.of(1, 2),
        Arguments.of(3, 4)
    );

For further details read the user-guide at http://junit.org/junit5/docs/current/user-guide/#writing-tests-parameterized-tests
Here is an excerpt using MethodSource:
@ParameterizedTest
@MethodSource("stringIntAndListProvider")
void testWithMultiArgMethodSource(String str, int num, List<String> list) {
    assertEquals(3, str.length());
    assertTrue(num >=1 && num <=2);
    assertEquals(2, list.size());
}

static Stream<Arguments> stringIntAndListProvider() {
    return Stream.of(
        Arguments.of("foo", 1, Arrays.asList("a", "b")),
        Arguments.of("bar", 2, Arrays.asList("x", "y"))
    );
}


text:
Q: REGEXP_SUBSTR Remove All Chars after the Match I am trying to extract Work Weeks from user comments, user comments might be like
"Something WW15 Target Complete"
"WW12.3 Good to Go"
Currently my script is grabbing the match but also everything after it,
Result = WW12.3 Good to Go
Ideal Result would be just the WW12.3 part.
I need to do a course and watch demos on REGEXP but thats for another day unfortunately.
SELECT
  BATCH, OPERATOR, COMMENTS, TXN_DATE
 ,REGEXP_SUBSTR(COMMENTS,'WW[^;]+') as ETA
FROM F_LOTCOMMENTHIST

I have also tried doing this to remove everything after a space but it doesnt work:
SELECT
  BATCH, OPERATOR, COMMENTS, TXN_DATE
 ,REPLACE(REGEXP_SUBSTR(COMMENTS,'WW[^;]+'),' [^;]+','') as ETA
FROM F_LOTCOMMENTHIST

I understand that I am probably using the wrong pattern string but I just cant figure out what I need when looking at example tables like:
https://www.techonthenet.com/oracle/functions/regexp_substr.php

A: Would this do? Oracle, though, I don't know db2.
SQL> with test (col) as
  2    (select 'Something WW15 Target Complete' from dual union all
  3     select 'WW12.3 Good to Go'              from dual union all
  4     select 'What is that WW1.2'             from dual
  5    )
  6  select col,
  7         regexp_substr(col, 'WW(\w+)?((\.)?(\d+))') result
  8  from test;

COL                            RESULT
------------------------------ ----------
Something WW15 Target Complete WW15
WW12.3 Good to Go              WW12.3
What is that WW1.2             WW1.2

SQL>

A: I suggest using an online tester of regular expressions to learn using them.
For example this one: https://regexr.com/5p0m6
You can type your expression and text and you'll see directly the behaviour. Take a look at the cheatsheet and explain section.

A: If you want to get WW[digits][dot][digits] not surrounded by any characters except space (may be), you may use negative lookahead & lookbehind (lookarounds) like below.
with test (col) as
(
values
  'SomethingWW15.3 WW12 Target Complete'
, 'WW12.3 Good to Go'
, 'WW12.3What is that WW1.2'
)
select
  col
, regexp_substr(col, '(?<![^ ])WW[\d]+\.?[\d]?(?![^ ])') result
from test;

|COL                                 |RESULT|
|------------------------------------|------|
|SomethingWW15.3 WW12 Target Complete|WW12  |
|WW12.3 Good to Go                   |WW12.3|
|WW12.3What is that WW1.2            |WW1.2 |


text:
Q: Bootstrap carousel and showing multiple items I'm using @paulalexandru(https://stackoverflow.com/users/3522687/paulalexandru) solution to showing multiple items on a bootstrap slider. Unfortunately I'm not advanced enough with javascript to be able to show 4 items(or more or less) instead of the current 3. Can someone break the following code down maybe so I can understand where to even begin to understand what tells the script to only show 3 at a time?
Here's a functioning JS fiddle of Paul's work.
http://fiddle.jshell.net/paulalexandru/at606jpe/light/
I understand the CSS just fine but I know the carousel doesn't solely rely on the CSS for displaying here. I'm trying to make it show x items based on screen size

A: I changed all the:

*

*33% to 25%.

*col-md-4 to col-md-3
And here's the result:

$('#myCarousel').carousel({
    interval: 10000
})

$('.carousel .item').each(function(){
    var next = $(this).next();
    if (!next.length) {
        next = $(this).siblings(':first');
    }
    next.children(':first-child').clone().appendTo($(this));

    if (next.next().length>0) {
        next.next().children(':first-child').clone().appendTo($(this));
    }
    else {
        $(this).siblings(':first').children(':first-child').clone().appendTo($(this));
    }
});
.carousel-inner .active.left  { left: -25%;             }
.carousel-inner .active.right { left: 25%;              }
.carousel-inner .next         { left: 25%               }
.carousel-inner .prev         { left: -25%              }
.carousel-control.left        { background-image: none; }
.carousel-control.right       { background-image: none; }
.carousel-inner .item         { background: white;      }

<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />

    Previous

    Next

Fiddle: http://fiddle.jshell.net/at606jpe/685/


text:
Q: Getting started with JeroMQ in MATLAB I am trying to use JeroMQ from MATLAB,by implementing this example ( How to use jeromq in MATLAB ):
% Author : Dheepak Krishnamurthy
% License : BSD 3 Clause

import org.zeromq.ZMQ;

ctx = zmq.Ctx();

socket = ctx.createSocket(ZMQ.REP);

socket.bind('tcp://127.0.0.1:7575');

message = socket.recv(0);

json_data = native2unicode(message.data)';

message = zmq.Msg(8);
message.put(unicode2native('Received'));

socket.send(message, 0);
socket.close()

The script runs until line:

message = socket.recv(0);

but stucks there.
MATLAB would then not respond anymore and has to be killed with Task Manager.
Can someone give a hint, if there are additional things to do, in order to get this running?

A: JeroMQ call signatures state:
        /**
         * Receive a message.
         *
         * @return the message received, as an array of bytes; null on error.
         */
        public final byte[] recv()
        {
            return recv(0);
        }

        /**
         * Receive a message.
         *
         * @param flags
         *            the flags to apply to the receive operation.
         * @return the message received, as an array of bytes; null on error.
         */
        public final byte[] recv(int flags)
        {
            zmq.Msg msg = base.recv(flags);

            if (msg != null) {
                return msg.data();
            }

            mayRaise();
            return null;
        }

        /**
         * Receive a message in to a specified buffer.
         *
         * @param buffer
         *            byte[] to copy zmq message payload in to.
         * @param offset
         *            offset in buffer to write data
         * @param len
         *            max bytes to write to buffer.
         *            If len is smaller than the incoming message size,
         *            the message will be truncated.
         * @param flags
         *            the flags to apply to the receive operation.
         * @return the number of bytes read, -1 on error
         */
        public final int recv(byte[] buffer, int offset, int len, int flags)
        {
            zmq.Msg msg = base.recv(flags);

            if (msg != null) {
                return msg.getBytes(0, buffer, offset, len);
            }

            return -1;
        }

Your code uses the 2nd one:public final byte[] recv( int flags ){...}
for which your code injects a hardcoded integer value of 0 for the flags parameter.
Next, the int flags meaning is better documented in API as:

The flags argument is a combination of the flags defined below:
ZMQ_NOBLOCK
  Specifies that the operation should be performed in non-blocking mode. If there are no messages available on the specified socket, the zmq_recv() function shall fail with errno set to EAGAIN.

With due care, one may use DONTWAIT flag inside JeroMQ, but some other meaningful options are hard to find from bottom up.
So finally, let's read the ZeroMQ definedand recognised set of flags:
// ------------------------------------------------- // Socket options.
#define ZMQ_HWM                1
#define ZMQ_SWAP               3
#define ZMQ_AFFINITY           4
#define ZMQ_IDENTITY           5
#define ZMQ_SUBSCRIBE          6
#define ZMQ_UNSUBSCRIBE        7
#define ZMQ_RATE               8
#define ZMQ_RECOVERY_IVL       9
#define ZMQ_MCAST_LOOP        10
#define ZMQ_SNDBUF            11
#define ZMQ_RCVBUF            12
#define ZMQ_RCVMORE           13
#define ZMQ_FD                14
#define ZMQ_EVENTS            15
#define ZMQ_TYPE              16
#define ZMQ_LINGER            17
#define ZMQ_RECONNECT_IVL     18
#define ZMQ_BACKLOG           19
#define ZMQ_RECOVERY_IVL_MSEC 20   /*  opt. recovery time, reconcile in 3.x   */
#define ZMQ_RECONNECT_IVL_MAX 21

// ------------------------------------------------- // Send/recv options.
#define ZMQ_NOBLOCK 1    // <<<<<<<<<<<<<<<<<<<<<<<<<<- THIS ONE IS NEEDED
#define ZMQ_SNDMORE 2

// ------------------------------------------------- // I/O Multplexing options.
#define ZMQ_POLLIN  1
#define ZMQ_POLLOUT 2
#define ZMQ_POLLERR 4

// ------------------------------------------------- // Device types.
#define ZMQ_STREAMER  1
#define ZMQ_FORWARDER 2
#define ZMQ_QUEUE     3

EPILOGUE:
If using .recv( 0 ) your code will BLOCK, until the socket-instance indeed receives anything .recv()-able in the local-side from any, possibly existing in some near or farther future, compatible, .connect()-ed remote end ( a REQ socket et al ).
If using .recv( 1 ) your code will NOT BLOCK, but one should properly handle both possible return-states { <msg.data()_Value> | (EXC, NULL) } and consult with ZeroMQ errno details, to act in accord with the signalled situation context.


text:
Q: What do I need to read .mat file in c++ I want to read some .mat file containing nested structs to use the data for a QT-GUI. So I'm using QT Creator.
My problem right now is, that I don't know what Files I need to call the read functions.
Right now I just very simply add all *.h files from matlabroot/extern/include and the file libmat and libmx from matlabroot/bin/win64 to my sourcecode directory.
My code looks like this
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "mat.h"

int main()
{
    MATFile* pmat;

    std::string filename = "x.mat";
    const char* file = filename.c_str();

    printf("Reading file %s...\n\n", file);

    pmat = matOpen(file, "r");
    if (pmat == NULL) {
        printf("Error opening file %s\n", file);
        return (1);
    }

    return 0;
}

I always get the error undefined reference to 'matOpen' but matOpen should be in mat.h.
I just want to run a small minimal example to at least call some of the matlab c++ functions. So I need to know which files are really necessary to put in my working directory.
I'm not really experienced with using someone else's code.


text:
Q: How to save multiple pdf files in array in TypeScript Angular? This is the code in HTML, is an input file with Angular:
 <input type="file" class="btn btn-info" id="archivoPDF" #PDFfile value="Seleccionar PDF(s)" accept="application/pdf" multiple />

And this is the code in TypeScript:
@ViewChild("PDFfile") private archivoPDF=[];
private onAlta() {
    console.log(this.archivoPDF);
  }

But in console only I got one file name.

A: Use the following code.
@ViewChild("PDFfile") private archivoPDF=[];
private onAlta() {
  console.log(this.archivoPDF.nativeElement.files);
}

Hope it helps!


text:
Q: Почему функция ввода чисел в массив не выполняется? Хочу наполнить массив и вывести его значение.
Если выполнять оператор for вне функции, то всё работает. В функции же - нет.
Переменные объявлял и внутри функции и вне её, толка нет.
В чем причина невыполнения функции?
<meta charset="utf-8">
<script>
    var c = parseInt(prompt("How much numbers do you want to put in the array? "));
    var arr1 = [];

    function fill_array(arr1){
        for (var i = 0; i < c; i++){
            var x = parseInt(prompt("Enter the number " + (i+1)));
            arr1.push(x);
            }
        return arr1;
    }

    document_write(fill_array);
</script>

A: Вызвать же надо функцию. И что это за document_write?

var c = parseInt(prompt("How much numbers do you want to put in the array? "));
var arr1 = [];

function fill_array(arr1) {
  for (var i = 0; i < c; i++) {
    var x = parseInt(prompt("Enter the number " + (i + 1)));
    arr1.push(x);
  }
  return arr1;
}

document.write(fill_array(arr1));

A: Вот рабочий вариант:

<meta charset="utf-8">
<script>
    var c = parseInt(prompt("How much numbers do you want to put in the array? "));
    var arr1 = [];

    function fill_array(arr1){
        for (var i = 0; i < c; i++){
            var x = parseInt(prompt("Enter the number " + (i+1)));
            arr1.push(x);
        }
        return arr1;
    }

    document.write(fill_array(arr1));
</script>

У вас две ошибки:

*

*Очевидно, document_write - ерунда полная. document.write - так верно.

*В document.write() вы передаете саму функцию, а не результат ее работы. Чтобы передать результат выполнения функции, нужно ее вызвать. Т.е. так:
document.write(fill_array(arr1));

Вот.


text:
Q: Why this application is taking so much of memory? So my problem is, i created one app for my personal use which fetch the html pages from some sites and then display it in a web browser after some alteration. Every thing is working fine but what perturbed me is the memory that it is taking. After querying for 3-4 terms, memory usage reaches to approximate 300-400 mb.
Some relevant code from the app is
void sentenceBox_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            GC.Collect();
        }
    HtmlDocument hd;
    Word w=new Word();

    private void button1_Click(object sender, EventArgs e)
    {
        button1.Enabled = false;
        status.Text = "Processing english req..";
        if (checkInHis(queryTxt.Text))
        {
            sentenceBox.AllowNavigation = true;
            richTextBox1.Text = w.engDefinition;
            sentenceBox.DocumentText = w.engDefinition;
            status.Text = "Word found in History.DONE!";
            button1.Enabled = true;
            return;
        }
        if (w == null || w.engWordProp != queryTxt.Text)
        {
            w.engWordProp=queryTxt.Text;
            w.loadEngDefn();
            w.engDefnLoadedEvent += new Word.engDefnLoaded(w_engDefnLoadedEvent);
            return;
        }
        w.loadEngDefn();
        w.engDefnLoadedEvent += new Word.engDefnLoaded(w_engDefnLoadedEvent);
    }

    void w_engDefnLoadedEvent(Word sender, EventArgs data)
    {
        sentenceBox.AllowNavigation = true;
        sentenceBox.DocumentText = sender.engDefinition;
        sender.engDefnLoadedEvent -= w_engDefnLoadedEvent;
        button1.Enabled = true;
    }

    private void addToHistory(Word w)
    {
        status.Text = "Saving offline...";
        if (!checkInHis(w.engWordProp))
        {
        history.Add(w);
//        label1.Text = w.engWordProp + " saved in localdb. Database size: " + history.Count;

        w = null;
        }
        else
        {
//                label1.Text = w.engWordProp + " Skipped. Database size: " + history.Count;

        }
    }

    private Boolean checkInHis(string p)
    {
        status.Text = "checking offline storage...";
        foreach (Word item in history)
        {
            if (item.engWordProp == p)
            {
                status.Text = "Word found in history.";
                w = item;
                return true;
            }
        }
        status.Text = "Not found in offline database...";
        return false;
    }

    private void sentenceBox_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        ((WebBrowser)sender).AllowNavigation = false;
    }

    private void button2_Click_1(object sender, EventArgs e)
    {
        button2.Enabled = false;
        status.Text = "Requesting hindi definition...";
        if (checkInHis(queryTxt.Text))
        {
            sentenceBox.AllowNavigation = true;
            sentenceBox.DocumentText = w.hindiDef;
            status.Text = "DONE!";
            button2.Enabled = true;
            return;
        }
        if (w == null || w.engWordProp != queryTxt.Text)
        {
            w.engWordProp=queryTxt.Text;
            w.loadHinDefn();
            w.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEvent);
            return;
        }
        w.loadHinDefn();
        w.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEvent);
    }

    void w_HindiDefLoadedEvent(Word sender, EventArgs data)
    {
        sentenceBox.AllowNavigation = true;
        sentenceBox.DocumentText = sender.hindiDef;
        button2.Enabled = true;
        sender.HindiDefLoadedEvent -= w_HindiDefLoadedEvent;
    }

 private void button3_Click(object sender, EventArgs e)
    {
        button3.Enabled = false;
        saveWord(w);
        button3.Enabled = true;
    }

    private void saveWord(Word w)
    {
        if (w.hindiDef == "")
        {
            w.loadHinDefn();
            w.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEventforHindiSave);
        }
        if (w.engDefinition == "")
        {
            w.loadEngDefn();
            w.engDefnLoadedEvent += new Word.engDefnLoaded(w_engDefnLoadedEventforEnglishSave);
        }
        addToHistory(w);
    }

    void w_HindiDefLoadedEventforHindiSave(Word sender, EventArgs data)
    {
        sender.HindiDefLoadedEvent -= w_HindiDefLoadedEvent1;
        sender.HindiDefLoadedEvent -= w_HindiDefLoadedEventforHindiSave;
    }
    void w_engDefnLoadedEventforEnglishSave(Word sender, EventArgs data)
    {
        sender.engDefnLoadedEvent -= w_engDefnLoadedEventforEnglishSave;
        sender.engDefnLoadedEvent -= w_engDefnLoadedEventforEnglishSave;
    }

    void w_HindiDefLoadedEvent1(Word sender, EventArgs data)
    {
        saveWord(sender);
        sender.HindiDefLoadedEvent -= w_HindiDefLoadedEvent1;
    }

    void w_engDefnLoadedEvent1(Word sender, EventArgs data)
    {
        sender.loadHinDefn();
        sender.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEvent1);
        sender.engDefnLoadedEvent -= w_engDefnLoadedEvent1;
    }

    void initWord(String query)
    {
        queryTxt.Text = query;
        w.engWordProp=queryTxt.Text;
        w.loadEngDefn();
        w.loadHinDefn();
        w.engDefnLoadedEvent += new Word.engDefnLoaded(w_engDefnLoadedEvent);
        w.HindiDefLoadedEvent += new Word.hindiDefLoaded(w_HindiDefLoadedEvent);
    }

Word class
    public Word(string q)
    {
        wb1 = new WebBrowser();
        wb2=new WebBrowser();
        engWord = q;
        hindiDef = "";
        engDefinition = "";
        flagE = false;
        flagH = false;
        engUrl = "http://oxforddictionaries.com/definition/english/" + q + "?q=" + q;
        hindiUrl = "http://dict.hinkhoj.com/hindi-dictionary.php?word=" + q;
        wb1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted); ;
        wb2.DocumentCompleted+=new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
    }

    public delegate void engDefnLoaded(Word sender, EventArgs data);
    public event engDefnLoaded engDefnLoadedEvent;
    protected void onEngDefnLoadCompleated(Word sender, EventArgs data)
    {
        if (engDefnLoadedEvent!=null)
        {
            engDefnLoadedEvent(this,data);
        }
    }

    public void loadEngDefn()
    {
        if (this.engDefinition=="")
        {
  //          wb1 = new WebBrowser();
            wb1.ScriptErrorsSuppressed = true;
            wb1.Url = new Uri(this.engUrl);
        }
        else
        {
            if (engDefnLoadedEvent!=null)
            {
                engDefnLoadedEvent(this, new EventArgs());
            }
        }

    }

    public void loadHinDefn() {
        if (this.hindiDef=="")
        {
    //        wb2 = new WebBrowser();
            wb2.ScriptErrorsSuppressed = true;
            wb2.Url = new Uri(this.hindiUrl);
        }
        else
        {
            if (HindiDefLoadedEvent!=null)
            {
                HindiDefLoadedEvent(this, new EventArgs());
            }
        }

    }
   [NonSerialized]
    HtmlDocument hd;

    void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {

            if (((WebBrowser)sender).ReadyState == WebBrowserReadyState.Complete)
            {
                hd = ((WebBrowser)sender).Document;
                if (e.Url.ToString() == this.hindiUrl)
                {
                    parsePage(hd.GetElementById("maint"), "hindi");
                    ((WebBrowser)sender).DocumentCompleted -= wb_DocumentCompleted;
                    sender = null;
                }
                else
                {
                    parsePage(hd.GetElementById("entryPageContent"), "eng");
                    ((WebBrowser)sender).DocumentCompleted -= wb_DocumentCompleted;
                    sender = null;
                }

            }
    }

    private void parsePage(HtmlElement hd, string lan)
    {
        HtmlElementCollection he;
        if (lan == "eng")
        {
            he = hd.GetElementsByTagName("section");
            foreach (HtmlElement item in he)
            {
                this.engDefinition += item.InnerHtml + "
";
            }
            flagE = true;
            engDefnLoadedEvent(this, new EventArgs());
            wb1 = null;
            wb1.Dispose();
            return;
        }
        else
        {
            he = hd.GetElementsByTagName("div");
            foreach (HtmlElement item in he)
            {
                if (item.GetAttribute("itemprop") == "itemListElement")
                {
                    this.hindiDef += item.GetElementsByTagName("div")[0].InnerHtml + "
";
                }
            }
            flagH = true;
            HindiDefLoadedEvent(this,new EventArgs());
            wb2 = null;
            wb2.Dispose();
            return;
        }
    }

Question: How to remove this memory leak issue ?
sample pic

After query 25 words.

A: First I'd like to point out that just because your application uses 300 - 400 MB of memory doesn't necessarily mean that you have a memory leak. Only if the memory keeps increasing with each requested page and is never released do you have a leak.
Second, in order to diagnose the problem you need to run a memory profiler. If you are using the Premium or Ultimate edition of Visual Studio, it has a memory profile feature. If not you can use either RedGate Memory Profile (14-day free trial) or similar software.
I would also add that the most common cause for leaks in .NET is the use of events where a short lived object attaches itself as an observer/handler to an event raised by a long lived object.

A: Well in the constructor of your Word class you have the following code:
wb1 = new WebBrowser();
wb2=new WebBrowser();

The WebBrowser class does is to instantiate some of the web browsing features of your local IE version.My guess is that WebBrowser being a part of the IE it has a high memory consumption.So imagine that you instantiate 2 WebBrowser objects for each word that you have.You could use a pool system for your WebBrowser objects, but i would replace the behavior of those with an WebClient object which is disposable.
P.S. The Garbage Collector system is a fine tuned system using  GC.Collect(); it's like using a sledgehammer on your code.


text:
Q: ansible-pull cannot exec unable to fork I trying to use ansible-pull to configure a RHEL 7 machine and get the following error.
vm-stg05 | FAILED! => {
    "changed": false,
    "cmd": "/usr/bin/git clone --origin origin 'ssh:********@vm-util01:/srv/git/applications.git' /var/lib/ansible/local",
    "msg": "fatal: cannot exec '/tmp/tmpU255JD': Permission denied\nfatal: unable to fork",
    "rc": 128,
    "stderr": "fatal: cannot exec '/tmp/tmpU255JD': Permission denied\nfatal: unable to fork\n",
    "stderr_lines": [
        "fatal: cannot exec '/tmp/tmpU255JD': Permission denied",
        "fatal: unable to fork"
    ],
    "stdout": "Cloning into '/var/lib/ansible/local'...\n",
    "stdout_lines": [
        "Cloning into '/var/lib/ansible/local'..."
    ]
}

This is a work box and is fairly locked down so I am assuming executing anything in /tmp is forbidden so I tried overriding the location and did not see any difference.
My first attempt was to accept the default setting. I have to run the command with dzdo (which is a Centrify command similar to sudo) and root is homeless so I was not surprised it failed. What bothered me was that it was still using /tmp
$ grep _tmp $ANSIBLE_CONFIG | egrep -v "^#"
remote_tmp     = ~/.ansible/tmp
local_tmp      = ~/.ansible/tmp

My second attempt was to create a directory.
$ grep _tmp $ANSIBLE_CONFIG | egrep -v "^#"
remote_tmp     = /var/lib/ansible/tmp
local_tmp      = /var/lib/ansible/tmp

$ ls -l /var/lib/ansible
total 4
-rwxr-x--- 1 root somegroup 576 Mar 12 12:51 ansiblePull.sh
drwxrwxrwx 2 root somegroup   6 Mar 12 14:08 tmp

The original error message is the output of running it with /var/lib/ansible/tmp.
$ ansible-pull --version
ansible-pull 2.4.2.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/home/wstrater/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible-pull
  python version = 2.7.5 (default, Jun 11 2019, 14:33:56) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]

I even tried it as a normal user in the /etc/sudoers file with and without sudo since this where I want to end up.
ls -l /var/lib/ansible/
total 4
-rwxr-x--- 1 somebody somegroup 576 Mar 12 12:51 ansiblePull.sh
drwxrwxrwx 2 somebody somegroup   6 Mar 12 14:37 tmp

Any help would be appreciated.
Thanks,
Wes.


text:
Q: One of my Panels is not showing What's wrong with my code? The panel named 'leftPanel' is not showing up when i run the program whereas 'flightPanel
        import javax.swing.*;
        import java.awt.*;
        import java.awt.event.ActionEvent;
        import java.awt.event.ActionListener;

    public class TravelAgentSystem {

    public static void main(String[] args){

        JFrame mainFrame = new JFrame();
        mainFrame.setLayout(new BorderLayout());
        mainFrame.setTitle("Main Menu");
        mainFrame.setVisible(true);
        mainFrame.setSize(500,500);
        mainFrame.setLocationRelativeTo(null);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel flightPanel = new JPanel();
        flightPanel.setLayout(new GridLayout(2,2));

        JButton timeb, priceb, hotelb, exitb;
        timeb = new JButton("Time");
        priceb = new JButton ("Price");
        hotelb = new JButton ("Hotels Menu");
        exitb = new JButton ("Exit Program");

        class buttonHandler implements ActionListener{

            public void actionPerformed(ActionEvent event) {
                JButton clickedButton = (JButton)event.getSource();
                String buttonText = clickedButton.getText();
                if (buttonText.equals("Exit Program")) {System.exit(0);}
            }

        }

        buttonHandler handler = new buttonHandler();

        exitb.addActionListener(handler);

        flightPanel.add(timeb);
        flightPanel.add(priceb);
        flightPanel.add(hotelb);
        flightPanel.add(exitb);

        mainFrame.add(flightPanel, BorderLayout.CENTER);

        JPanel travelPanel = new JPanel();
        travelPanel.setLayout(new GridLayout(2,2));
        travelPanel.setVisible(true);

        JPanel timePanel = new JPanel();
        timePanel = new JPanel();
        timePanel.setLayout(new GridLayout(2,1));
        timePanel.setVisible(true);

        JPanel leftPanel = new JPanel();
        leftPanel.setLayout(new GridLayout(2,1));
        leftPanel.setVisible(true);

        JLabel Lfrom, Lto, LDeparture;
        Lfrom = new JLabel("From");
        Lto = new JLabel("To");
        LDeparture = new JLabel("Departure Date (DD/MM/YY)");

        String[] fromOptions = {"East Midlands","Birmingham","Heathrow","Manchester"};
        String[] toOptions = {"New York", "Dahab", "Rome", "Sydney", "Tokyo"};

        JComboBox fromDest = new JComboBox(fromOptions);
        JComboBox toDest = new JComboBox(toOptions);

        JPanel datePanel = new JPanel();
        datePanel.setLayout(new FlowLayout());   // So i can fix size of dateField
        JTextField dateField = new JTextField();
        dateField.setPreferredSize(new Dimension(100,20));
        datePanel.add(dateField);

        travelPanel.add(Lfrom);
        travelPanel.add(fromDest);
        travelPanel.add(Lto);
        travelPanel.add(toDest);

        timePanel.add(LDeparture);
        timePanel.add(datePanel);

        leftPanel.add(travelPanel);
        leftPanel.add(timePanel);

        mainFrame.add(leftPanel, BorderLayout.EAST);

    }
}

A: Call mainFrame.setVisible(true); in last. I.e,
mainFrame.add(leftPanel, BorderLayout.EAST);
    mainFrame.setVisible(true);

Here's what I get :


text:
Q: Add contact to pushbullet with the api I'm trying to add a contact to my contacts on pushbullet using the api.
I send following json data with my POST request to https://api.pushbullet.com/v2/contacts
{ "name": "some name", "email": "test@example.com" }

According to the documentation this should add the contact.
Instead I get a bad request error.
When requesting my list of contacts via the api, it is always empty. I can add contacts using the Windows desktop client and via the web. However those contacts only show up on the desktop and on the web, not when using the api.

A: This request works fine for me, what exactly is the request you are using and what does the bad request error say?
Contacts were recently replaced with /v2/chats, which is not documented yet, I should replace them in the docs, sorry about that!


text:
Q: Warning from GAM predicting deaths from weather time series data: ti(time) vs ti(year, day_of_year) in mgcv I am getting the following warning when running a generalised additive model (GAM) with the R package mgcv:
Warning in newton(lsp = lsp, X = G$X, y = G$y, Eb = G$Eb, UrS = G$UrS, L = G$L,  :
  Fitting terminated with step failure - check results carefully

I am modelling the effect of temperature and other weather variables on daily number of deaths. Because deaths may occur not just on the same day but also over a period of time following particularly high exposure, distributed lag needs to be included in the model. I am interested in understanding how day-to-day variability in temperature relates to deaths and not/ less interested in understanding the effects of seasonality and long-term trend, which I am trying to "remove"/ control for.
I am trying to decide between two approaches to model time:

*

*a single predictor for time e.g. s(time) where time is a counter running from 1 to 5,113 (the total number of days in the data set), like

    m1 <- gam(deaths~s(time, k = 500) + heap +
                     s(temp_max, k=25) +
                     s(lag, k=5) +
                     ti(temp_max, lag, k=c(25,5)),
                     data = dat, family = nb, method = 'ML')

*using a ti() interaction with year and doy (day of year), where year models the long-term trend, doy models seasonality and ti(year, doy) models the interaction between long-term trend and seasonality (e.g. El-Nino/ la Nina effects) like

   knots <- list(doy=c(0.5, 366.5))

   m2 <- gam(deaths~ s(year, k= 14) +
                     s(doy, k=100, bs = 'cc') +
                     ti(year, doy, bs = c('tp', 'cc'), k = c(10, 20)) + heap +
                     s(temp_max, k=25) + s(lag, k=5) +
                     ti(temp_max, lag, k=c(15,5)),
                     data = dat, family = nb, method = 'ML', knots = knots)

Model m2 leads to the warning mentioned above. What does this warning mean and how should I resolve it?
The output from gam.check(m2) is as follows:
Method: ML   Optimizer: outer newton
step failed after 13 iterations.
Gradient range [-2.330371,775600.9]
(score 8841.651 & scale 1).
eigenvalue range [-447129799866,5.309916].
Model rank =  525 / 526

Basis dimension (k) checking results. Low p-value (k-index<1) may
indicate that k is too low, especially if edf is close to k'.

                       k'      edf k-index p-value
s(year)          1.30e+01 1.07e+01    0.96   0.085 .
s(doy)           9.80e+01 1.50e+01    0.95   0.005 **
ti(year,doy)     1.62e+02 1.01e+01    0.96   0.065 .
s(temp_max)      2.40e+01 3.08e+00      NA      NA
s(lag)           4.00e+00 1.73e-14      NA      NA
ti(temp_max,lag) 5.60e+01 1.80e+01      NA      NA
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Only after substantially reducing k and changing default tprs splines to cubic regression splines, does the warning disappear, as in model m3:
    m3 <- gam(deaths~ s(year, k= 5, bs = 'cr') +
                      s(doy, k=20, bs = 'cc') +
                      ti(year, doy, bs = c('cr', 'cc'), k = c(8, 10)) + heap +
                      s(temp_max, k=8, bs = 'cr') +
                      s(lag, k=5, bs = 'cr') +
                      ti(temp_max, lag, k=c(8,5), bs = c('cr', 'cr')),
                      data = dat, family = nb, method = 'ML', knots = knots)

For anyone interested, the daily time series data (5,113 days), spanning 14 years from 2001-2014, looks as follows:
           date doy year time heap heap_bin deaths  temp    sh    rh  solar wind2m precip_hourly precip_daily_total
1016 2003-10-13 286 2003 1016    0        0      3 32.37 19.10 61.19 701.45   0.50          0.43               4.58
1017 2003-10-14 287 2003 1017    0        0      3 29.97 19.53 71.69 773.80   2.02          0.68               4.60
1018 2003-10-15 288 2003 1018   34        1     21 29.06 18.43 71.56 852.81   1.59          0.73               3.47
1019 2003-10-16 289 2003 1019    0        0      4 27.54 18.01 76.38 701.43   1.57          0.76               6.32
1020 2003-10-17 290 2003 1020    0        0      2 29.86 17.76 65.88 669.89   2.15          0.36               3.49
1021 2003-10-18 291 2003 1021    0        0      5 31.03 16.91 58.56 857.88   3.14          0.03               0.21

Explanation of some variables: doy = day of year, running from 1-366, time = a counter of days running from 1 – 5,113, temp = temperature, sh = specific humidity, solar = solar irradiance, wind2m = wind speed and precip_daily_total = total daily rain fall. Heap and heap_bin are explained below.
The data set (.rds and .csv) can be found on my GitHub site.
The full code is below. Any help would be greatly appreciated!
library(readr)
library(mgcv)

df <- read_rds("data_crossvalidated_post.rds")

# Create matrices for 7-day lagged variables based on example by Simon Wood (ref in post)

lagard <- function(x,n.lag=7) {
    n <- length(x); X <- matrix(NA, n, n.lag)
    for (i in 1:n.lag) X[i:n,i] <- x[i:n-i+1]
    X
}

df$heap <- as.factor(df$heap)
df$heap_bin <- as.factor(df$heap_bin)

dat <- list(lag=matrix(0:6, nrow(df), 7,
         byrow=TRUE), deaths=df$deaths,
         doy=df$doy, year = df$year,
         time = df$time, heap=df$heap,
         heap_bin = df$heap_bin)
dat$precip_hourly <- lagard(df$precip_hourly)
dat$precip_daily_total <- lagard( df$precip_daily_total)
dat$temp <- lagard(df$temp)
dat$sh <- lagard(df$sh)
dat$rh <- lagard(df$rh)
dat$solar <- lagard(df$solar)
dat$wind2m <- lagard(df$wind2m)

knots <- list(doy=c(0.5, 366.5)) # set knots for
    # cyclic spline for day of year

# model currently being attempted to run

m3 <- gam(deaths~te(year, doy, bs = c('cr', 'cc'),
     k = c(7, 50)) + heap  +
     te(temp, lag, k=c(8, 4),
     bs = c('cr', 'cr')) +
     te(sh, lag, k=c(8,4), bs = c('cr', 'cr')) +
     te(solar, lag, k=c(8,4), bs = c('cr', 'cr'))
     + te(wind2m, lag, k=c(8,4), bs = c('cr',
     'cr')) + te(precip_daily_total, lag,
     k=c(8,4), bs = c('cr', 'cr')) +
     te(temp, sh, solar, wind2m, lag,
     bs = c('cr', 'cr', 'cr', 'cr', 'cr')),
     data = dat, family = poisson,
     method = 'REML', knots = knots)


text:
Q: How to add subscript and superscript in WordPress page titles It is possible to add subscript and superscript in a WordPress page title? I need to add pages with "H2O" in the title.
I have been searching, but cannot find anything with answers... only a few non-answered threads on wordpress.org forums.

A: You can use markup in titles. H2O will work just fine. I would use H₂O with a real ₂ because markup will be stripped in title attributes and in feeds.
Note that WordPress will not create a pretty permalink for the correct character. The slug for my example will look like this: h2o-h%e2%82%82o.
You need my plugin Germanix URL to get h2o for both variants.


text:
Q: How to delete worker task templates in AWS Augmented AI? I've created the worker task template for test in AWS Augmented AI.
However, I don't know how to delete those template.
Please tell me how to do it.
image

A: You cannot currently delete HumanTaskUis. That may be a capability added in the future.

A: You can now delete a HumanTaskUi
Boto3
client = boto3.client('sagemaker', REGION)

response = client.delete_human_task_ui(HumanTaskUiName=HUMAN_TASK_UI_NAME)

AWS CLI


text:
Q: XPath query filtering by date I have some sample XML where I am querying for nodes based on a date.
Sample XML document:
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>
<NewDataSet>

        <EmployeeBankGUID>dc396ebe-c8a4-4a7f-85b5-b43c1890d6bc</EmployeeBankGUID>
        <ValidFromDate>2012-02-01T00:00:00-05:00</ValidFromDate>

        <EmployeeBankGUID>2406a5aa-0246-4cd7-bba5-bb17a993042b</EmployeeBankGUID>
        <ValidFromDate>2013-02-01T00:00:00-05:00</ValidFromDate>

        <EmployeeBankGUID>2af49699-579e-4beb-9ab0-a58b4bee3158</EmployeeBankGUID>
        <ValidFromDate>2014-02-01T00:00:00-05:00</ValidFromDate>

</NewDataSet>

So there are basically three dates:

*

*2/1/2012

*2/1/2013

*2/1/2014

Using MSXML I can query and filter by these dates using an XPath query:
/NewDataSet/Table[ValidFromDate>"2013-02-12"]

And this works, and returns an IXMLDOMNodeList containing one item:

    <EmployeeBankGUID>2af49699-579e-4beb-9ab0-a58b4bee3158</EmployeeBankGUID>
    <ValidFromDate>2014-02-01T00:00:00-05:00</ValidFromDate>

Except it doesn't work anymore
That XPath query using using MSXML; the variant of xml that Microsoft created in the late 1990's, before the W3C standardized on a completely different form of XPath.
DOMDocument doc = new DOMDocument();
//...load the xml...
IXMLDOMNodeList nodes = doc.selectNodes('/NewDataSet/Table[ValidFromDate>"2013-02-12"]');

But that version of MSXML is not "standards compliant" (since it was created before there were standards). Since 2005 the recommended one, the one that follows the standards, the only one that has features I require is MSXML 6.
It's a simple change, just instantiate a DOMDocument60 class rather than a DOMDocument class:
DOMDocument doc = new DOMDocument60();
//...load the xml...
IXMLDOMNodeList nodes = doc.selectNodes('/NewDataSet/Table[ValidFromDate>"2013-02-12"]');

Except the same XPath query returns nothing.
What is the "standards compliant" way to filtering a value by date?
Pretend it's a string, you say
You might be thinking that I might be thinking that XML is treating the 2013-02-01T00:00:00-05:00 as some sort of special date, when in reality it's a string. So maybe I should just think of it like string comparisons.
Which would work, except that it doesn't work. No string comparison works:

*

*/NewDataSet/Table[ValidFromDate<"a"] returns no nodes

*/NewDataSet/Table[ValidFromDate>"a"] returns no nodes

*/NewDataSet/Table[ValidFromDate!="a"] returns all nodes

*/NewDataSet/Table[ValidFromDate>"2014-02-12T00:00:00-05:00"] returns no nodes

*/NewDataSet/Table[ValidFromDate<"2014-02-12T00:00:00-05:00"] returns no nodes

*/NewDataSet/Table[ValidFromDate!="2014-02-12T00:00:00-05:00"] returns no nodes

So, there we have it
What is the "standards compliant" way to achieve what used to work?
What is the "correct" way to XPath query for date strings?
Or, better yet, why are my XPath queries not working?
Or, better better yet, why does the query that used to work no longer work? What was the decision that was made that decided the syntax was bad. What were edge cases they were solving by "breaking" the query syntax?
MSXML6 compatible version
Here's the final functional code, nearly in the language I use:
DOMDocument60 GetXml(String url)
{
   XmlHttpRequest xml = CoServerXMLHTTP60.Create();
   xml.Open('GET', url, False, '', '');
   xml.Send(EmptyParam);

   DOMDocument60 doc = xml.responseXML AS DOMDocument60;

   //MSXML6 removed all kinds of features originally present (thanks W3C)
   //Need to use Microsoft's proprietary extensions to get some of it back (thanks W3C)
   doc.setProperty('SelectionNamespaces', 'xmlns:ms="urn:schemas-microsoft-com:xslt"');

   return doc;
}

DOMDocument doc = GetXml('http://example.com/GetBanks.ashx?employeeID=12345');

//Finds future banks.

//Only works in MSXML3; intentionally broken in MSXML6 (thanks W3C):
//String qry = '/NewDataSet/Table[ValidFromDate > "2014-02-12"]';

//MSXML6 compatible version of doing the above (send complaints to W3C);
String qry = '/NewDataSet/Table[ms:string-compare(ValidFromDate, "2014-02-12") >= 0]';

IXMLDOMNodeList nodes = doc.selectNodes(qry);

A: XPath is not date-aware

What is the "correct" way to XPath query for date strings?

In XPath 1.0, there is no way to handle date strings, just think of time zone support. At least there is no correct way to handle them. Comparing strings will fail if timezones are different.
Comparing strings

Or, better yet, why are my XPath queries not working?

XPath 1.0 only defines equality operators on strings, for greater/less than the values have to be converted to numbers.
Use ms:string-compare which was introduced in MSXML 4.0.
/NewDataSet/Table[
  ms:string-compare(ValidFromDate, "2014-02-12T00:00:00-05:00") > 0
]

For the rest of the (XML) world

What is the "standards compliant" way to achieve what used to work?

An alternative that also works in other XPath implementations (I tested it using xmllint, which uses libxml) might be to translate away all non-string characters, so the string will be parseable as a number:
/NewDataSet/Table[
  translate(ValidFromDate, "-:T", "") < translate("2014-02-12T00:00:00-05:00", "-:T", "")
]


text:
Q: How to debug an X session shutting down by itself I currently have a very curious "crash" under X when I run a particular application. I say "crash" because as far as I can tell neither the application (HandBrake's ghb) or X crash. I've verified both by running under gdb and they both seem to exit of their own accord.
Looking at my system log there is no sign of crash, just of my X session shutting down:
Jan 22 12:16:03 danny dbus[340]: [system] Activating via systemd: service name='org.freedesktop.hostname1' unit='dbus org.freedesktop.hostname1.service'
Jan 22 12:16:03 danny systemd[1]: Starting Hostname Service...
Jan 22 12:16:04 danny dbus[340]: [system] Successfully activated service 'org.freedesktop.hostname1'
Jan 22 12:16:04 danny systemd[1]: Started Hostname Service.
Jan 22 12:16:05 danny lightdm[27656]: pam_unix(lightdm:session): session closed for user alex

And my .xsession-errors just shows the consequence of X going away:
[../../i3-4.13/i3bar/src/xcb.c:1074] ERROR: X11 connection was closed unexpectedly - maybe your X server terminated / crashed?
[27849:27849:0122/121605:ERROR:x11_util.cc(87)] X IO error received (X server probably went away)
[libi3] ../../i3-4.13/libi3/font.c Using X font -misc-fixed-medium-r-normal--13-120-75-75-C-70-iso10646-1

Obviously something that ghb is doing is bringing something down in a critical way but it's hard to tell what. Given there are no crashes or core dumps what's the best way to debug this? Is there a way to snoop on the X messages and work out what the last command sent to the server way? Could this be a broken toolkit?


text:
Q: Cuándo tipar en typescript y cuándo no? tengo una pregunta teórica que no encontré respuesta en ningún lado.
Cuándo es bueno tipar mis estructuras con typeScript? lo es siempre? por qué?

A: ¿Qué es una estructura de datos y que es un objeto?
Una estructura de datos no es más que una definición de propiedades/atributos, mientras que un objeto es una estructura de datos pero que además tiene funciones (Como una clase, por ejemplo).
En la practica tanto una estructura de datos como un objeto se pueden representar con clases, la diferencia es que para crear una estructura de datos no se deben implementar métodos según los programadores más puristas (Hay otros programadores que permiten en sus estructuras métodos get-set sin implementar lógica para estos, ya que al implementar lógica estás creando un objeto, pero esto no seria una buena practica de estructura).
¿Por qué definir tipos de datos para mis estructuras?
La ventaja de las estructuras de dato es que la persona sepa que dicha estructura siempre le retornará esas propiedades (aunque algunas estén vacías o posean valores por defecto), lo que permite evitar un par de comprobaciones para asegurar que la propiedad existe en el objeto antes de comenzar con el desarrollo de la lógica, del contrario no tiene sentido utilizar estructuras.
Si el lenguaje lo permite estas propiedades siempre deben estar tipadas, para asegurar que el tipo de dato es el adecuado cuando posteriormente se llama en la lógica de tu aplicación.
Imagina este escenario, en tu aplicación un usuario puede tener un objeto de configuración de la aplicación, donde puede configurar muchos parámetros y algunos de ellos son listas(array).
Sin utilizar estructura, utilizando solo objetos tendrás que validar que la propiedad exista para poder guardar en una base de datos o rescatar el valor, además, si no defines la propiedad de ese objeto nunca la tendrá, por lo cual debes siempre guardar las propiedades que configure o no el usuario, del contrario es muy probable que tengas problemas de integridad y para evitar eso habrá un aumento exagerado de validaciones.
Si utilizas una estructura esas propiedades siempre existirán, por lo cual simplemente te encargas de validar el contenido.
Ahora, si estás trabajando con propiedades no tipadas y posteriormente para una propiedad de dicho objeto de configuración necesitas hacer un ciclo de iteración tendrás que validar que realmente sea un objeto iterable, del contrario obtendrás una excepción.
Si utilizas una estructura de datos tipada, podrás iterar sin hacer validaciones de tipo previo, ya que tu estructura te asegurará que tu propiedad siempre será iterable.
Ventajas del tipado
Esto en realidad es algo más del lenguaje y se basa en opiniones posiblemente, por lo cual arruinaría mi respuesta, pero si quieres saber cuales son las ventajas de los lenguajes tipados, te invito a revisar el buen amigo google.


text:
Q: Android - Set minimum and maximum time for Time picker I am trying to set the min and max time for time picker. I am giving the values like following
1 -> min - 10:00 and max - 12:00
2 -> min - 15:00 and max - 18:00
3 -> min - 19:00 max 20:00
4 -> min - 23:00 max 24:00
And I am using the following code:
@Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                boolean flag = true;

                if (hourOfDay <= maximumHour && hourOfDay >= minimumHour) {
                    if (hourOfDay == maximumHour && hourOfDay == minimumHour) {
                        if (minute > maximumMin)
                            flag = false;
                        else if (minute < minimumMin)
                            flag = false;
                        else if (minute == maximumMin && minute == minimumMin) {
                            flag = false;
                        } else if (minute == maximumMin) {
                            flag = false;
                        } else if (minute == minimumMin) {
                            flag = false;
                        }
                    } else if (hourOfDay == maximumHour) {
                        if (minute > maximumMin) {
                            flag = false;
                        }
                    } else if (hourOfDay == minimumHour) {
                        if (minute < minimumMin)
                            flag = false;
                    }
                    if (flag) {
                        curHour = hourOfDay;
                        curMin = minute;
                    } else {
                        updateTime(curHour, curMin);

                    }
                }
}

This code is working for 2nd and 3rd scenarios. But for 1st and 4th scenarios I can not set the time to 12 AM or 12 PM. I can set upto 11:59 AM and 11:59 PM.
I verified Android TimePickerDialog set max time this too. But I am getting same issue. please help me on this.

A: try     datePicker.setMaxDate();
datePicker.setMinDate();
please check this link as well : enter link description here


text:
Q: Build eclipse deployable feature in cli or update site in cli I have below 3 packages
eclipse plugin,
eclipse feature and
update site
Now I have to build eclipse feature in cli as same as right click over feature -> Deployable feature -> archive.zip . Tried with maven tycho but it is building jar not the archive file.
Otherwise I have to build update site in cli as same as open site.xml -> Build all. Tried with p2 publisher but it is not creating contents.jar, artifact,jar, plugin and feature folders.
Please help me to automate the build in cli.
Regards,
Sunil


text:
Q: Finding min values in a 3D array across one axis and replacing the non-corresponding values in another 3D array with 0 without loops in python Let's say we have two 3D arrays, A(x,y,z) and B(x,y,z) that x,y,z  are dimensions. I want to identify all the minimum values across the z-axis in the A array and then based on those values and their indices choose the corresponding values in the B, keep them and replace other values with zero.

A: You can think of it a little differently. Finding the locations of the minima in A is straightforward:
ind = np.expand_dims(np.argmin(A, axis=2), axis=2)

You can do one of the following things:

*

*Simplest: create a replacement of B and populate the relevant elements:
 C = np.zeros_like(B)
 np.put_along_axis(C, ind, np.take_along_axis(B, ind, 2), 2)

*Same thing, but in-place:
 values = np.take_along_axis(B, ind, 2)
 B[:] = 0
 np.put_along_axis(B, ind, values, 2)

*Convert the index to a mask:
 mask = np.ones(B.shape, dtype=bool)
 np.put_along_axis(mask, ind, False, 2)
 B[mask] = 0

You can replace the calls to take_along_axis and put_along_axis with suitable indexing expressions. In particular:
indx, indy = np.indices(A.shape[:-1])
indz = np.argmin(A, axis=-1)

The examples above then transform into

*

*New array:
 C = np.zeros_like(B)
 C[indx, indy, indz] = B[indx, indy, indz]

*In-place:
 values = B[indx, indy, indz]
 B[:] = 0
 B[indx, indy, indz] = values

*Masked:
 mask = np.ones(B.shape, dtype=bool)
 mask[indx, indy, indz] = False
 B[mask] = 0


text:
Q: iPhone OpenGL augmented reality I am writing an iOS application (Xcode/swift) that capture real time images on the iPhone back camera.
I have a transparent GLView and i want to display some objects in order to make augmented reality.
I know the field of view of this camera (about 60°). This value is transmit to GLKMatrix4MakePerspective.
But the sizes does not match with reality.
Does one OpenGL unit is one meter on the reality ? Is there a calibration to do ?


text:
Q: WhatsApp Api: как получить ссылку приглашения в группу чата? Есть очень хорошая библиотека для работы с WhatsApp Api:
https://github.com/mgp25/Chat-API
В ней есть требуемые методы для работы с группой чата (создание группы, добавление/удаление участников):
https://github.com/mgp25/Chat-API/wiki/WhatsAPI-Documentation#creating-a-group
Но, в ней не предусмотрена возможность получить ссылку приглашения в группу чата.
Ссылки на приглашение в группу чата такого вида: https://chat.whatsapp.com/oMXlKBIlJc7CxQWiBr6VA7
Подскажите, как можно получить ссылку приглашения в группу чата через WhatsApp Api?
В самом приложении ссылку приглашения в группу чата можно получить следующим образом:


text:
Q: Matplotlib errorbar plot does not use marker cycling In the following example, the error bar plot does not use the marker cycle specified in the axes rc, although it does use the color cycle. Specifying fmt rather than marker in the cycler throws an AttributeError: Unknown property fmt. How can I use the prop_cycle to specify the markers of an error bar plot? I am using Matplotlib 1.5.1 and Python 3.5.1.
import matplotlib.pyplot as plt
from cycler import cycler
plt.rc('axes', prop_cycle=cycler(color=['orange', 'violet', 'darkgreen'],
                                 marker=['s', 'o', 'd']))
plt.rc('lines', linestyle=None)
plt.errorbar((0, 1), (1, 0), yerr=(0.1, 0.1))
plt.errorbar((0, 1), (0, 1), yerr=(0.1, 0.1))
plt.errorbar((0, 1), (0.5, 0.75), yerr=(0.1, 0.1))

A: Although this doesn't answer the question as posed, there are two ways to get around this using a prop_cycle. One is to simply use a for loop to construct the graphs. If you'd rather not use a for loop, you can define a generator function to yield values of the markers. This has the disadvantage that it doesn't automatically reset for every axis, but I think its easier to use than a for loop. The while True: statement is necessary to get it to loop back to the beginning as though it were a cycle of markers to use.
import matplotlib.pyplot as plt
from cycler import cycler

def mfunc(syms):
    while True:
        for s in syms:
            yield s

markers = ['s', 'o']
mark = mfunc(markers)
plt.rc('axes', prop_cycle=cycler(color=['orange', 'violet', 'darkgreen']))
plt.rc('lines', linestyle=None)
plt.errorbar((0, 1), (1, 0), yerr=(0.1, 0.1), marker=next(mark))
plt.errorbar((0, 1), (0, 1), yerr=(0.1, 0.1), marker=next(mark))
plt.errorbar((0, 1), (0.5, 0.75), yerr=(0.1, 0.1), marker=next(mark))


text:
Q: Getting data from Database and storing into Dictionary I am trying to get the data from a MySQL table and storing it into a dictionary. I know I can do that with a loop but DB table contains more than a million tuples and will slow the progress. Is there any way to do that without having to loop all the entries?
DB table has two columns, 1st(key) float type and 2nd(value) varchar.
My Current approach:
public static Dictionary<Single, string> GetData()
{
   Dictionary<Single, string> dic= new Dictionary<Single, string>();
   string query = "select * from table;";
   if (OpenConnection() == true)
   {
        try
        {
            MySqlCommand cmd = new MySqlCommand(query, connection);
            MySqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
            {

               //Something to store DB columns into dictionary without having to loop.

            }
            reader.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
   }
   return dic;
}

A: Next is what you want:
try
    {
        MySqlCommand cmd = new MySqlCommand(query, connection);
        MySqlDataAdapter msda = new MySqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        msda.Fill(ds);
        your_control.DataSource = ds;
        your_control.DataBind();
        //your control means some repeater, or gridview, or anything else, which may show all your elements together.
    }

But you also should consider that if you have millions of records, it would be better to make them selected partially. For example, 100 records per page, using row_number or similar methods


text:
Q: Is HQL still supported in NativeQuery calls in Hibernate 5? According to latest Hibernate docs section 17.3, this should work:
List<Person> persons = session.createNativeQuery(
        "SELECT * FROM Person", Person.class)
    .getResultList();

I have a nearly identical query and I'm getting an exception:
java.sql.SQLException: Invalid object name 'Person'

I'm using hibernate-core-5.2.10.FINAL.
After stepping through the source, it never branches off to look at the entity graph like a normal HQL query does.
Anyone else seeing this? I can post more details for the curious, and will add more stuff as I continue to debug...
I ran the same query after downgrading Hibernate to 5.0.12 with the same result. Although, in Hibernate 5.0 there is no "nativeQuery" method on session, it's "createSQLQuery" which creates a "SQLQuery" object. The Hibernate 5.0 Users Guide section 17.3 says the same though:
List<Person> persons = session.createSQLQuery(
        "SELECT * FROM person" )
    .addEntity( Person.class )
    .list();

A: Aha! Answer: No, and HQL was NEVER supported in Hibernate NativeQuery calls.
I misinterpreted the documentation. When I read
("SELECT * FROM Person", Person.class)

...as the arguments for createNativeQuery, I assumed the capitalized "Person" was an entity and would map to whatever table name was specified in Person.class. This is not the case, and never has been the case. The createNativeQuery() method behaves the same as the old createSQLQuery() method, and simply ushers your query string AS IS down to the db, without doing the entity mapping translation stuff on the way down.
The only reason you specify the second class argument is for marshaling ResultSet variables back into an object after the query you gave it is done and has returned results. It's clearer in the old docs with the lowercase "person" in:
"SELECT * FROM person"

...but not real clear, although Hibernate docs are still better than a lot of other libraries' docs.
Anyway, NativeQuery(s) are just like the old SQLQuery(s), and simply execute native sql and try to help you marshal the ResultSet(s).
Oh, and the exception! Why did I get the exception? Because my Person class doesn't map to a table named exactly "Person", so when it tried to execute the query it failed.


text:
Q: PhantomJS using too many threads I wrote a PhantomJS app to crawl over a site I built and check for a JavaScript file to be included. The JavaScript is similar to Google where some inline code loads in another JS file. The app looks for that other JS file which is why I used Phantom.
What's the expected result?
The console output should read through a ton of URLs and then tell if the script is loaded or not.
What's really happening?
The console output will read as expected for about 50 requests and then just start spitting out this error:
2013-02-21T10:01:23 [FATAL] QEventDispatcherUNIXPrivate(): Can not continue without a thread pipe
QEventDispatcherUNIXPrivate(): Unable to create thread pipe: Too many open files

This is the block of code that opens a page and searches for the script include:
page.open(url, function (status) {
    console.log(YELLOW, url, status, CLEAR);
    var found =  page.evaluate(function () {
      if (document.querySelectorAll("script[src='***']").length) {
        return true;
      } else { return false; }
    });

    if (found) {
      console.log(GREEN, 'JavaScript found on', url, CLEAR);
    } else {
      console.log(RED, 'JavaScript not found on', url, CLEAR);
    }
    self.crawledURLs[url] = true;
    self.crawlURLs(self.getAllLinks(page), depth-1);
  });

The crawledURLs object is just an object of urls that I've already crawled. The crawlURLs function just goes through the links from the getAllLinks function and calls the open function on all links that have the base domain of the domain that the crawler started on.
Edit
I modified the last block of the code to be as follows, but still have the same issue. I have added page.close() to the file.
if (!found) {
  console.log(RED, 'JavaScript not found on', url, CLEAR);
}
self.crawledURLs[url] = true;
var links = self.getAllLinks(page);
page.close();
self.crawlURLs(links, depth-1);

A: From the documentation:

Due to some technical limitations, the web page object might not be completely garbage collected. This is often encountered when the same object is used over and over again.

The solution is to explicitly call close() of the web page object (i.e. page in many cases) at the right time.
Some included examples, such as follow.js, demonstrate multiple page objects with explicit close.

A: Open Files Limit.
Even with closing files properly, you might still run into this error.
After scouring the internets I discovered that you need to increase your limit of the number of files a single process is allowed to have open. In my case, I was generating PDFs with hundreds to thousands of pages.
There are different ways to adjust this setting based on the system you are running but here is what worked for me on an Ubuntu server:
Add the following to the end of /etc/security/limits.conf:
# Sets the open file maximum here.
# Generating large PDFs hits the default ceiling (1024) quickly.
*    hard nofile 65535
*    soft nofile 65535
root hard nofile 65535 # Need these two lines because the wildcards (above)
root soft nofile 65535 # are not applied to the root user as well.

A good reference for the ulimit command can be found here.
I hope that puts some people on the right track.

A: I had this error come up while running multiple threads in my ruby program.
I was running phantomjs with Capybara-poltergeist and each thread was visiting a page opening up the same CSV file and writing to it.
I was able to fix it by using the Mutex class.
lock = Mutex.new
lock.synchronize do
    CSV.open("reservations.csv", "w") do |file|
        file << ["Status","Name","Res-Code","LS-Num","Check-in","Check-out","Talk-URL"]
          $status.length.times do |i|
              file << [$status[i],$guest_name[i],$reservation_code[i],$listing_number[i],$check_in[i],$check_out[i], $talk_url[i]]
          end
        end
        puts "#{user.email} PAGE NUMBER ##{p+1} WRITTEN TO CSV"
    end
end


text:
Q: Event Delegation on selector that's returned from an ajax response The summary of this question is: if we're using Event Delegation does it always have to be bound to an element that exists in the DOM on page load? Can we bind to a selector returned in an ajax response?
I'm using jQuery 3.2.1 and have been reading about Event Delegation: http://learn.jquery.com/events/event-delegation/
Using their example markup:

Item #1

Item #2

Item #3

Item #4

I understand the point they're making about how if we added a 5th item to #list with js, the following would only work for Items 1 - 4 because the 5th item didn't exist when .on was called and therefore doesn't get the event handler:
$( "#list a" ).on( "click", function( event ) {
});

So the solution given is use a delegated event handler like this:
$( "#list" ).on( "click", "a", function( event ) {
});

In both of these cases they have targeted #list because that's there on page load.
In my application, I am making an ajax request which would return the equivalent of the entire block of markup given at the start (i.e. everything including #list) and appending it to a Bootstrap 3.3.7 modal window with an ID, #notifierModal inside the default area for content which has a class of .modal-body:
$.ajax({
    url: $(this).attr('href'),
    method: 'get'
}).done(function(response) {
    $('.modal-body').html(response);
    $('#notifierModal').modal('show');
});

I have this present on page load:
$( "#list" ).on( "click", "a", function( event ) {
    console.log('something inside #list was clicked');
});

This does not work - presumably because #list is not there on page load since it's appended to .modal-body after the ajax request completes.
This does work - presumably because .modal-body is present on page load:
$( ".modal-body" ).on( "click", "a", function( event ) {
    console.log('something inside .modal-body was clicked');
});

So my question is two-fold:

*

*If we're using Event Delegation does it always have to be bound to an element that exists in the DOM on page load? Is it possible to target a selector that's returned in an ajax response?

*The reason this is a problem in my application is because I have other anchor tags inside .modal-body which I don't want to be handled by the click event given in my js. It seems impossible to target anchors inside #list in this way? How could I write the js such that it only targets anchors inside #list?
PS - I've read Event binding on dynamically created elements? but this seems to address binding on an element that existed on page load.

A: Yes, when you use event delegation to add a handler to a container, that container must exist first in order to add the handler.
The solution here is to provide a more precise selector string when using event delegation on your .modal-body - rather than selecting any a descendant, use the selector string #list a instead to ensure that elements that trigger the listener must descend from #list:

$( ".modal-body" ).on( "click", "#list a", function( event ) {
    event.preventDefault();
    console.log('something in the list was clicked');
});

function append() {
  $( ".modal-body" ).append(`

Item #1

Item #2

Item #3

Item #4

  `);
}

setTimeout(append, 1500);

something that shouldn't trigger listener


text:
Q: OS X PATH problems: Home directory set to /Applications/XAMPP I was using XAMPP, and added a XAMPP sub-directory to my PATH in ~/.bash_profile, and now for some reason all of a sudden /Applications/XAMPP is my home directory (e.g. when I type "cd ~" and do "ls", it only lists the contents of the XAMPP folder. And because of this, I can't find my ~/.bash_profile to revert the PATH back to normal. It seems to have disappeared. Any suggestions?

A: I'm not completely sure what causes you to end up in /Applications/XAMPP. But I can tell you a way to debug a login shell:
PS4='+ $BASH_SOURCE:$LINENO: ' bash -xlic ''

-x is for debug, -l is login, -i is interactive, and -c '' is a NOP command.
PS4 will be appended on each line printed by -x, and in our case it will print file and line number from where the code is executed.


text:
Q: How can I connect to a different database during application's runtime with Laravel? By default Laravel will connect into a database whose configurations showed in .env file. However, I want to have my application connected to a database which configurations will be provided by other internal service through HTTP (database host, username, password, ...).
So, how can I get my Laravel application connected into a database during runtime?
This thread: Set database connection and language dynamically in Laravel gives me a nutshell approach on using middleware to connect to a database. But it does not explain on how I can connect to a database dynamically from any part of my Laravel codes.

A: You can use the Config::set method to change your underlying config on the fly - to another database connection, assuming that is what you mean.
Config::set("database.connections.mysql", [
    "host" => "...",
    "database" => "...",
    "username" => "...",
    "password" => "...
]);


text:
Q: How to add event in Android calendar, repeated every 3 days? I want to add an event to the Android calendar using this code:
cr = getContentResolver();
ContentValues values = new ContentValues();
values.put(Events.DTSTART, startMillis);
values.put(Events.DURATION, "P3600S");
values.put(Events.TITLE, "MyTestNew");
values.put(Events.DESCRIPTION, "Group workout");
values.put(Events.CALENDAR_ID, calID);
values.put(Events.EVENT_TIMEZONE, "India");
values.put(Events.ALL_DAY, 1);
values.put(Events.RRULE, "FREQ=WEEKLY;WKST=SU;BYDAY=SA");
uri = cr.insert(Events.CONTENT_URI, values);

But I want to add this event which should repeat every three days than what will be changed in my (Events.RRULE, parameter. How might I do this?

A: finally I found the solution.
values.put(Events.DTSTART, startMillis);
values.put(Events.DURATION, "P1800S");
values.put(Events.TITLE, "MyTestNew");
values.put(Events.DESCRIPTION, "Group workout");
values.put(Events.CALENDAR_ID, calID);
values.put(Events.EVENT_TIMEZONE, "India");
values.put(Events.RRULE, "FREQ=DAILY;INTERVAL=3");
uri = cr.insert(Events.CONTENT_URI, values);

A: This code start the default calender of android and you can add event on it.

String dtStart = "2012" + "" + "06-11-01T10:50:00Z";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {Date date = format.parse(dtStart);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
//cal.setTime(date);

Intent intent = new Intent(Intent.ACTION_EDIT);                                        intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FREQ=DAILY;COUNT=1");
intent.putExtra("endTime", cal.getTimeInMillis() + 60 * 60 * 1000);
intent.putExtra("title", "Booking Confirm Notification");
intent.putExtra("Description", "Please check details");
startActivity(intent);

Arun chandravanshi
Thanks.


text:
Q: Module not found: Can't resolve 'fs' - yet another NextJS problem I am attempting to read a json file that is in one directory above my NextJS application directory. In a normal JavaScript setting,
var fs = require('fs');
var data = JSON.parse(fs.readFileSync(directory_path))

Boom boom pow, I have the JSON data available to do what I want with. With NextJS, you're not allowed to use the  var fs = require('fs') line. You'll get errors like:
Module not found: Can't resolve 'fs'

Import trace for requested module:
./pages/file_where_broken_function_is_called.js

Basically saying it can't read the file and doesn't know where to find the JSON file since it's outside the application directory I believe (according to the import trace error). So you need to configure your next.config.js file. Mine currently looks like this:
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
}

module.exports = nextConfig

I followed this video to set up my file to be like so:
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  webpack5: true,
  webpack: (config) => {
    config.resolve.fallback = { fs: false };
    return config;
  }
}

module.exports = nextConfig

Only to be met with
404 This page could not be found
When I restart the server.
I fully admit to copy/pasting and not understanding what I'm typing in the next.config.js file or how it works to begin with. But reading a file should not be this hard.
Edit
I narrowed down my error: In this component file, resplendent_contract_export.js
import Web3 from "web3"
// export local copies of contracts

const provider = new Web3.providers.HttpProvider(
    process.env.NEXT_PUBLIC_RINKEBY_RPC_URL
)

const web3 = new Web3(provider)
const fs = require('fs')

var data = JSON.parse(fs.readFileSync("../../build/contracts/Betting.json"))

I'm attempting to read in a JSON file. When I uncomment the line var data = JSON.parse..., it crashes. Therefore I suppose I'm using fs incorrectly? At the very least, I am making progress.
Edit 2
import fs from 'fs'
export async function getStaticProps() {
    const { readFileSync } = require("fs");
    console.log(fs)
    const post = JSON.parse(readFileSync("File.json"))
   console.log(post.abi)
    data = post.abi
    return {
      props: {
        data,
      },
    }
  }
}

This is what I was attempting to post in the comments below, I can't figure out how to post a code block in the comments (3 backticks didn't work for me and Ctrl-K just cleared a line, is this unavailable on OSX?) so I have to edit this in. But as I noted in the comment down below, I ended up getting this error here:
ReferenceError: readFileSync is not a function
Any suggestions to solve this error?

A: It looks like you're importing fs into a file in your pages directory. This is ok in theory but you have to use that function in getServerSideProps() otherwise you'll get the Module not found error that you reported.
If you just put a call to fs in your file, it will error because the browser has no concept of that module.
export const getServerSideProps = () => {
  console.log(fs); <-- ok because this function runs on the server
  const data = JSON.parse(fs.readFileSync(... your file);
  return { props: data };
};

EDIT:
You can replace getServerSideProps with getStaticProps if your page is statically generated and fs will still work.


text:
Q: how to return value in PHPrecursive function i am trying to build a recursive tree but child function is not returning any value. i don't know how to return value in PHP code. is there i am doing any mistake. please help
 $sql="select * from MenuMaster order by MenuId";
        $result= ExecuteQuery($sql);
    function BuildMenu($result){
        $output ='';
        $output .= '
';

        while ($row = mysqli_fetch_array ($result)){
            if($row['ParentId']== null || $row['ParentId'] ==0){
                $output .= '
'.$row['MenuText'].'
';
            }
             $output .= FindChild($output , $row['MenuId']);
        }

        $output.= '
';
        return $output;
    }
    $finaloutput.= BuildMenu($result);
    echo $finaloutput;

function FindChild($childOutput, $Menuid){

    $sqlChild="select * from MenuMaster where ParentId = $Menuid ";
    $resultChild= ExecuteQuery($sqlChild);
    $Rowcont =mysqli_num_rows($resultChild);

    if($Rowcont > 0){
      $childOutput.='
';

        while ($row1 = mysqli_fetch_array ($resultChild)){
            $childOutput.= '
'.$row1['MenuText'].'
';
            FindChild($childOutput,$row1['MenuId']);
        }
        $childOutput.='
';
    }
        return  $childOutput;
      }


text:
Q: facet-grid in ggplot, R I'm trying to plot categorical data using ggplot in which I have two categories for parameter ( C and C+Fe) that I pass facet-grid argument.
here is part of my code:
mediagene<-ggplot(ARG)+
geom_boxplot(aes(x = gene, y= RA, fill=type))+
ylab("Relative gene abundance\n copies/ 16s rRNA")+
theme_bw()+
facet_grid(parameter~.,switch="y")+
scale_fill_manual(values=cols)+
labs(fill="Saturation")

and here is the result:
enter image description here
now my question is that how I can have only the top graph ( only category C from the parameter)

A: As stefan suggests, using dplyr::filter() can keep only the rows in your data that match a certain condition.
In this instance, you only want to keep data where parameter is 'C', so you could do something like the following to keep just this data:
ARG %>%
  filter(
    parameter == 'C'
  )

We can then send this data to ggplot to plot, by:
ARG %>%
  filter(
    parameter == 'C'
  ) %>%
  ggplot()+
  geom_boxplot(aes(x = gene, y= RA, fill=type))+
  ylab("Relative gene abundance\n copies/ 16s rRNA")+
  theme_bw()+
  facet_grid(parameter~.,switch="y")+
  scale_fill_manual(values=cols)+
  labs(fill="Saturation")

In this case, you will not need to use facet_grid() anymore, because you should only have one facet anyway. Keeping it will however give you the same box with the heading strip with the 'C' label though, which might be handy.
Without a sample of your data I can't show an example for you unfortunately.

A: One way to do this without adding additional packages is to use the subset() function as in:
mediagene<-ggplot(subset(ARG, parameter == 'C'))+
geom_boxplot(aes(x = gene, y= RA, fill=type))+
ylab("Relative gene abundance\n copies/ 16s rRNA")+
theme_bw()+
facet_grid(parameter~.,switch="y")+
scale_fill_manual(values=cols)+
labs(fill="Saturation")