text:
Q: Execute groovy inside nextflow process using process inputs I have a nextflow script with a channel for paired file inputs. I am trying to extract a substring from the file inputs to use as part of the shell call. I am trying to use Groovy's regex matching to extract the substring, but since it is based on an input value, I am having trouble executing the matching. An alternative would be to perform the regex in bash as part of the process shell call, but I am interested in figuring out how to manipulate inputs within a process anyways, as I feel it would be useful for other things too. How can I perform intermediate Groovy code with the process inputs prior to the shell call?
process alignment {
    input:
        val files
    output:
        stdout
    def matcher = "${files[1][0]}" =~ /.+\/bcl2fastq_out\/([^\/]+)\/.+/
    # this is the culprit, as if I hardcode the first string it works
    def project = matcher.findAll()[0][1]
    """
    echo ${project}
    """
}

workflow {
    files = Channel
            .fromFilePairs("${params.out_dir}/**{_R1,_R2}_00?.fastq.gz", checkIfExists:true, size: 2)
    alignment(files)
}

when I execute this, I get the error
No such variable: files
an example input string would look like extractions/test/bcl2fastq_out/project1/example_L001_R1_001.fastq.gz where I'm trying to extract the project1 substring

A: As you've already discovered, you can declare variables in the script block, before the command string. For example:
process alignment {

    input:
    tuple val(sample), path(fastq_files)

    output:
    tuple val(sample), path(output_file)

    script:
    output_file = "${sample}.bam"

    """
    >&2 echo "Aligning ${sample}..."
    touch "${output_file}"
    """
}

Note that these are global (within the process scope) unless you define them using the def keyword. If you don't need these elsewhere in your process definition, like in your example, a local variable (using def) is usually preferable. If, however, you need to access these in your output declaration, for example, then they will need to be global.
Note that the fromFilePairs factory method emits a tuple, where the first element is a group key and the second element is a list of files. The problem with just using val to declare the inputs is that the files in the second element will not be localized to the working directory when your script is run. To fix this, you can just change your input definition to something like:
input:
tuple val(sample), path(fastq_files)

The problem with this approach, is that we're unable to extract the parent directory name from the localized filenames. So you will need to pass this in somehow. Usually, you could just get the parent name from the first file in the tuple, using:
params.input_dir = './path/to/files'
params.pattern = '**_R{1,2}_00?.fastq.gz'

process alignment {

    debug true

    input:
    tuple val(sample), val(project), path(fastq_files)

    """
    echo "${sample}: ${project}: ${fastq_files}"
    """
}

workflow {

    Channel
        .fromFilePairs( "${params.input_dir}/${params.pattern}" )
        .map { sample, reads ->
            def project = reads[0].parent.name

            tuple( sample, project, reads )
        }
        .set { reads }

    alignment( reads )
}

But since the glob pattern has an additional wildcard, i.e. _00?, you may not necessarily get the results you expect. For example:
$ mkdir -p path/to/files/project{1,2,3}
$ touch path/to/files/project1/sample1_R{1,2}_00{1,2,3,4}.fastq.gz
$ touch path/to/files/project2/sample2_R{1,2}_00{1,2,3,4}.fastq.gz
$ touch path/to/files/project3/sample3_R{1,2}_00{1,2,3,4}.fastq.gz
$ nextflow run main.nf
N E X T F L O W  ~  version 22.04.0
Launching `main.nf` [determined_roentgen] DSL2 - revision: f80ab33ac8
executor >  local (12)
[a8/9235cc] process > alignment (12) [100%] 12 of 12 ✔
sample2: project2: sample2_R1_001.fastq.gz sample2_R1_004.fastq.gz

sample1: project1: sample1_R1_003.fastq.gz sample1_R2_001.fastq.gz

sample1: project1: sample1_R1_004.fastq.gz sample1_R2_003.fastq.gz

sample3: project3: sample3_R1_001.fastq.gz sample3_R2_001.fastq.gz

sample1: project1: sample1_R1_001.fastq.gz sample1_R2_004.fastq.gz

sample1: project1: sample1_R1_002.fastq.gz sample1_R2_002.fastq.gz

sample2: project2: sample2_R1_002.fastq.gz sample2_R2_002.fastq.gz

sample2: project2: sample2_R2_001.fastq.gz sample2_R2_004.fastq.gz

sample2: project2: sample2_R1_003.fastq.gz sample2_R2_003.fastq.gz

sample3: project3: sample3_R2_002.fastq.gz sample3_R2_004.fastq.gz

sample3: project3: sample3_R1_003.fastq.gz sample3_R1_004.fastq.gz

sample3: project3: sample3_R1_002.fastq.gz sample3_R2_003.fastq.gz

Fortunately, we can supply a custom file pair grouping strategy using a closure. This uses the readPrefix helper function:
workflow {

    Channel
        .fromFilePairs( "${params.input_dir}/${params.pattern}" ) { file ->
            prefix = Channel.readPrefix(file, params.pattern)
            suffix = file.simpleName.tokenize('_').last()

            "${file.parent.name}/${prefix}_${suffix}"
        }
        .map { key, reads ->
            def (project, sample) = key.tokenize('/')

            tuple( sample, project, reads )
        }
        .set { reads }

    alignment( reads )
}

Results:
$ nextflow run main.nf
N E X T F L O W  ~  version 22.04.0
Launching `main.nf` [loving_cantor] DSL2 - revision: 5a76ac712f
executor >  local (12)
[f4/74edbc] process > alignment (12) [100%] 12 of 12 ✔
sample1_003: project1: sample1_R1_003.fastq.gz sample1_R2_003.fastq.gz

sample2_002: project2: sample2_R1_002.fastq.gz sample2_R2_002.fastq.gz

sample1_002: project1: sample1_R1_002.fastq.gz sample1_R2_002.fastq.gz

sample2_003: project2: sample2_R1_003.fastq.gz sample2_R2_003.fastq.gz

sample2_004: project2: sample2_R1_004.fastq.gz sample2_R2_004.fastq.gz

sample2_001: project2: sample2_R1_001.fastq.gz sample2_R2_001.fastq.gz

sample1_001: project1: sample1_R1_001.fastq.gz sample1_R2_001.fastq.gz

sample1_004: project1: sample1_R1_004.fastq.gz sample1_R2_004.fastq.gz

sample3_001: project3: sample3_R1_001.fastq.gz sample3_R2_001.fastq.gz

sample3_004: project3: sample3_R1_004.fastq.gz sample3_R2_004.fastq.gz

sample3_002: project3: sample3_R1_002.fastq.gz sample3_R2_002.fastq.gz

sample3_003: project3: sample3_R1_003.fastq.gz sample3_R2_003.fastq.gz

A: I figured it out, if instead of just jumping into the shell script with the triple quotes, you can start specifying the process execution script with "script:" then run Groovy using the process inputs
process alignment {
    input:
        val files
    output:
        stdout
    script:
    test = (files[1][0] =~ '.+/test/([^/]+)/.+').findAll()[0][1]
    """
    echo $test
    """


text:
Q: Set a post expiration and delete a post when expirate I'm trying to create a function that allows me to delete an article when the date of the day is equal or superior than a date filled in a custom ACF field.
I wrote the function below that I placed in my single.php in order to test it. It works, except that you must be reading the article in question for this function to execute (pretty logical actually).
What I want is that this function runs itself on all the articles, automatically, without having to go to the articles. This is where It's difficult for me, I often use plugins to do things like that.
Could you show me some ways to achieve the desired result? I'm really looking for improve my back-end skills using Wordpress, so I'm not asking particulary for a ready-made solution but ways to guide my work.
Here's the function :
/**
 * Draft after expiration
 */

function draft_the_post(){
    $expire_date = get_field( "field_5cef86384e5f2" );
    $actual_date = date("d-m-Y");
    $postid = $post->ID;

    if ($expire_date <= $actual_date) {
        wp_update_post(array(
            'ID'    =>  $postid,
            'post_status'   =>  'draft'
        ));
    } else {
        echo "Not same date or inferior than today";
    };
}

Oh and, excuse my english I'm French :-)
I thank you in advance,
willwoody.

A: The correct way is to use WordPress Cron and schedule your event. Also you should consider adding real cron job as outlined here for better precision.
1.) I modified your draft_the_post function to support parameter. So now we can specify which post and also i updated the portion that checking the time.
2.) dg_cron_schedule_delete_posts will schedule the hook if it's not scheduled when init hook is fired. I set it to hourly for better precision but you can also set it to daily. Note: If you are doing this with plugin it's better to use the activation hook and schedule it here.
3.) dg_delete_posts_handler is where the deletion is handled. It goes through all the posts and calls the function maybe_draft_the_post on each. Note: This queries all the posts so depending of how big is your data this may cause performance issues. I suggest implementing some kind of queue but this should be a good starting point.
/**
 * Function that will draft specific post on specific conditions
 *
 * @param \WP_Post $_post
 */
function maybe_draft_the_post( $_post ) {
    $expire_date = get_field( "your_field_name" );
    // Bail if no expire date set.
    if ( ! $expire_date ) {
        return;
    }
    $expire_date = strtotime( $expire_date );
    $actual_date = time();
    if ( $expire_date <= $actual_date ) {
        wp_update_post( array(
            'ID'          => $_post->ID,
            'post_status' => 'draft'
        ) );
    }
}

/**
 * Register cron event on init action
 */
function dg_cron_schedule_delete_posts() {
    $timestamp = wp_next_scheduled( 'dg_delete_posts' );
    if ( $timestamp == false ) {
        wp_schedule_event( time(), 'hourly', 'dg_delete_posts' );
    }
}
add_action( 'init', 'dg_cron_schedule_delete_posts' );

/**
 * Handle deletion of posts periodically.
 * - Loop through the posts and call the draft_the_post function.
 */
function dg_delete_posts_handler() {
    $posts = get_posts( array(
        'posts_per_page' => - 1,
        'post_type'      => 'post',
        'post_status'    => 'publish',
    ) );
    foreach ( $posts as $_post ) {
        maybe_draft_the_post( $_post );
    }
}
add_action( 'dg_delete_posts', 'dg_delete_posts_handler' );

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are the best and worst case scenarios of an algorithm that partitions around the maximum value in an array? I have been given this algorithm that takes the maximum item (let's call it m) in an array A and partitions around it such that all the items smaller than m go in a set A1 and all those bigger or equal go in A2. Eventually, it goes recursively on A1 and uses InsertionSort on A2. It terminates after concatenating A1 and A2 in A.
First of all I don't really get why it uses insertionSort on A2 (I mean, m is the maximum, so A2 will only contain elements that are equal to the maximum). Anyway, one of the questions is about finding worst and best case scenarios and their time complexity. As for the worst case time complexity I think it's O(n^2), but I'm not quite sure (It should be like SelectionSort, right?) As for the rest I don't really know..


text:
Q: Prove: $a | c$ and $b | c\implies ab | c$
For any natural numbers $a, b, c$, if $a | c$ and $b | c$ then $ab | c$.

Can this statement be proven or does it require a counterexample to disprove it?
I tried to prove it, but failed to get past any steps that I know of, so I think it is false.
Can someone confirm for me if this is false?

A: It's false. Counterexample: $a=b=c=2$


text:
Q: Getting the modification time of a file on a FTP server I need to get the modification time of a group of files on a server. I know how to get this on a local computer, but File.mtime doesn't work via FTP. How would I convert this code to work on a server?
files_sorted_by_time = Dir['*'].select { |f|
  ((Time.now - File.mtime(f)).to_i / 604800) < 7
}

A: You want Net::FTP#mtime.
Example from documentation:
Net::FTP.open('ftp.netlab.co.jp') do |ftp|
  ftp.login
  files = ftp.chdir('pub/lang/ruby/contrib')
  files = ftp.list('n*')
  ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
  ftp.mtime('file.pdf')
end

You can use #mtime with #nlst to filter through the list of remote files.
Net::FTP.open('ftp.netlab.co.jp') do |ftp|
  ftp.login
  ftp.nlst do |file|
    if ftp.mtime(file) # ...
  end
end


text:
Q: Using async functions that borrow arguments in contexts where trait object is needed I've recently started playing with async streams in Rust, and I keep finding myself in situations where I want to use async functions in the implementation of a Stream. The async functions often come from libraries I don't control, but for the sake of example suppose they look like this:
async fn bar_str(s: &str) -> String {
    s.to_string()
}

async fn bar_string(s: String) -> String {
    s
}

Also to keep things simple suppose I'm just trying to use these functions to implement a trait like the following (no actual stream stuff involved):
use std::future::Future;

trait Foo {
    fn bar(self) -> Box<dyn Future<Output = String>>;
}

For the String case this just works as you'd expect:
impl Foo for String {
    fn bar(self) -> Box<dyn Future<Output = String>> {
        Box::new(bar_string(self))
    }
}

For the case where the async function borrows, it doesn't.
impl Foo for &str {
    fn bar(self) -> Box<Future<Output = String>> {
        Box::new(bar_str(self))
    }
}

This fails to compile:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter '_ in function call due to conflicting requirements
  --> foo.rs:23:18
   |
23 |         Box::new(bar_str(self))
   |                  ^^^^^^^^^^^^^
   |
...

I can understand why this is a problem, and I understand that the async fn syntax provides special handling for borrowed arguments like this (although I don't know anything about how it's actually checked, desugared, etc.).
My question is about what the best thing is to do in these situations generally. Is there some way I can reproduce the magic async fn is doing in my non-async fn code? Should I just avoid borrowing in async functions (when I can, since that's often a decision I didn't make)? In the code I'm currently writing I'm happy to use experimental or not-necessarily-future-proof solutions if they make reading and writing this kind of thing nicer.

A: I think that the problem is not so much in the async but in the Box<dyn Trait> thing. In fact it can be reproduced with a simple trait:
use std::fmt::Debug;

trait Foo {
    fn foo(self) -> Box<dyn Debug>;
}

impl Foo for String {
    fn foo(self) -> Box<dyn Debug> {
        Box::new(self)
    }
}

impl Foo for &str {
    fn foo(self) -> Box<dyn Debug> {
        Box::new(self) // <--- Error here (line 15)
    }
}

The full error message is:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/lib.rs:15:18
   |
15 |         Box::new(self)
   |                  ^^^^
   |
note: first, the lifetime cannot outlive the lifetime `'_` as defined on the impl at 13:14...
  --> src/lib.rs:13:14
   |
13 | impl Foo for &str {
   |              ^
note: ...so that the expression is assignable
  --> src/lib.rs:15:18
   |
15 |         Box::new(self)
   |                  ^^^^
   = note: expected `&str`
              found `&str`
   = note: but, the lifetime must be valid for the static lifetime...
note: ...so that the expression is assignable
  --> src/lib.rs:15:9
   |
15 |         Box::new(self)
   |         ^^^^^^^^^^^^^^
   = note: expected `std::boxed::Box<(dyn std::fmt::Debug + 'static)>`
              found `std::boxed::Box<dyn std::fmt::Debug>`

There is a nice hint about what is going on in the last two lines... what is this Box<(dyn Debug + 'static)> thing?
When you write dyn Trait there is actually an implicit 'static constraint to the type that implements that trait, so these two are the same thing:
Box<dyn Debug>
Box<(dyn Debug + 'static)>

But that means that we can only box a value whose type is 'static. And &'a str is not a static type, so it cannot be boxed that way.
The easy solution is, as usual, to clone, if at all possible. This compiles and it's not too ugly:
impl Foo for &str {
    fn foo(self) -> Box<dyn Debug> {
        Box::new(self.to_owned())
    }
}

Or if you only use static strings, then &'static str is actually static and you can write:
impl Foo for &'static str {
    fn foo(self) -> Box<dyn Debug> {
        Box::new(self)
    }
}

If you actually want or need to borrow, then the boxed dyn object has to be generic over some lifetime. You have to change the return type of your trait, something like this:
use std::fmt::Debug;

trait Foo<'a> {
    fn foo(self) -> Box<dyn Debug + 'a>;
}

impl Foo<'static> for String {
    fn foo(self) -> Box<dyn Debug> {
        Box::new(self)
    }
}

impl<'a> Foo<'a> for &'a str {
    fn foo(self) -> Box<dyn Debug + 'a> {
        Box::new(self)
    }
}

But beware now that Box<dyn Debug + 'a> is not a static type by itself, but the type itself has a lifetime of 'a.


text:
Q: Wordpress Page has a chaotic Recent News Widget For my work I'm being asked to edit a Wordpress website but there's NO documentation and NO organization whatsoever so editing it is a nightmare.
And it relies heavily on Widgets I don't really know how to use but I can't find any info other than like sites that used it too so I'm not sure what to edit and I'm terrified on breaking the site since it's already uploaded.
For the most part all I need to do is edit the way recent news display the dates

Like, delete the "ON ___ AGO" or be able to modify it to display with different words since the site is in spanish.
[trx_widget_recent_news style="news-announce" show_categories="" category="0" count="4" orderby="date" order="desc"]

But this is all the code I have for it and nothing tells me how to edit the format of the date display.
[vc_row full_width="stretch_row" hide_bg_image_on_tablet="" hide_bg_image_on_mobile="" row_delimiter="" hide_on_desktop="" hide_on_notebook="" hide_on_tablet="" hide_on_mobile="" hide_on_frontpage="" css=".vc_custom_1657334261997{background-color: #1a1d24 !important;}"][vc_column icons_position="left"][trx_widget_recent_news style="news-announce" show_categories="" category="0" count="4" orderby="date" order="desc"][vc_empty_space height="32 px" alter_height="medium" hide_on_desktop="" hide_on_notebook="" hide_on_tablet="" hide_on_mobile="1"][vc_single_image image="9793" img_size="full" alignment="center" onclick="custom_link" img_link_target="_blank" link="https://agricoladasam.com.mx/dasam/" css=".vc_custom_1658420299087{padding-top: 50px !important;padding-bottom: 50px !important;}"][vc_empty_space height="50px" alter_height="medium" hide_on_desktop="" hide_on_notebook="" hide_on_tablet="" hide_on_mobile=""][/vc_column][vc_column icons_position="left"][/vc_column][/vc_row][vc_row][vc_column width="2/3" icons_position="left"][vc_empty_space height="4em" alter_height="none" hide_on_desktop="" hide_on_notebook="" hide_on_tablet="" hide_on_mobile=""][vc_empty_space height="3.5em" alter_height="none" hide_on_desktop="" hide_on_notebook="" hide_on_tablet="" hide_on_mobile="1"][trx_sc_title title_style="default" link_style="default" title="Últimas Noticias" description="Del Sector"][trx_widget_recent_news style="news-announce" show_categories="1" category="56" orderby="none" order="asc"][vc_empty_space height="2.6em" alter_height="none" hide_on_desktop="" hide_on_notebook="" hide_on_tablet="" hide_on_mobile=""][vc_column_text]%%CONTENT%%[/vc_column_text][vc_empty_space height="3.5em" alter_height="none" hide_on_desktop="" hide_on_notebook="" hide_on_tablet="" hide_on_mobile="1"][/vc_column][vc_column width="1/3" icons_position="left"][vc_empty_space height="2em" alter_height="none" hide_on_desktop="" hide_on_notebook="" hide_on_tablet="" hide_on_mobile="1"][vc_empty_space height="3.6em" alter_height="none" hide_on_desktop="" hide_on_notebook="" hide_on_tablet="" hide_on_mobile="1"][vc_widget_sidebar sidebar_id="sidebar_widgets" el_class="widget_area"][vc_empty_space height="4em" alter_height="none" hide_on_desktop="" hide_on_notebook="" hide_on_tablet="" hide_on_mobile=""][/vc_column][/vc_row][vc_row][vc_column width="2/3" icons_position="left"][vc_empty_space alter_height="medium" hide_on_desktop="" hide_on_notebook="" hide_on_tablet="" hide_on_mobile=""][vc_single_image image="11941" img_size="full" onclick="custom_link" img_link_target="_blank" link="https://contactostihl.com"][vc_empty_space alter_height="medium" hide_on_desktop="" hide_on_notebook="" hide_on_tablet="" hide_on_mobile=""][/vc_column][vc_column width="1/3" icons_position="left"][vc_empty_space alter_height="medium" hide_on_desktop="" hide_on_notebook="" hide_on_tablet="" hide_on_mobile=""][vc_single_image image="3670" img_size="medium"][vc_empty_space alter_height="medium" hide_on_desktop="" hide_on_notebook="" hide_on_tablet="" hide_on_mobile=""][/vc_column][/vc_row][vc_row][vc_column icons_position="left"][/vc_column][/vc_row]

This is the mess I was left with, I feel someone did the block editing thingy and just left me to suffer. Lol.

A: If the Site Language is Spanish, the rendering of "on 21 horas ago" could be altered by changing the date/time formats in:
WP Admin > Settings > General
NB. This would affect all dates/times displayed on the site globally.
Another option would be to search for the "trx_widget_recent_news" callback function in the plugin/theme directory to see exactly how the time in the widget is rendered. Depending on what you find, you could overwrite the shortcode callback with your own or provide a translation for the function used.
Fortunately with WordPress, even when there is no documentation, you can always read the source code and use it as a guide to find your way around. Hope this helps you feel more confident - you can do it..


text:
Q: Zend Framework - applying order by on a nested query This might be a very simple thing. Check out the normal sql query below

(select * from shopping order by shopping_id desc limit 5) order by RAND()

This query runs successfully in mysql - not sure if this is the right way of doing it - but it works. It gets the last 5 ids from shopping table and randomly orders them everytime
I want to achieve this in Zend. I'm not sure how to execute the first part and then apply the RAND clause to the results - what I have below does not do that.

$select = $this->select()
           ->from(array('sh'=>'shopping'))
           ->order('shopping_id desc')
           ->limit(5)
           ->order('RAND()');

A: Why not take a slightly different approach which will acheive the same results.  If you drop the subselect and the order by RAND() you can get the rows very quickly from the database, then when you are working with the rows, you could always randomize them.
$select = $this->select()
       ->from(array('sh'=>'shopping'))
       ->order('shopping_id desc')
       ->limit(5)

$rows = $this->fetchAll($select);

// take it from a rowset object, convert to an array:
$rowArray = array();
foreach ($rows as $row) $rowArray[] = $row;
shuffle($rowArray);

A: The Zend_Db_Expr class lets you do that. You create a new instance of the Zend_Db_Expr class and using its constructor you pass in the expression as a string: "RANDOM()".
$select = $this->select()
           ->from(array('sh'=>'shopping'))
           ->order('shopping_id desc')
           ->limit(5)
           ->order(new Zend_Db_Expr('RANDOM()'));


text:
Q: TypeError when calling parent class despite passing parameter I have a class TextElement which inherits from PyQt-class QTextEdit and a custom class BaseElement.
BaseElement needs the parameter "transmitter" which is passed by the parameter "transmitter" of TextElement itself.
Despite doing everthing accordingly I get the TypeError:
Traceback (most recent call last):
  File "...\HotTeacher\package\tblock.py", line 102, in insertTextElem
    TE = TextElement(self.transmitter, self)
  File "...\HotTeacher\elements\textelement.py", line 13, in __init__
    QTextEdit.__init__(self, parent=parent)
TypeError: BaseElement.__init__() missing 1 required positional argument: 'transmitter'

I checked if I forgot to pass the parameter "transmitter" when an instance of TextElement is created but everthing seems fine.
baseelement.py
class BaseElement:
    def __init__(self, transmitter) -> None:
        self.transmitter = transmitter
        self.isfocussed = False

textelement.py
class TextElement(QTextEdit, BaseElement):
    def __init__(self, transmitter, parent=None) -> None:
        print(transmitter) # Just for checking if something is passes
        QTextEdit.__init__(self, parent)
        BaseElement.__init__(self, transmitter)
        ...

This is where an instance of TextElement is created:
class BlockRow:
    def insertTextElem(self) -> None:
        TE = TextElement(self.transmitter, self)
        ...

I didn't use super() to call the parent classes because both need different parameters.
So why am I getting this TypeError despite every parameter is passed seemingly fine?
I've also tried to pass the parameters like this:
class TextElement(QTextEdit, BaseElement):
    def __init__(self, transmitter, parent=None) -> None:
        print(transmitter) # Just for checking if something is passes
        QTextEdit.__init__(self, parent=parent)
        BaseElement.__init__(self, transmitter=transmitter)

But this didn't work either.

A: I suspect that QTextEdit looks a little like this:
class QTextEdit:
    def __init__(self, parent) -> None:
        ...
        super().__init__()
        ...

The super().__init__() there, accidentally calls your BaseElement.__init__().
Swapping the classes over: class TextElement(BaseElement, QTextEdit): means that the super call no longer looks into BaseElement.
You can get a sense of what happens if you try: print(TextElement.mro()) for both versions of the base classes.


text:
Q: Abelian Group proof 1 Recall that a $\Bbb Z$-module is an abelian group ($G$,$+$) together with a map $\Bbb Z$ $\times$ $G$ $\to$ $G$ $:$ $(a, x)$ $\mapsto$ $ax$ (Scalar multiplication) such that
(a) $a(x+y) = ax + ay$  for all $a$ $\in$ $\Bbb Z$, $x,y\in G$
(b) $(a+b)x$ = $ax + bx$ for all $a,b \in \Bbb Z$, $x\in G$
(c) $(ab)x$ = $a(bx)$ for all $a,b \in \Bbb Z$, $x\in G$
(d) $1x$ = $x$ for all $x \in G$
Let ($G$, $+$) be an abelian group. Prove that there is at most one scalar multiplication $\Bbb Z$ $\times$ $G$ $\to$ $G$ $:$ $(a, x)$ $\mapsto$ $ax$ making it into a $\Bbb Z$-module

A: It follows from the axioms that
$$(1+1+\cdots+1)x=x+x+\cdots+x$$
This uniquely determines the action of each positive integer. For zero we have
$$(0+0)x=0x+0x=0x$$
So
$$0x=0x-0x=0$$
This tells us the action for negative integers; we have
$$0=(a+-a)x=ax+(-a)x$$
Thus
$$(-a)x=-(ax)$$
That is, $(-a)x$ is the inverse of $ax$.


text:
Q: JasperReports Server: Exporting Data to multiple tabs/sheets in a single Excel file I have tried many suggestions in the forum but could not find a working solution for exporting data to multiple tabs/sheets in a single excel file.
I created the .jrxml using iReport Designer Pro 5.0.0 and when I preview in iReport Report viewer, I can see multiple tabs (each tab is supplied by a different DataSet/Query and the rows are > 10000) as expected.
But when I deploy in JasperReports Server and try to export in Excel format it gives all the data from two queries/dataset into a single Excel tab only. Could anyone send a working example to solve this problem.
I have already tried the Page Break, Line Break, Sub report, Groups, Different properties like ignore pagination, net.sf.jasperreports.export.xls.one.page.per.sheet, net.sf.jasperreports.export.xls.break.after.row and net.sf.jasperreports.export.xls.break.before.row.

A: you need to set a property in Jrxml
net.sf.jasperreports.export.xls.max.rows.per.sheet
Value : your expected more than 10000 rows right. Give 25000


text:
Q: How to do SQL query for DISTINCT and COUNT at the same time I try to do a query which allow me to DISTINCT column1 (name), column2 (mode) and column3 (date). But at the same time, I want to count the value in column mode from the same table. I try to join these 2 queries (below), but the queries are from the same table. Are there any solution ?

*

*SELECT DISTINCT Name, Mode, Date FROM table_name

*SELECT COUNT(Mode) FROM table_name

The OnHand column is COUNT from the Mode column

A: If I understand correctly, you want window functions:
SELECT column1, column2, column3,
       SUM(COUNT(*)) OVER (PARTITION BY column2) as column2_cnt
FROM table_name 2
GROUP BY column1, column2, column3;

On each row, you will have the count of column2 values over the entire table.  So the values will be repeated on rows with the same column2 value.
EDIT:
Based on your revised question, you seem to want:
SELECT name, mode, date,
       COUNT(*) OVER (PARTITION BY name) as cnt
FROM table_name
GROUP BY name, mode, date;

You can express this in other ways:
SELECT t.name, t.mode, t.date, tn.cnt
FROM table_name t JOIN
     (SELECT name, COUNT(DISTINCT mode, date) as cnt
      FROM table_name t
      GROUP BY name
     ) tn
     ON t.name = tn.name
GROUP BY t.name, t.mode, t.date, tn.cnt;


text:
Q: how use flutter for routing dynamic deep link in website(crm)? how navigate directly to custom dynamic url in flutter web ?
for example this is the url : https://example.com/panel/account/site?accountId=**16501**&siteId=**5103**
how navigate to this url directly and get params from url?


text:
Q: Using Python's async/await with PyGObject has made my code synchronous again. Why? Ok, so here's the beat: I'm developing a Rhythmbox plugin that allows me to copy songs of a playlist from a place to another.
I used Gio.File.copy_async to copy the files. Here's what I did at first (the code is actually more complex but stick with me):
files = []
pending = []

def copy_file(file: Gio.File, cancellable: Gio.Cancellable):
    destination_path = ""  # Compute new path

    cancellable.connect(on_cancel)

    self.__file.copy_async(
        Gio.File.new_for_path(destination_path),
        Gio.FileCopyFlags.ALL_METADATA
        | Gio.FileCopyFlags.NOFOLLOW_SYMLINKS
        | Gio.FileCopyFlags.OVERWRITE,
        GLib.PRIORITY_DEFAULT,
        cancellable,
        on_progress,
        (),
        on_file_copied,
        None,
    )

def on_cancel():
  ...

def on_progress(self, current_num_bytes: int, total_num_bytes: int):
  ...

def on_file_copied(self, file: Gio.File, res: Gio.AsyncResult, _):
  pending.remove(file)

  if len(pending) == 0:
    on_batch_done()
  else
    ...

def on_batch_done():
  # Do things after files have been copied
  ...

def copy_files():
  files = []
  cancellable = Gio.Cancallable()
  for file in files:
    copy_file(file, cancellable)

At first it was managable but, as code grew more complex, using Gio's *_async functions turned the whole thing into a callback hell and made the code more difficult to reason about.
So I decided to use Python's async/await to turn callbacks into awaitable coroutines like I'm used to do in Kotlin, now:
class TransfertTask(GObject.Object):
    def __init__(
        self,
        destination: str,
        file: Gio.File,
        cancellable: Gio.Cancellable,
        loop: AbstractEventLoop,
    ):
        ...
        super().__init__()

    def start(self):
        self.__cancellable.connect(self.__on_cancel)

        self.__file.copy_async(
            Gio.File.new_for_path(self.destination),
            Gio.FileCopyFlags.ALL_METADATA
            | Gio.FileCopyFlags.NOFOLLOW_SYMLINKS
            | Gio.FileCopyFlags.OVERWRITE,
            GLib.PRIORITY_DEFAULT,
            self.__cancellable,
            self.__on_progress,
            (),
            self.__on_file_copied,
            None,
        )

        return self.__future

    def __on_progress(self, current_num_bytes: int, total_num_bytes: int):
      ...

    def __on_cancel(self):
        self.__future.cancel()

    def __on_file_copied(self, file: Gio.File, res: Gio.AsyncResult, _):
        async def set_future_result():
            self.__future.set_result(self)

        self.__finished = True
        run_coroutine_threadsafe(set_future_result(), self.__loop)
        try:
            file.copy_finish(res)
        except GLib.Error as e:
            self.error = e

async def copy_files():
  cancellable = Gio.Cancellable()
  loop = get_running_loop()

  await gather(*[
    TransfertTask("...", file, cancellable, loop).start()
    for file in files
  ])

def start():
  asyncio.run(copy_files())

Thing is, now the code blocks the UI until the files a copied. In order to recover async processing, I have to launch the main coroutine in a seperate thread like so:
def start():
  loop = get_event_loop()
  thr = Thread(target=loop.run_forever)
  thr.daemon = True
  thr.start()
  run_coroutine_threadsafe(copy_files(), loop)

I'm very new to asyncio so there's a few things I still don't quite understand. I would expect await or event asyncio.run() to be blocking until the coroutine has fininshed running. But I couldn't find anywhere on the internet a way to tell Python "just launch this coroutine and move on, I don't care about the result". Maybe Python can't do that and I'm still too much thinking like I'm writing Kotlin.
Can someone tell me what I'm doing wrong?
EDIT: to expand on Simon Hawe's answer, the main problem here is the asyncio.run() function I find in most asyncio examples which waits for the awaited coroutines. All the examples you can find on the internet are examples in which you are in control of the program's entrypoint, which is not my case here. Within Rhythmbox you must define plugins like so:
from gi.repository import GObject, RB, Peas

class SomePlugin (GObject.Object, Peas.Activatable):
  object = GObject.property(type=GObject.Object)

  def __init__(self):
    super().__init__()

  def do_activate(self):
    ...

  def do_deactivate(self):
    ...

Then the class is created and the do_activate() method is executed byt Rhythmbox.
As you can see, I have no control over the program's entrypoint so there's no correct place where I can call asyncio.run() and it doesn't block the UI.
Maybe it's just me not knowing how to ask search engines, but I'm surprised nobody seemed to have met this use case before.

A: If you are in pure async world, you can just fire of a coroutine without awaiting the result using create_task or ensure_future. An example would be something like
import asyncio

async def dosomething():
    print("Hell")
    await asyncio.sleep(10)
    print("world")

async def main():
    asyncio.create_task(dosomething())
    for i in range(10):
        print(f"What {i}")
        await asyncio.sleep(2)

asyncio.run(main())

The important thing is that this only works if you don't combine so to say async and sync code. Or more precisely, the just "blindly" started coroutine must have finished before the function given to asyncio.run has finished. This means the code
import asyncio
from time import sleep

async def dosomething():
    print("Hell")
    await asyncio.sleep(10)
    print("world")

async def main():
    asyncio.create_task(dosomething())

print("Start")
asyncio.run(main())
print("Stop")

for i in range(10):
    print(f"What {i}")
    sleep(2)

will never print world as main finished imediately. So I think you just did the right thing with the new Thread for you problem at hand.


text:
Q: JAX-WS with async servlets So, I have this old legacy JAX-WS service, that does a lot of IO per request, so each request takes quite a bit of time, but doesn't consume much CPU/RAM.
With amount of clients increasing lately, there's a huge problem of thread starvation.
At first, I thought about implementing JAX-WS builtin async support, but it requires clients to be aware of it, and thats a no in my situation. I cannot possibly force them all to update their code.
My current idea is to create special async servlet and manually parse SOAP request and encode the response, but I can't seem to find some good way to do that.
Is there any way to utilize Servlet 3.1 async support when handling JAX-WS requests?
I should clarify, that I cannot use some kind of queue, or otherwise "just return early", because request processing can fail, and client must get that failure.

A: I've found the solution that works perfectly for me, CXF Continuations API.
http://cxf.apache.org/docs/continuations.html
https://github.com/search?l=java&q=ContinuationProvider&type=Code&utf8=%E2%9C%93
I had to enable async for CXF Servlet, and add jboss module dependency to bundled CXF.
While the whole things feels somewhat like a hack, it allowed me to do proper asynchronous processing without changing service external API at all.
As a bonus, I can even decide whether to suspend request, or process it normally, which helps a lot in certain cases.

A: You could make use of workflow here where say you have webserver's workers accept the request, you handle it and places it in a queue which is shared by thread which will process this event asynchronously.
This would just mean that you have low wait time on client side and you process the client request asynchronously. In that way, you build your system scalable and can increase number of worker threads on either of the side i.e. webserver so you could accept multiple requests from client concurrently and at the same time multiple threads may be concurrently processing the events from client.


text:
Q: Varnish default grace behavior Have some api resources that are under heavy load, where responses are dynamic and to offload the origin servers we are using Varnish as a caching layer in front. The api responds with cache-control headers ranging from max-age=5 to max-age=15. Since we are using a low cache ttl a lot of requests still end up in a backend fetch. In that sense we are not sure we understand varnish request coalescing correctly with regards to grace. We have not touched any grace settings, using grace from VCL og sending stale-while-revalidate headers from the backend.
So question is; After a resource expires from the cache, all request for that resource will wait in varnish until the resource is fresh in the cache again, to prevent the thundering herd problem? Or will the default grace settings prevent "waiting" requests as they will be served "stale" content while the backend fetch completes? From the docs is not clear to us how the defaults work.

A: The basics about the lifetime of an object in Varnish
The total lifetime of an object is the sum of the following items:
TTL + grace + keep

Let's break this down:

*

*The TTL defines the freshness of the content

*Grace is used for asynchronous revalidation of expired content

*Keep is used for synchronous revalidation of expired content

Here's the order of execution:

*

*An object is served from cache as long as the TTL hasn't expired

*When the TTL is equal or lower to zero, revalidation is required

*As long as the sum of the remaining TTL (possibly below zero) and the grace time is more than zero, stale content can be served

*If there is enough grace time, Varnish will asynchronously revalidate content while serving stale content

*If both the TTL and the grace have expired, synchronous revalidation is required

*Synchronous revalidation uses the waiting list and is subject to request coalescing

*The remaining keep time will ensure the object is kept around so that conditional requests can take place

Default values

*

*According to http://varnish-cache.org/docs/trunk/reference/varnishd.html#default-ttl the default TTL is set to 120 seconds

*According tohttp://varnish-cache.org/docs/trunk/reference/varnishd.html#default-grace the default grace is set to 10 seconds

*According tohttp://varnish-cache.org/docs/trunk/reference/varnishd.html#default-keep the default keep is set to 0 seconds
What about request coalescing?
The waiting list in Varnish that is used for request coalescing is only used for non-cached objects or expired objects that are passed their grace time.
The following scenarios will not trigger request coalescing:
TTL > 0
TTL + grace > 0

When the object is fresh or within grace, there is no need to use the waiting list, because the content will still be served from cache. In the case of objects within grace, a single asynchronous backend request will be sent to the origin for revalidation.
When an object is not in cache or out of grace, a synchronous revalidation is required, which is a blocking action. To avoid that this becomes problematic when multiple clients are requesting the same object, a waiting list is used and these requests are coalesced into a single backend request.
In the end, all the queued requests are satisfied in parallel by the same backend response.
Bypassing the waiting list
But here's an important remark about request coalescing:

Request coalescing only works for cacheable content. Stateful content that can never be satisfied by a coalesced response should bypass the waiting list. If not, serialization will take place.

Serialization is a bad thing. It means that queued requests cannot be satisfied by the response, and are handled serially. This head-of-line blocking can cause significant delays.
That's why stateless/uncacheable content should bypass the waiting list.
The decision to bypass the waiting list is made by the hit-for-miss cache. This mechanism caches the decision not to cache.
The following code is used for that:
set beresp.ttl = 120s;
set beresp.uncacheable = true;

It's the kind of VCL code you'll find in the built-in VCL of Varnish. It is triggered when a Set-Cookie header is found, or when Cache-Control: private, no-cache, no-store occurs.
This implies that for the next 2 minutes the object will be served from the origin, and the waiting list will be bypassed. When the next cache miss would return a cacheable response, the object is still stored in cache, and hit-for-miss no longer applies.
With that in mind it is crucial to not set beresp.ttl to zero. Because that would expire hit-for-miss information, and would still result in the next request ending up on the waiting list, even though we know the response will not be cacheable.


text:
Q: Capybara test failing because element can not be found I am writing a RSpec Capybara test for a Rails 5 application. My application is for students learning how to write HTML and CSS. The application creates "test" objects, and then allows the user to take a test. Each time the user answers a question correctly, the app adds to the test object's "score" attribute. At the end, the application gives the user a final score and then records the test result.
I am having my Capybara tests fail because they can not locate a button. The way my app works, the user answers a question and then clicks the "Submit" button. ONLY after they submit an answer, a SECOND button appears that says "Next Question."
My test can not find that second button. I'm not an expert at testing and could use some help. I tried "sleep 5" but it didn't work.
Here is the error:
1) taking test with incorrect answers
     Failure/Error: click_button 'Next Question'
 Capybara::ElementNotFound:
   Unable to find button "Next Question"
 # ./spec/features/taking_test_spec.rb:12:in `block (2 levels) in <top (required)>'

Here is my test:
require 'rails_helper'

feature "taking test" do

    scenario "with incorrect answers" do
        visit '/'
        click_link "HTML Test"
        click_button "Start"
        fill_in "answer", with: '
'
        click_button 'Submit'
        sleep 5
        click_button 'Next Question'
        expect(page).to have_content('CSS helps you control the appearance of HTML elements.')
    end

end

Here is the relevant portion of the controller for tests:
class TestsController < ApplicationController
before_action :authenticate_user!, only: [:destroy]

def index
    @test = Test.new
    @tests = Test.all.order(created_at: :desc).paginate(:page => params[:page], :per_page => 4)
end

def question1
    @test = Test.find(params[:id])
    correct_answer = "
"
    user_answer = params[:answer]
    if user_answer == correct_answer
        flash.now[:success] = "That is correct!"
        new_score = @test.score += 1
        @test.update(score: new_score)
    elsif params[:answer].present? && params[:answer] != correct_answer
        flash.now[:danger] = "Wrong answer."
    end
end

Here is the view for question1, including the button that Capybara can not find:

Current Score: <%= @test.score %>

            <%= form_tag question1_path(@test), method: :get do %>

1. How do you write an opening paragraph tag in HTML?

                    <%= text_area_tag :answer, params[:answer], class: 'form-control', id: 'answer' %>

                <% if !flash[:success] && !flash[:danger] %>

                    <%= submit_tag "Submit", class: "btn btn-primary" %>

                <% end %>
            <% end %>

            <% if flash[:success] || flash[:danger] %>
                <%= link_to "Next Question", question2_path(@test), class:"btn btn-success pull-right" %>
            <% end %>

A: Your Next Question is not a button, it's a link (  element with href attribute - that happens to be styled to look like a button, but it's not a button).  Capybara defines a button as input [of type submit, reset, image, button] or button element. You need to use click_link to click a link, or click_link_or_button if you don't care which it is.
visit '/'
click_link "HTML Test"
click_button "Start"
fill_in "answer", with: '
'
click_button 'Submit'
click_link 'Next Question'
expect(page).to have_content('CSS helps you control the ap


text:
Q: Getting current value from Stream There is a StreamBuilder (using RxDart) which displays some date. After click on InkWell widget I need to calculate a new date on basis of old one. The code below simply explains the algo but when I run it there is nothing happens and execution stops after underlined row, i.e. I never see the value of lastCalcDate.
GUI:
child: StreamBuilder(
  stream: bloc.getDate,
  builder: (context,snapshot) {
    return InkWell(
      onTap: () => tapHandler
    );
}),

void tapHandler() async {
  var lastCalcDate = await bloc.getDate.single;
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  print(lastCalcDate);
  var newCalcDate = lastCalcDate.add(Duration(days:1));
  bloc.setDate(newCalcDate)
}

BLoC:
class Bloc {
  // BehaviourSubject is usedto be sure that last sent date will be accessible in `tapHandler`.
  final _dateSubject = BehaviourSubject<DateTime>();
  Observable<DateTime> get getDate => _dateSubject.stream;
  Function(DateTime) get setDate => _dateSubject.add;
}

To implement what I need I created some workaround but I don't like it because I fill that I can do the same thing using observables.
BLoC (workaround):
class Bloc {
  final _dateSubject = BehaviourSubject<DateTime>();
  Observable<DateTime> get getDate => _dateSubject.stream;
  DateTime _date;
  void setDateWorkaround(DateTime date) {
    _date = date;
    _dateSubject.add(date);
  }
}

Could you someone to give me advise. What I did wrong?

A: single will not work because it is going to return the next item in the stream, however, that has to be added first. This means that single will just wait for the next item and in your case it will not happen.
Since you are using rxdart and BehaviorSubject already, you can easily access the current element like this:
class Bloc {
  final _dateSubject = BehaviourSubject<DateTime>();
  Observable<DateTime> get getDate => _dateSubject.stream;
  Function(DateTime) get setDate => _dateSubject.add;

  DateTime get currentDate => _dateSubject.value;
}

In this case, I am making use of BehaviorSubject.value, which is actually the whole point of that class.
Now, you can just use currentDate in your tap handler:
void tapHandler() async {
  var lastCalcDate = bloc.currentDate;
  print(lastCalcDate);
  var newCalcDate = lastCalcDate.add(Duration(days:1));
  bloc.setDate(newCalcDate)
}

A: Use StreamProvider from provider

Listen to a Stream and expose the latest value emitted.


text:
Q: How to make a GPS transportation app? I live in Split,Croatia, and a city bus company recently accuired a new piece of software, and what it does is this: if I am a passenger and am awaiting a bus on a bus station, there is a huge monitor on which I can see the bus code and the time it will take for him to get to my station. The problem is, that in two years of having the software, not once have I seen that the time of the arrival is even remotley accurate. I am aware that GPS data can be inaccurate but this.... And that makes me so frustrated, that I decided that I will try to write a similar application for my final exam in CS in college. The problem is that I searched the web extensively in the last few days, and I cannot find good starting points. So my question is: have you ever been involved in such a project, and if so could you give me some pointers be it tutorials, or books regarding the subject? I appreciate any kind of input.
If I made a mistake regarding the question itself feel free to close it.
Thanks!

A: You will probably have:

*

*Vehicle object containing each vehicles position, assigned route, direction of travel on route, and next scheduled stop, previous scheduled stop, arrival time at previous scheduled stop

*Array of routes which comprises a list of stops and a data structure holding historic transit times between stops on each route

Now, updates to a vehicle's location push to the vehicle's object.
When you want to update a display at a station, find all routes passing through that station and for each route display the estimated arrival time of the next vehicle on that route.
The estimated arrival time structure is at the heart of this. Seed it by assuming some distance between stops and an average travel speed.
Now, every time a vehicle arrives at a stop, calculate the real time it took to get there from its last stop and use this to update an average transit time binned by half-hour increments (or what have you), you could also bin by season and/or day of week. The purpose of the binning is to implicitly account for varying traffic congestion by time of day, day of week, and/or season. Assuming otherwise homogeneous conditions, you'll eventually converge on a decent estimate of the transit time between each station.
You may find it useful to employ a Kalman filter.
Estimates of travel times between more distant stations may be more accurate than travel times between adjacent stations, if you feel like looking into that. Higher-order Markov chains may also help describe the underlying statistics of transit times.
Just ideas.


text:
Q: Having multiple section with different color which have the same environment I'm having trouble changing the sections's colors. They all have the same environment rSection defined below :
\newenvironment{rSection}[1]{
  \sectionskip
  \MakeUppercase{\bf #1} % Section title
  \sectionlineskip
  \hrule % Horizontal line
  \begin{list}{}{
    \setlength{\leftmargin}{1.5em}
  }
  \item[]
}{
  \end{list}
}

But if I manage to set a specific color for this section, every sections will have the same color.. I tried
\begin{rSection}{\protect\textcolor{ForestGreen} Education}
but xcolor doesn't recognize this color but it does for basic text within the section..
How can I solve this ?

A: Because you gave us no compilable code I can only guess what the commands \sectionskip and \sectionlineskip should do. I simply commented them in the following code.
You can define a second parameter carrying the color name for environment rSection like
\newenvironment{rSection}[2]{%
% \sectionskip
  \color{#2}\MakeUppercase{\bf #1} % Section title
% \sectionlineskip
  \hrule % Horizontal line
  \begin{list}{}{
    \setlength{\leftmargin}{1.5em}
  }
  \item[]
}{
  \end{list}
}

then you can use
\begin{rSection}{Education}{ForestGreen}

to get the green color.
Please see the following compilable code:
\documentclass{article}

\usepackage[svgnames]{xcolor}

\newenvironment{rSection}[2]{%
% \sectionskip
  \color{#2}\MakeUppercase{\bf #1} % Section title
% \sectionlineskip
  \hrule % Horizontal line
  \begin{list}{}{
    \setlength{\leftmargin}{1.5em}
  }
  \item[]
}{
  \end{list}
}

\begin{document}

\begin{rSection}{Education}{ForestGreen}
Text Text Text
\end{rSection}

\begin{rSection}{Education}{red}
Text Text Text
\end{rSection}

\end{document}

and its result:

If your used class already defined the environment rSection simply create a new one myrSection in your preamble of your document with
\newenvironment{myrSection}[2]{%
  \sectionskip
  \color{#2}\MakeUppercase{\bfseries #1} % Section title
  \sectionlineskip
  \hrule % Horizontal line
  \begin{list}{}{
    \setlength{\leftmargin}{1.5em}
  }
  \item[]
}{
  \end{list}
}

and use it this way in your document:
\begin{myrSection}{Education}{ForestGreen}
Text Text Text
\end{myrSection}


text:
Q: Constructor Not Defined Error when writing a test class I read through other Constructor Error posts but I seem to be missing something, I am writing a test class net new for a class that edits an event that was built by another developer. Previously, I had been working on a test class for a class that creates an event.
The edit class uses a standard controller and it's throwing off the code I am trying to reuse from the create test class.
I have this working in a method:
@isTest static void doSaveFail(){

    // Get the new Account Id we created and put it into the vf page.
    Account acc = [Select Id FROM Account];

    // Grab the user
    User u1 = [Select Id, LastName FROM User WHERE username = 'apextestuser@npd.com'];

    ApexPages.currentPage().getParameters().put('accId',acc.Id);
    SL_CallReport callReport = new SL_CallReport();

    callReport.event.EndDateTime = System.now() - 1;

    callReport.doSave();

}

I tried to edit this method to do the same but with the standard controller I get the error Constructor not defined.
@isTest static void doSaveFail(){

    // Get the new Account Id we vf page.
    Account acc = [Select Id FROM Account];

    // Grab the user
    User u1 = [Select Id, LastName FROM User WHERE username = 'apextestuser@npd.com'];

    ApexPages.StandardController sc = new ApexPages.StandardController();
    SL_CallReportEditController callReport = new SL_CallReportEditController(sc);
    ApexPages.currentPage().getParameters().put('Id',acc.Id);

    callReport.event.EndDateTime = System.now() - 1;

    callReport.doSave();

}

Class:
 /**
    * @methodName  Constructor
    * @date 5/18/2016
    * @description : Constructor
**/
public SL_CallReportEditController(ApexPages.StandardController stdController)
{
    // logic
}

Error: Result: [COMPILE FAILED]: (classes/NPD_Test_CallReport_Edit.cls) Constructor not defined: [ApexPages.StandardController].()  (Line: 161, Column: 43)

A: The ApexPages.StandardController class does not have an empty constructor. The only defined constructor accepts one SObject parameter:

public StandardController(SObject controllerSObject)

So in your testMethod you must do:
ApexPages.StandardController controller = new ApexPages.StandardController(acc);
MyExtension extension = new MyExtension(controller);

A note that in the constructor logic (I removed because it seems irrelevant here) you do not need to ever touch ApexPages.currentPage().getParameters(). Just use the ApexPages.StandardController.getId() method:
Id controllerId = stdController.getId();

Your SL_CallReportEditController class does not have a constructor defined that accepts an instance of ApexPages.StandardController as its only parameter. By default, only the empty constructor is defined, and this definition is lost if you define one yourself.


text:
Q: "Welcome to the Jones__": Plural or Plural Possessive? When making a welcome sign, what form of the name Jones would you use?  ("Welcome to the Jones__")

A: To me, a possessive seems fitting in this context. But I would think you would want a plural: just as "the house of the Smith family" can be called "the Smiths' (house)", it seems to me that "the house of the Jones family" should be expressed as "the Joneses' (house)".
So my recommendation for a sign is:

Welcome to the Joneses'

based on the fact that for a family with the name "Smith", I would use

Welcome to the Smiths'

(The following question is very similar, but closed for some unclear reason: Re: a sign on your residence: The Smiths vs. The Smiths'. I disagree with the answers there.)

A: I'd go with "Joneses":

The plural of Jones is Joneses, ‐es being added as an indicator of the plurality of a word of which the singular form ends in s, as in dresses or messes. The apposition of the much misused apostrophe to the word Jones does not pluralize it. Source: Keeping up with the Jones' or Joneses?

A: Unless you are referring to the house of the Jones family or in any other way that makes it possessive 'Joneses' would be correct otherwise Jones' or Jones's are both correct but "Jones's" is preferred because it more closely represents the spoken English.

A: It somewhat depends on if you want to intend possession of something. You likely do because the implication is "Welcome to the Jones' [house]".
For that reason I would go with Jones'. If you are just pluralizing Jones, then, yes, it's Joneses. As in, "We are the Joneses.". In your case you are wanting a sign that indicates it's the home of the Jones family, the home you possess or own. So, Jones', whether you explicitly use the word house/home or not, seems to be the right word.
Link to answer on pluralizing names


text:
Q: How do I upload my personal NodeJS website to my FTP server? I need your help. I have my personal NodeJs website for a contact form. Everything works fine on my localhost, but when I put it on my FTP server it didn't work because the HTML file is in the "public" folder, I can't get this file out of the folder because otherwise it doesn't work anymore. So I had a problem transferring my website to the FTP server since my index.html file is in the "public" folder, which I solved by configuring the . htaccess, however, it only loads html but not CSS or JS, what do I do?
require('dotenv').config()

const express = require("express");
const app = express();

const nodemailer = require("nodemailer");

const PORT = process.env.PORT;

// Middleware
app.use(express.static("public"));
app.use(express.json())

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/public/index.html");
})

app.post('/', (req, res)=>{
    console.log(req.body);

    const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: 'mail@gmail.com',
            pass: process.env.NODE_PASS ,
        }
    })

    const mailOptions = {
        from: req.email,
        to: 'mail@gmail.com',
        subject: `Message from ${req.body.name}: ${req.body.email}`,
        text: `${req.body.message}`,
    }

    transporter.sendMail(mailOptions, (error, info)=>{
        if(error){
            console.log(error);
            res.send('error');
        }else{
            console.log('Email sent: ' + info.response)
            res.send('success')
        }
    })
})

app.listen(PORT, () => {
  console.log("Server running on port ${PORT}");
});

         <form id="myForm">

                  Name

                  <input type="text" name="name" id="name" required />

                  Email

                  <input type="email" name="email" id="email" required />

                  Message

                  <textarea
                    class="contact_textarea"
                    name="message"
                    id="message"
                    rows="5"
                    required
                  ></textarea>

              <button class="submit_cousin" type="submit">Submit</button>

          </form>

package.json

{
  "name": "contact-form",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "dev": "nodemon server.js",
    "start": "cross-env node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "nodemailer": "^6.4.17"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }
}

image of my folder

A: Thanks for providing the extra info.
Your express server is serving just the index.html file out of the public folder when you call GET /. If you want to be able to serve all the other static files from there using express, you can use the express.static middleware. Here are the docs: https://expressjs.com/en/starter/static-files.html
That said, it sounds like you're not actually running/accessing the express server.

I just did "$ npm install express --save" and used it by init I guess

To run the server, you would have to do node server.js.
Also, express wouldn't care about the .htaccess. I don't know what kind of server you are using, but it sounds like you are using its existing Apache setup to serve the public directory.
This is perfectly fine way to access a static site. You don't need to use express for this.
Also, this wasn't part of your question, but the from field is ignored by Google when sending mail this way. They will always come from your own email.
If you don't want to worry about making sure your express server stays online to send emails, you could consider using something like JotForm and embedding it into your app. I believe they have a free tier that you can use.


text:
Q: Why HttpHeaders doent send Bareer token in POST Request? I am using this in my service:
import {HttpClient, HttpHeaders} from '@angular/common/http';

and I'm triying to do a Post with this :
 public sendInvitation(id):Observable<any>{
    let url = URL_SERVICIOS + '/users/contacts?id=' + id;
    let headers = new HttpHeaders();
    headers.append('Authorization', 'Bearer ' + this.getToken());
    return  this.http
      .post(url , headers)
      .map(res => {
        return res['result'];
      })
      .catch(this.handleError)
  }

But when i am debugging i look :
1.OPTIONS REQUEST with 200 OK

*POST WITH 401 , because TOKEN DOESNT SEND

I've tried to change:
.appened with .set but this doesn't function yet
Maybe I am losing anything?
It's strange because when I do GET, it does function well
  public listContacts(type):Observable<Invitation[]>{
    let url = URL_SERVICIOS + '/users/contacts?type=' + type;
    let headers = new HttpHeaders().set('Authorization','Bearer ' +this.getToken());
    return  this.http
      .get(url , {headers})
      .map(res => {
        return res['result'];
      })
      .catch(this.handleError)
  }

Thank you in advance

A: There is a conflict in the parameters you used in the Post method.
you use the Post method as follows:
  .post(url , headers)

but the actual parameters is
 .post(url, body, headers)

you need to specify the body, in order to deliver the headers as it suppose to be.

A: It should fix the error:
public sendInvitation(id):Observable<any>{
  let url = URL_SERVICIOS + '/users/contacts?id=' + id;
  let headers = new HttpHeaders();
  headers.set('Authorization', 'Bearer ' + this.getToken());
  return  this.http
    .post(url , {}, {headers: headers})
    .map(res => {
      return res['result'];
    })
    .catch(this.handleError);
}


text:
Q: Explain usage of put statement   data _null_;
   %let _EFIRR_=0;
    %let _EFIREC_=0;

  file '/home/abc/demo/sale.csv' delimiter=',' DSD;
      put country=;
       run;

I wrote this code but couldn't find anything in the log. Shouldn't I be getting country=xyz in the log?

A: The FILE statement is used to write out to files. I believe you were attempting to read country values from the file instead.
You need the INFILE statement:
data _null_;
  %let _EFIRR_=0;
  %let _EFIREC_=0;

  /* infile statement points to the file which is being read */
  infile '/home/abc/demo/sale.csv' delimiter=',' DSD;

  /* Input statement specifies which columns to populate from the file */
  input country $;

  /* A put statement in a data step without an associated */
  /* file statement will output lines in the log */
  put country=;
run;


text:
Q: inverting colors in just one monitor (dual monitor setup) Using a dual monitor setup on Ubuntu 18.04, how can I invert colors on just one screen? I have been using xrandr-invert-colors and when I run it all monitors get their colors inverted.
My xorg.conf:

Section "ServerFlags"
        Option "DontVTSwitch" "on"
EndSection
Section "InputDevice"
    Identifier  "Mouse0"
    Driver      "mouse"
    Option      "Protocol" "auto"
    Option      "Device" "/dev/input/mice"
    Option      "ZAxisMapping" "4 5 6 7"
EndSection
Section "Device"
   Identifier  "Intel Graphics"
   Driver      "intel"
   Option      "AccelMethod"  "sna"
EndSection

Edit: xcalib -i -a also inverts the colors on both monitors.


text:
Q: CoqIDE and JAVA I want to retrieve the result of the compilation of a file. v from coqide or coqc for treated with java, rather I have treatment of an automaton and I want to build a graphical interface of this automaton in java.
Thanks for your response.

A: This project about connecting Coq to Eclipse might of of some help: Coqoon
It is specifically about Java verification and takes special care of managing .v files.


text:
Q: Legend in barplot with ggplot2 I have a barplot in ggplot2 with 12 bars (non stacked) in which every even bar has one color and odd bars have another color, but I can't figure out how to legend just the color of the bars. Even though I could reshape my data two just have this two categories they have to be displayed from 1 to 12.
For plotting I created a data frame with 5 columns in which the 1st is 1:12, the 2nd the heights of the bars, 3rd and 4th the standard errors and 5th the color of each bar.
and the code I used:
per.block.plot<-data.frame(block,means,std.up,std.down,color.block)
performance.per.block.plot<-ggplot(per.block.plot,aes(block,means)) +
     geom_bar(stat="identity",fill=color.block) + xlab("Block number") +
     ylab("Error rate") + ggtitle("Performance per block") +
     geom_errorbar(aes(ymin=std.down, ymax=std.up),width=.2) +
     theme_classic()

Thanks in advance!

A: As Heroka commented above, fill should be specified in aes() with the variable ... that determines the color of the bars, like so:
performance.per.block.plot<-ggplot(per.block.plot,aes(block,means, fill = ...))

Side hint: spelling the parameters out like aes(x = block, y = means) can help to build the working script you want ;-) Once working, there will still be time to remove these little helpers.


text:
Q: check whether an element is in list or not I have a matrix or list of lists:
x = [[1,2,3],
     [2,3,1],
     [3,1,2]]

My goal is to check whether
1) Each column of the matrix contains, each of the whole numbers from 1 to n exactly once.
2) Each row of the matrix contains each of the whole numbers from 1 to n exactly once.
This is the problem exercise that I encountered when I was solving Udacity's intro to programming course. This is my solution to the problem. I know that this is long and inefficient. So what is the short and efficient way to do this problem??
def check(p):
    j = 0
    for e in p:
        i = 1 + j
    s = str(p)

    if s.find('.')!= -1:
        return False

    while i < len(p):
        if p[i] == e:
            return False
        if p[i] > len(p) or p[i] < 1:
            return False
        i += 1
        j += 1
    return True

def check_sudoku(p):
    i = 0
    z = []
    a = []
    x = 0
    for e in p:
        r = check(e)
        if r == False:
            return r

    #Below here is to transpose the list
    while x < len(p):
        z.append(1)
        x += 1
    while i < len(p):
        for e in p:
            a.append(e.pop())
        z[i] = a
        i +=  1
        a = []

    #Below here is to check the transpose
    for g in z:
        r = check(g)
        if r == False:
            return r
    return True

A: You can simplify your check program like this:
def check_valid(matrix):
    n = len(matrix[0])
    valid_num = range(1, n+1)     # make a list of valid number from 1 to n

    # sort rows and column of matrix in ascending order and compare with valid_num
    for line in matrix:
        if sorted(line) != valid_num:
            return False
    for column in zip(*matrix):
        if sorted(column) != valid_num:
            return False

    # If all rows and column is valid, then
    return True

EDIT: follow @vocalno KISS rule but faster and work for both numbers and characters
def check_valid2(matrix):
    n = len(matrix)

    for line in matrix+zip(*matrix):
        if len(set(line)) != n:
            return False

    return True

In[9]: %timeit for m in (x, y): check_valid_mine(m)
100000 loops, best of 3: 8.55 µs per loop

In[10]: %timeit for m in [x,y]: check_valid2(m)
100000 loops, best of 3: 5.77 µs per loop

EDIT 2: all about the speed
def check_valid3(matrix):
    n = len(matrix)

    for line in matrix+zip(*matrix):
        if not len(set(line)) - n:
            return False

    return True

In[19]: %timeit for m in [x,y]: check_valid3(m)
100000 loops, best of 3: 2.29 µs per loop

A: Here's my solution
I cycle over rows and columns, using zip to flips matrix and chain - to combine 2 lists.
if either row or column contain values not in valid_set,
set(row) - valid_set

expression will yield non-empty set - turned to False by not- and all cycle will end
from itertools import chain
def check_valid(matrix, n):
   valid_set = set(range(1, n+1))
   return all(not(set(row) - valid_set) for row in chain(matrix, zip(*matrix)))

EDIT:
Sorry, misread the question; here's correct answer - all exits on first False
from itertools import chain
def check_valid(matrix):
   valid_set = set(range(1, len(matrix)+1))
   return all(set(row) == valid_set for row in chain(matrix, zip(*matrix)))

EDIT 2:
Out of curiosity - I timed sort vs set approach
In [74]: x = [[1,2,3],
   ....:      [2,3,1],
   ....:      [3,1,2]]

In [79]: %timeit for row in x: sorted(row)
1000000 loops, best of 3: 1.38 us per loop

In [80]: %timeit for row in x: set(row)
1000000 loops, best of 3: 836 ns per loop

set is about 30% faster
EDIT 3:
I fixed dangerous solution and updated mine
In [132]: def check_valid(matrix):
    valid_num = np.unique(np.array(matrix)).tolist() # selects unique elements
    for line in matrix:
        if sorted(line) != valid_num:
            return False
    for column in zip(*matrix):
        if sorted(column) != valid_num:
            return False
    return True
In [136]: %timeit for m in (z, d): check_valid(m)
10000 loops, best of 3: 57.8 us per loop

In [115]: def check_valid_mine(matrix):
       valid_set = set(chain(*matrix))
       return all(set(row) == valid_set for row in chain(matrix, zip(*matrix)))

In [137]: %timeit for m in (z, d): check_valid_mine(m)
100000 loops, best of 3: 8.96 us per loop

Bottom line? KISS - keep it simple stupid
Explaining the matrix transposition by zip()

*

*operator before iterable argument in a function call expands this argument list of positional arguments, essentially
zip(*matrix)
means
zip(matrix[0], matrix[1], matrix[2], ...)

thus rearranging columns into rows
Check out this answer for detailed explanation of * and ** operators

A: I was searching for a solution that perfectly matches both characters and numbers and I came with a solution using numpy library. I slightly modified dragon2fly solution. Please correct me if I am wrong.  I checked the solution for both z and d values and it gave correct results.
 import numpy as np

z = [[8,9,10],  # example case with numbers
     [9,10,8],
     [10,8,9]]

d =  [['a','b','c'], # example case with characters
      ['b','c','a'],
      ['c','a','b']]

def check_valid(matrix):
    valid_num = list(np.unique(matrix)) # selects unique elements

    # sort rows and column of matrix in ascend order and compare with valid_num
    for line in matrix:
        if sorted(line) != valid_num:
            return False
    for column in zip(*matrix):
        if sorted(column) != valid_num:
            return False

    # If all rows and column is valid, then
    return True


text:
Q: Connection question for Renology - order and possible converter needed? I bought a Renology 100w solar panel with charge controller - and I see in the controller instructions booklet, "Never connect the solar panel array to the controller without a battery. Battery must be connected first. This may cause a dangerous occurrence where the controller would experience a high open circuit voltage at the terminals."
However the solar panel connections for the controller included (looks like a MC4 by this page) show stop, do not disconnect under load. So, which is it, if I set up a portable system I cannot pack it up by unplugging the solar panel from the controller, I cannot pack up by unplugging the battery from the controller either?
What's more, I see the pack I have has an input of 15v, measured on the adapters and this probably will not work seeing the voltage marked 12v on the controller... would that charge it not at all or, very slowly? Would just a dc-dc converter 12v to 15v, to plug be all that's necessary in this case?


text:
Q: excel count unique values by group (cluster) in just a worksheet or a pivot table count the number of unique items by cluster
---------------------
name | cluster
---------------------
john    1
john    1
john    1
james   1
james   1
james   1
ron     2
ron     2
ron     2

and I would like to get....
--------------
cluster | count
--------------
1          2 (john and james)
2          1

I had an idea -- Maybe this can be done using a pivot table, but it seems only 2013 has the ability to count distinct? Can this be done with a pivot table calculated field?
I have to be able to do it it normal excel with a formula, because other people I work with do not have access to excel powerpivot. And whatever I do has to be able to be read by them.

A: You can do it with an array formula**, e.g. with your original table in A1:B10 (with headers in row 1), and e.g. 1 in C2, in D2:
=SUM(IF(FREQUENCY(IF($B$2:$B$10=C2,MATCH($A$2:$A$10,$A$2:$A$10,0)),ROW($A$2:$A$10)-MIN(ROW($A$2:$A$10))+1),1))
Regards
**Array formulas are not entered in the same way as 'standard' formulas. Instead of pressing just ENTER, you first hold down CTRL and SHIFT, and only then press ENTER. If you've done it correctly, you'll notice Excel puts curly brackets {} around the formula (though do not attempt to manually insert these yourself).


text:
Q: Set both meta_query and tax_query using wp_query->set Is there a way to combine both tax_queries and meta_queries using
wp_query->set() ?
I am trying to create an AJAX filter for WooCommerce, and I'm currently building out the conditional wp_query->set() in my ajax_functions.php file.
The final filter I am stuck with is when I am filtering for both a price_range, and multiple tag, checkbox or attributes selected. This is the query I want to run:
if($value['pRange'] && $value['tags']) {
  $wp_query->set('tax_query', array(
        'relation' => 'OR',
        array(
          'taxonomy' => 'product_tag',
          'field' => 'slug',
          'terms' => $value['tags'],
        ),
        array(
          'taxonomy' => 'product_cat',
          'field' => 'slug',
          'terms' => $value['tags'],
        ),
        array(
          'taxonomy' => 'pa_branding',
          'field' => 'slug',
          'terms' => $value['tags'],
        ),
      )
    );
    // I want to include the meta_query in the set() method above.
    'meta_query', array(
      'relation' => 'AND',
       array(
           'key' => '_price',
           'value' => array($value["pRange"][0], $value["pRange"][1]),
           'compare' => 'BETWEEN',
           'type' => 'NUMERIC'
       )
    ),
}

Could anyone help me on how I might do this?
Thanks in advance!

A: Just use another set() method:
if ($value['pRange'] && $value['tags']) {
    $wp_query->set('tax_query', array(
            'relation' => 'OR',
            array(
                'taxonomy' => 'product_tag',
                'field' => 'slug',
                'terms' => $value['tags'],
            ),
            array(
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                'terms' => $value['tags'],
            ),
            array(
                'taxonomy' => 'pa_branding',
                'field' => 'slug',
                'terms' => $value['tags'],
            ),
        )
    );

    $wp_query->set('meta_query', array(
            'relation' => 'AND',
            array(
                'key' => '_price',
                'value' => array($value["pRange"][0], $value["pRange"][1]),
                'compare' => 'BETWEEN',
                'type' => 'NUMERIC'
            )
        )
    );
}


text:
Q: How do I define functions using Racket macros? I am trying to write a macro that defines a special class of data structure with associated functions.
I know this is possible; it is done multiple times in the core language itself.
As a specific example, how would I define the define-struct macro in Scheme itself. It needs to create make-struct, struct-<<field>>, etc functions.
I tried doing this using define, however, this only defines the function in the macro's lexical scope.
How can I actually define a function in a macro?

A: The key for an answer is datum->syntax.  The basic idea is that you want to take some random data and turn it into a syntax -- in this case, turn a symbol into an identifier.  An identifier is basically a symbol with some lexical information that (very roughly) indicates how it is bound.  Using datum->syntax you can do exactly that: it expects an existing piece of syntax which is where it copies the binding from, and a datum (a symbol here) which is the value that is contained in the syntax wrapper.
Here's an example that demonstrates a define-struct-like tool using this:
#lang scheme
;; implements a defstruct-like macro that uses association lists
(define-syntax (defstruct-lite stx)
  (syntax-case stx ()
    [(defstruct-lite name field ...)
     (let ([make-id
            (lambda (template . ids)
              (let ([str (apply format template (map syntax->datum ids))])
                (datum->syntax stx (string->symbol str))))])
       (with-syntax ([make-name (make-id "make-~a" #'name)]
                     [name?     (make-id "~a?" #'name)]
                     [(arg ...) (generate-temporaries #'(field ...))]
                     [(name-field ...)
                      (map (lambda (f) (make-id "~a-~a" #'name f))
                           (syntax->list #'(field ...)))])
         #'(begin
             (define (make-name arg ...) (list 'name (cons 'field arg) ...))
             (define (name? x) (and (pair? x) (eq? 'name (car x))))
             (define (name-field x)
               (and (name? x) (cdr (assq 'field (cdr x)))))
             ...)))]))

And here's an example of using it:
(defstruct-lite point x y)
(point-y (make-point 1 2))


text:
Q: Mongo: is it possible to satisfy "and" condition on two documents Say I have two documents
/*1*/
{
"id":1,
"name":"natty",
"subject_enrolled":"english"
}
/*2*/
{
"id":2,
"name":"natty",
"subject_enrolled":"science"
}

Ideally, it should have been same document, with subject_enrolled being an array having both subjects. But for some reason, I maintained my data flat like this.
Now, I want to write a query which will retrieve all students who have enrolled for both "english" and "science".
I tried the below query:
db.students.find({"subject_enrolled":{"$in":["science", "english"]}})

But that is wrong, coz if any student who registered for only science will also be in the result. I cannot use "$all", as both science and english are in two different documents.
Is there a way to achieve this easily and effectively?

A: All I could think of now is to use an aggregate.
db.students.aggregate([{"$group":{"_id":"$name", "subject_enrolled":{"$addToSet":"$subject_enrolled"}}}, {"$match":{"subject_enrolled":{"$all":["english", "science"]}}}])

This satisfies my condition perfectly.
But I am worried about performance only. If I have say 10,000 documents, worst case I have all documents are for individual students and the querying Param is also a single value, then I will be aggregating for no good!
Mongo experts, please share your views on my situation.


text:
Q: normal subgroup + Socle I am looking for examples of socle and normal-subgroup relations.
If $G=S_{4}$, the normal subgroups are $A_{4}$ and $V_{4}$, thus the socle of $G$ is the klein-four group, and for $A_{4} \cap Soc(G) = Soc(A_{4}) = V_{4}$.
Now I am looking for some easy example where this does not work. Where we have no normal subgroup in $G$, s.t. the cut with the $Soc(G)$ equals the socle of this normal subgroup.
Any hints where I can look for such a group?
Thanks and best :)
Kathrin


text:
Q: Delay when updating the background of a UIButton I'm using setBackgroundImage:forState: to update the background of a UIButton. The background is updated but only after a few seconds. There is obviously some refresh cycle at work here but I can't find exactly what the problem is. I've tried to play with setNeedsRefresh and setNeedsDisplay without any result.
How can I change the UIButton background instantaneously ?
Thanks

A: Strange delays like this are usually caused when you try and perform UIKit operations on a background thread (e.g. in a delegate callback). Try this:
dispatch_async(dispatch_get_main_queue(), ^{
    // set your button background here
});


text:
Q: How can I get the numeric value of metric in SonarQube? How can I get the numeric value of a metric in SonarQube?
For example: <%= format_measure('ncloc') -%> will display the number of lines of code.
But I need to get the value (number of lines) in some variable to process further.
Thanks in advance.

A: Project Dashboards are dropped in SonarQube 6.1. I suggest to not put too much effort on writing widgets.
Moreover, Ruby code is being dropped and we don't know yet how it will be replaced or if it will be. I've notified our documentation team to make things clearer.
Regarding your question, you can assign the result of format_measure(…) to a variable and do whatever you want in Ruby.


text:
Q: Yeoman angularjs scaffolding error I am trying to run this command:
yo angular

But it gives me this error:
**/usr/local/lib/node_modules/generator-angular/node_modules/wiredep/lib/detect-dependencies.js:84
  if (_.isString(componentConfigFile.main)) {
                                    ^
TypeError: Cannot read property 'main' of undefined
    at findMainFiles (/usr/local/lib/node_modules/generator-angular/node_modules/wiredep/lib/detect-dependencies.js:84:37)
    at /usr/local/lib/node_modules/generator-angular/node_modules/wiredep/lib/detect-dependencies.js:146:17
    at forOwn (/usr/local/lib/node_modules/generator-angular/node_modules/wiredep/node_modules/lodash/dist/lodash.js:1301:15)
    at Function.forEach (/usr/local/lib/node_modules/generator-angular/node_modules/wiredep/node_modules/lodash/dist/lodash.js:2595:9)
    at detectDependencies (/usr/local/lib/node_modules/generator-angular/node_modules/wiredep/lib/detect-dependencies.js:28:5)
    at wiredep (/usr/local/lib/node_modules/generator-angular/node_modules/wiredep/wiredep.js:57:39)
    at Generator._injectDependencies (/usr/local/lib/node_modules/generator-angular/app/index.js:326:5)
    at /usr/local/lib/node_modules/generator-angular/node_modules/yeoman-generator/node_modules/async/lib/async.js:232:13
    at /usr/local/lib/node_modules/generator-angular/node_modules/yeoman-generator/node_modules/async/lib/async.js:113:21
    at /usr/local/lib/node_modules/generator-angular/node_modules/yeoman-generator/node_modules/async/lib/async.js:24:16**

How can I fix above error?
Note: I am running Ubuntu 14.04

A: The problem is Git was not installed, because yeoman tries to get bower_components via Git

A: I use nvm and came across this issue after installing and switching to the latest version of node. I realized I forgot to re-install bower globally:
npm install -g bower

After installing bower, the issue went away.


text:
Q: PHP Carbon add dynamic object property inside double quoted string I am trying to build a Carbon date from an existing Laravel date that uses dynamic object properties:
private static function createEvent($booking, $service) {
    dd(Carbon::createFromFormat('Y-m-d H:i:s', "$booking->service_{$service}_date_end $booking->service_1_time_end"));
}

This keeps returning:

Unexpected data found. Unexpected data found. Unexpected data found.
  Data missing

Any idea how I can get this to work? I can't seem to pass the variables directly to Carbon as it expects a string as a second parameter. The double quotes make things a little tricky.

A: Lets break this down a bit you have 2 properties one is dynamic.
So to access a dynamic property you can do this
 $prop = "service_{$service}_date_end";

 $booking->{$prop}

Then we just have a standard property an a space, so then putting that togather
     dd(Carbon::createFromFormat('Y-m-d H:i:s', $booking->{$prop}.' '.$booking->service_1_time_end"));

Now you may be able to put them together on one line, but you are basically double interpolating variables.  So it's easier to read and do if you take care of the one then do the other.
For me readability is everything, keep it simple and it will work.
That said I think this approach is fundamentally flawed, as you have no real way to know if the property actually exists.  So you are leaving yourself open to errors like, undefined object property .
You could do it more robustly using a simple switch statement.
But, without knowing the full scope of how you are using it or where $service comes from I can't say that, it may be fine in your use case.  I just wanted to give you a word of caution.


text:
Q: Realtek Audio Manager on Kubuntu 12.04 I have Realtek soundcard on my HP-430 notebook but I can't seems able to have it's HD sound experience. The sound is lousy compared to Windows 7.
I've been searching all over the 'www' to find any Realtek Audio Manager for linux or some sort of it but have no luck. All I could find is Realtek Soundcard driver form their website.
I don't want go back to Windows 7 because of it. Would anyone help me, please.

A: Have you tried to install drivers using Additional Drivers?
Can you see your driver when clicking on the speaker icon (the one you click to adjust volume)? If you can't, your driver may not installed.
Try typing Additional Drivers into search and it should pop up, then launch it.
Now activate your drivers by clicking on its name, then choosing activate. It should then start downloading and installing that driver for you.
(I have Realtek Audio too)
If you need help, let me know.
Oh yah, its a good idea to update your post by clicking the "edit" just right under your post.

A: Never mind, finally my problem is assumed solved.
I updated ALSA driver with this driver update script.
And then installed PulseAudio Equalizer as explained on this thread.
And now, the Audio Setup does showed ALC270 soundcard.
The sound quality is almost as good as in Win7.


text:
Q: Determine when $f_{a}(x)$ is bounded. For some $a\in \Bbb{R}$ define a function $f_{a}(x) =
\begin{cases}
{x^{a}\cos{1\over x}},  & \text{if $x$ $\ne$ 0} \\[2ex]
0, & \text{if $x=0$}
\end{cases}$
What should $a$ be in order for $f_{a}(x)$ to be bounded?
I am a bit confused... $cos{1\over x}$ is bounded by $-1,1$ so every real $a$ should give a bound, is it not so??

A: 1) If $\;a>0\;$ , then
$$f_a(x)=x^a\cos\frac1x\xrightarrow[x\to\infty]{}\infty\;,\;\;\text{since}\;\;\cos\frac1x\xrightarrow[x\to\infty]{}1$$
2) If $\;a<0\;$ , then
$$f_a\left(\frac1{2n\pi}\right)=\frac1{(2n\pi)^a}\overbrace{\cos2n\pi}^{=1}\xrightarrow[n\to\infty]{}\infty$$
Well, what $\;a\;$ then works for sure ?


text:
Q: How to invoke a Polymer Method, that is not exposed as attribute, via Javascript? for example, when you load the Google Web Components <google-streetview-pano> polymer element, the panorama slowly rotates. Upon inspection of the google-streetview-pano.html file it is easy to see the "update" function that makes this happen. There is also a "stop" function that calls cancelAnimationFrame(this.rAFid) to stop animation.
How can I call the "stop" function from a button on the page?
Do all exposed public functions need to be listed in the attributes declaration of the google-streetview-pano.html file? If so, do I need to create a new custom element based on the parent?

A: Methods are on the element's prototype. You call a custom element's method just like calling a native HTML element DOM API:
<google-streetview-pano id="pano"></google-streetview-pano>
<script>
  document.addEventListener('polymer-ready', function() {
    document.querySelector('#pano').stop();
  });
</script>

Published properties are properties on the element that are configurable via an HTML attribute of the same name. They're different than methods.


text:
Q: Bound combobox items refers to different field items I got a bounded combobox to a group name in vb.net. i can view in the drop down items of the combobox the set of GROUP NAMES. but when i do an insert or update query, i need to make the selected group name refers to the GROUP NUMBER. I don't want to store letters in the database, instead i prefer numbers. how can i do that?!
Here is my code so far :
cmd1.Parameters.AddWithValue("@group", DirectCast(Additemcombobox.SelectedItem,
                                  DataRowView).Item("GroupName"))

Storing the group name in database is currently working well.
My question might not be well explained. Please ask me in case...
any help would be appreciated

A: You can show one element to the user such as the name, but use a different one for the code to identify the item using DisplayMember and ValueMember
Dim SQL = "SELECT Id, Name FROM GroupCode ORDER BY Name"
...
GrpDT = New DataTable
GrpDT.Load(cmd.ExecuteReader)

cboGroup.DataSource = GrpDT
cboGroup.DisplayMember = "Name"
cboGroup.ValueMember = "Id"

The user will only see the names, while the code can use ValueMember:
Private Sub cboGroup_SelectedValueChanged(...etc
    Console.WriteLine(cboGroup.SelectedValue)
End Sub

It prints the Group ID not the name.  Depending on the ORDER BY clause in the SQL and the ID, the SelectedIndex may or may not match, so respond to SelectedValueChanged event.  If you use SelectedValue instead of SelectedItem you wont have to thrash about with a DataRowView item.
Note that SelectedValue is Object so you will have to cast to integer or whatever for use elsewhere.


text:
Q: Parse multiple paragraph in a single loop-cycle with BeautifulSoup I am parsing the comment section of a blog. The structure is unfortunately quite irregular.
Here two situations I am facing:
The first comment will be divided in multiple paragraphs

My first paragraph.
But this a second line

And this is a third line

while the second only in one paragraph.
I want to parse each comment in a string variable. But executing the following code
from bs4 import BeautifulSoup

html_doc = """
<!DOCTYPE html>

First comment and first line

First comment and second line

          Date1

Second comment

          Date2

"""

soup = BeautifulSoup(html_doc)

for p in soup.find(id="firstDiv").find_all("p"):
    print "Print comment: " + p.get_text()
    print "End of loop"

the program will catch the first two paragraph in different instances of the loop, printing
Print comment: First comment and first line
End of loop
Print comment: First comment and second line
End of loop
Print comment: Second comment
End of loop

How could I proceed to print the first two paragraphs in the same loop?

A: soup = BeautifulSoup(html_doc)
text = [''.join(s.findAll(text=True))for s in soup.findAll('p')]

text = [''.join(s.findAll(text=True))for s in soup.findAll('p')]
print ", ".join(text[:2])
print " ".join(text[2:])

First comment and first line, First comment and second line
Second comment

When call soup.find(id="firstDiv").find_all("p")  it creates a list as below, so it is logical that iterating over three elements in the list you getting three loops:
[
First comment and first line
,
First comment and second line
,
Second comment
]

A: What you're trying to do here isn't a job for soup, because you're dealing with flat data whose structure isn't reflected in the HTML. So, you want to let the soup take you as far as it can, then switch over to iteration.
The easiest way to get the p and div children of the parent div is to just get all the children. We only want the HTML nodes, not the strings between them, so we can find with no parameters. Like this:
def chunkify(parent):
    """yields groups of
 nodes separated by
 siblings"""
    chunk = []
    for element in parent.find_all():
        if element.name == 'p':
            chunk.append(element)
        elif element.name == 'div':
            yield chunk
            chunk = []
    if chunk:
        yield chunk

for paras in chunkify(soup.find(id="firstDiv")):
    print "Print comment: " + '\n'.join(p.get_text() for p in paras)
    print "End of loop"

The output will be:
Print comment: First comment and first line
First comment and second line
End of loop
Print comment: Second comment
End of loop

And that's what you want, right?

You can write that function much more compactly, and I think more readably if you understand itertools… but I wanted to write it in a way that would make more sense to a novice, even if it's clunkier, first. Here's a shorter version:
def chunkify(parent):
    """yields groups of
 nodes separated by
 siblings"""
    grouped = groupby(parent.find_all(), lambda element: element.name != 'div')
    groups = (g for k, g in grouped if k)
    return ([node for node in g if node.name == 'p'] for g in groups)

You can also replace those first two lines with a higher-level function that wraps groupby; I more-itertools has this, or at least has something close to it:
    groups = isplit(parent.find_all(), lambda element: element.name != 'div')


text:
Q: zftool create controller not working I add zftool.phar to /usr/local/bin as zftool. I use zf 2.2 in my ubuntu 13.04 machine. I can create project and module at /home/dinuka/workspace using following command.
zftool create project test
zftool create module Admin test

I try to create a controller inside workspace folder using
zftool create controller Home test/module/Admin

But it shows following message
The path . doesn't contain a ZF2 application. I cannot create a module here.

So i move inside to the test directory and try following command.
zftool create controller Home Admin

But it shows following error.
PHP Fatal error:  Class 'Zend\Cache\Service\StorageCacheAbstractServiceFactory' not found in phar:///usr/local/bin/zftool/vendor/zendframework/zend-servicemanager/Zend/ServiceManager/ServiceManager.php on line 2

All zftool command inside test directory is show above error.
How can i create a controller?

A: When you create your project you need to install Zend Framework in it. This is one of the ways to do it if you want your project to contain the Zend Library.
It is done like this:
$ php zftool.phar create project myzendproject
$ cd myzendproject
$ php composer.phar install

This will install Zend Framework into your new project
Then you may type:
$ cd ..
$ php zftool.phar create module MyModule myzendproject

which will create MyModule module into your project, but you have to do this from the parent directory. It won't work if you try from myzendproject$
Good luck!


text:
Q: How to enable user registration for specific country and disable registration from all other countries? is their any method to enable user registration for specific country like only people from USA can register and all other users coming from other countries redirect to to a specific page showing them message that  only people from USA can  register to this site ?

A: After some thought, I have a better answer. Although keep in mind all of this can be circumvented by having a friend living in the US:

*

*Credit card transaction - This is your best bet for verifying, however it's possible the person is foreign and has a US credit card, be it for business purposes, or to order things from the US. This will likely cost you money, and you'll be subject to finance & privacy laws

*Mobile Phone SMS - This can be done using an external SMS service, but keep in mind I could take a holiday in the US, and buy a pay as you go phone, then use your service when I return to the UK, as a UK citizen. SMS services normally cost money, and you'll be subject to personal information laws
Try
http://wordpress.org/extend/plugins/sms-text-message/ or http://wordpress.org/extend/plugins/quick-sms/

*GPS - This would work, but, it assumes the other person can be trusted, and is easily spoofable. Numerous devices and browsers do not support this, and most desktop machines lack the hardware. Some browsers ask where the user is, letting them move to the US by choice. This also discriminates against American citizens on holiday elsewhere ( President Obama on holiday in Italy tries to get on your site? Nope, access denied )
All three can be bypassed or spoofed. All three require that the user trust you ( they're likely to leave the site in disgust or opposition, after all would you hand over your credit card details or mobile phone number to just anyone? ), also these details are all private, and are heavily regulated.
If your site is usable by non-US citizens, then you shouldn't limit yourself. If your site provides a service that is meaningless outside the US, then let them sign up if they choose but warn them that there won't be much point.
To summarize:
There are measures you can take, but the internet is inherently anonymous, and you can't be sure if the user is an American at a Russian computer cafe, or a Russian sitting on the whitehouse lawn.
Of Note
All three methods I pointed out are beyond the scope of this website, as they are not WordPress problems, but general problems. There may be plugins that can help, but thats a different question. You will certainly need help with credit cards ( beyond WordPress, you need to be able to handle raw credit details online, you can't just use a paypal or WordPress plugin, then there's compliance needed for your code )

A: Your best bet is to require them to enter a piece of information that is specific to the USA.
e.g. to limit UK people you would ask for a UK post code
Alternatively you could trust your users and ask them if they're in the USA.
Tracking users by their IP will get you some of the way, but geolocation databases aren't precise, or reliable, and you will have lots of false positives and negatives. It's also absurdly easy to get around via proxy websites, or SSH tunnels.
Thus without ISP cooperation, there is no guaranteed way of doing this.
As a non US citizen I would hope you're not depriving me of well earnt cookies!