text:
Q: C: Palindrome: Different strlen-values I'm making a function which reverses a string and checks if the string is a palindrome or not. When I test the function with a obvious palindrome like "abba", the function says it's not a palindrome. Also the forward string and the reversed string also differ in string length!
#include <stdio.h>
#include <string.h>

char forward [] = "abba"; //The string to be reversed

int size = (sizeof(forward)/sizeof(forward[0]) - 1);
int j = 0;
char reverse [10];

void reverser(char forward []) {

    printf("%s", "String forward: ");
    for (int i = 0; i < size; i++) { //Function for printing out the forward string.
        printf("%c", forward[i]);
    }

    printf("\n");

    printf("%s", "String reversed: ");

    for (int i = size, j = 0; i >= 0; --i, ++j) { //Function for reversing the string and printing it.
        reverse[j] = forward[i];
        printf("%c", reverse[j]);
    }

    printf("\n");

    if (strcmp(forward, reverse) != 0) { //Using strcmp to check if the forward and reversed string are the same.
        printf("Not a palindrome!\n");
    }
    else{
        printf("A palindrome!\n");
    }

    printf("Forward string length: %d\n",strlen(forward));
    printf("Reversed string length: %d\n",strlen(reverse));
}

int main () {
    reverser(forward);
}

Output:
String forward: abba
String reversed: abba
Not a palindrome!
Forward string length: 9
Reversed string length: 0

A: In this loop
for (int i = size, j = 0; i >= 0; --i, ++j) { //Function for reversing the string and printing it.
    reverse[j] = forward[i];
    printf("%c", reverse[j]);
    }

forward[i] is the terminating zero of the string when the initial value of variable i is equal to size
Try the following loop implementation
for ( int i = size, j = 0; i != 0; ++j) { //Function for reversing the string and printing it.
    reverse[j] = forward[--i];
    printf("%c", reverse[j]);
    }

Also take into account that for variables that will store values returned by the operator sizeof or by the function strlen it is better to use type size_t.
So in these statements
printf("Forward string length: %d\n",strlen(forward));
printf("Reversed string length: %d\n",strlen(reverse));

use format specifier %zu instead of %d
For example
printf("Forward string length: %zu\n",strlen(forward));
printf("Reversed string length: %zu\n",strlen(reverse));

Some answerers here said that you have to zero-terminate the string reverse. However it is already zero-terminated because it is declared outside any function and as result has the static storage duration and as such it is zero-initialized by default.

A: I think the first char of "reversed" is '\0'.
Replace this line int size = (sizeof(forward)/sizeof(forward[0]) - 1); by int size = strlen(forward).
Moreover :
printf("%s", "String forward: ");
 for (int i = 0; i < size; i++) { //Function for printing out the forward string.
    printf("%c", forward[i]);
 }
can be replaced by printf("String forward : %s\n", forward);

A: You are putting the null character in the first index when reversing (reverse[0]). That's why every fails.
for (int i = size, j = 0; i >= 0; --i, ++j) {
    reverse[j] = forward[i];
}

should be
for (int i = size - 1, j = 0; i >= 0; --i, ++j) {
    reverse[j] = forward[i];
}
reverse[size] = '\0';

sizeof(forward)/sizeof(forward[0]) is 5 which means size = 4.
forward[0] = 'a'
forward[1] = 'b'
forward[2] = 'b'
forward[3] = 'a'
forward[4] = '\0'

A: The reversing code is off by one on one of the indices, i should run from size-1 to 0 inclusive:
// Function for reversing the string.
for (int i = size, j = 0; i > 0;) {
    reverse[j++] = forward[--i];
}
reverse[size] = '\0';

To avoid updating 2 different indices, you can simplify this loop:
// Function for reversing the string.
for (int i = 0; i < size; i++) {
    reverse[i] = forward[size - 1 - i];
}
reverse[size] = '\0';

There are many other issues in your code:

*

*forward and size are global variables, but you also name the argument in function reverser the same way and use the global size there, which may be inappropriate if called with a different argument.  size and even worse j should not be global variables (!)

*function name reverser is inconsistent with what the function does: printing its argument.

*you can print the argument string directly with a %s printf format.  No need for a loop.

*%d is not the correct format for strlen() return value.  Either cast as (int)strlen(forward) or use %zu.


text:
Q: Multiple netlify static sites served under a single cloudfront domain path I have multiple netlify static sites that I want to serve in their entirety under a path of a cloudfront domain.  However, resources that don't reside at the root of the netlify app are not being served (raise a 404)
i.e.
https://netlify1-abcd123.netlify.app/

*

*/

*/page1

*

*/page1/subpage1

*/page2

*/images/logo.png

*/stylesheets/styles.css

https://netlify2-defg456.netlify.app/

*

*/

*/netlify2-page1

*

*/netlify2-page1/subpage1

*/netlify2-page2

*/netlify2-images/logo.png

*/netlify2-stylesheets/styles.css

and I want these to be served under www.mydomain.com/netflify1 and www.mydomain.com/netlify2.  The root of www.mydomain.com is currently served via an S3 static site.
I have configured rewrite rules in netlify.toml for each site (changing as appropriate to netlify2) as below:
[[redirects]]
  from = "/netlify1/*"
  to = "https://netlify1-abcd123.netlify.app/:splat"
  status = 200
  force = true

...and then added an Origin to Cloudfront which has the Origin Domain Name of https://netlify1-abcd123.netlify.app/ - all other Origin settings are the defaults.
I've then configured a Behaviour with a Path Pattern netlify1 that points to the netlify1 origin.  Note that I cannot use the Default behaviour as the main index of www.mydomain.com is served via a static site hosted on S3.
This all works perfectly fine when serving the root / of my netlify app.  I can navigate to www.mydomain.com/netlify1 and see the home page of my netlify app.  However,  anything that is not on the / of netlify doesn't get served.
I can see from the developer tools that a request is being made to www.mydomain.com/images/logo.png and www.mydomain.com/stylesheets/styles.css when trying to load the images and the styles.  This returns a 404 because (I presume) they are not getting picked up by any Cloudfront Behaviour or Netlify rewrite rules.
So my question is.  How can I make images, stylesheets and any page not on the root of the netlify apps work correctly?  I can make it work by manually added every single potential path as a Behaviour on Cloudfront (i.e. configure a Behaviour with a Path Pattern of /images/* to point to the netlify1 Origin) - but that doesn't seem scalable or even correct.
I don't know whether I need to somehow rewrite all my URLs on the netlify app during building so that they become /netlify1/images and /netlify/page1 rather than /images and /page1 (the netlify apps are docs built with Sphinx docs), or whether this is something that needs to be handled via a Rewrite Rule in Lambda@Edge.  I'm completely stumped.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get All the contents between two tags by excluding few tags in it I want to retrieve everything between two tags of an xml by excluding few tags within that content. What is the regular epxpression for this? For example,in the below xml I want to extract everything between <ASObject mappedClass="com.taliantsoftware.claims.indemnity.PayeeAllocationDTO" encoding="0"> and </ASObject> by excluding <updated tagClass="boolean">false</updated> and    <voided tagClass="boolean">false</voided> tags.
<ASObject mappedClass="com.taliantsoftware.claims.indemnity.PayeeAllocationDTO" encoding="0">
    <payeecustomerid tagClass="double">2004570.0</payeecustomerid>
    <amount tagClass="double">2131.2</amount>
    <new tagClass="boolean">true</new>
    <percent tagClass="double">100.0</percent>
    <updated tagClass="boolean">false</updated>
    <voided tagClass="boolean">false</voided>
    <remainderindicator tagClass="boolean">true</remainderindicator>
    <detailamountstatustypecode tagClass="String">pnd</detailamountstatustypecode>
    <primary tagClass="boolean">true</primary>
    <mailtoindicator tagClass="boolean">true</mailtoindicator>
    <checkgroupnumber tagClass="double">1.0</checkgroupnumber>
    <detailamountstatustypename tagClass="String">Pending</detailamountstatustypename>
    </ASObject>

A: If you want to just remove updated and voided tags, this regex should work:
var clean_xml = xml.replace(/<(updated|voided).*</\1>/,'')

Notes:

*

*you can add other tags, but they can't be self-closing with this regex

*xml parsers are more reliable

edit
If you have to firstly capture the ASObject tag, the regex is not very pretty. Perhaps better with a recursive pattern.
/(<ASObject.*)<(updated|voided).*<\/\2>(.*)<(updated|voided).*<\/\4>(.*<\/ASObject>)/

And then concat the indexes 1,3,5 of the resulting array.


text:
Q: SP Foundations 2013 workflow - copying data from source list to field in tasks Greetings to everyone,
I am really putting my efforts in setting a sharepoint foundation 2013. One of my start workflows is leave request approval process, made from scratch in sharepoint designer.
In short - I am using 'collect data from user' to get the approval / rejection.
My goal is to ( after the task is created ) to copy there some fields from source list - mainly 'leave start date' and 'leave end date'. So the task will have it visible straight away, without 7 clicks.
The problem I encountered:

*

*Workflow pauses after 'collect data' line ( history logs inserted before - went ok / after - nothing )

*I tried to populate source list with ID of the created task - into some column, for future reference - failed.

I would really appreciate help in this issue. I found some tips use for this purpose output ID from the collect line?
Adding some details:

*

*the workflow is live and running

*I can provide some screens, if needed I will translate the PL comands

New thougt - it might be that the core problem is getting task id just after the task is created, and putting it the 'leave' list. Found some hints about parallel actions, side workflows - but no progress yet.
Thanks in advance,
Tom, Poland

A: Why are you using "collect data from user"?  I would recommend a different approach. Simply leverage the out of box approval workflow on the list or form. It will automatically create the approval task and even send email to the approver for you.
EDIT: Sorry, I missed the foundation catch.  Here's some recommendations from a Stack thread on the same topic.
SharePoint 2010 Approval Workflow in Foundation?


text:
Q: How to effectively manage multiple URL responses in python 3? Background:
I have a script that runs analytics against a series of URL response objects (json).  I do this by iterating over a dictionary containing the URLs, and then dynamically creating filenames and writing those files to disk, performing the analytics upon opening the files into memory.
I would like to eliminate the IO in the script and push this downstream to my users who could run it themselves in a Jupyter notebook using pandas dataframes to do the table presentation/logic.
This is the code snippet that I am unsure how to modify:
for key, value in url_dict.items():
    print("Issuing query for {}".format(key))
    json_response = s.get(value, verify=cert_authority)
    data = json_response.json()
    jsonfilename = 'query_' + key + '.json'
    jsonfile = os.path.join(query_output_directory, jsonfilename)
    with open(jsonfile, 'wb') as outfile:
        json.dump(data, outfile)

What I am trying to figure out is how to pipe the various json response objects into their own variables; e.g., instead of just data I need data1, data2, etc.  It feels like I need dynamic variables but I am sure there must be a far less janky solution.

A: You can just append the responses to a list as you loop through.
alljsonvariables=[]
for key, value in url_dict.items():
    print("Issuing query for {}".format(key))
    json_response = s.get(value, verify=cert_authority)
    alljsonvariables.append(json_response.json())
#the rest of your code goes here


text:
Q: perl extract common elements from 2 arrays (common sequences in fastq file) I have 2 file (paired_end) with reads in fastq format from the same organism (File_R1.fastq and File_R2.fastq). And I want to determinate the coverage deep using bwa and samtools (bioinformatics), for do it I need both files with the same number of reads, the same name (file_1: @XX00341:4450:6341 1:N:0:AACGTTAA+TTGCAATT   and   file_2: @XX00341:4450:6341 2:N:0:AACGTTAA+TTGCAATT), in the same order in both files, the problem is that both files have empty reads (The corresponding read for each file, could be empty in one but not in other !!!!), and if I try to run it with bwa it fails due to empty sequences.
So I'm trying to make a perl script to extract the NO empty reads with the same name and order in both files.
this is the format of fastq file (each read has 4 lines: name (@XX00341:19:000H27K25:1:11101:4450:6341 1:N....), sequence (GAGGTGCGTGGTTGTCACCCC...), Q_head (+) and Quality (FFFFFFFFFFFFFFF....), in that order.
file_r1.fastq (characterized with = .... 1:N:0:AACGTTAA+TTGCAATT)
@XX00341:4450:6341 1:N:0:AACGTTAA+TTGCAATT
CGCCCATCATGAGGTGCGTGGTTGTCACCCCCGCAAACGCGGAGGTGTAAACAGGCTCACCTGTGGGTTGTTGGTAGTCGTTATTGTGCTTGCGCTGTTCATCTGGATTACTGGATTCGACGCGTTGAGC
+
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
@XX00341:14420:6341 1:N:0:AACGTTAA+TTGCAATT
GCTTTGTCGTCGTCGGTTTTAAAGTGAACCGCTTTACCTGTTTCTGCTTGAACTTGTTCTGCTTGAGGTGCTGCTTCTGGTTTTGTTTCTTCTTTCTGACAACCTACCGCTAGCATTACTGTTGCAGCAA
+
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF/FFFFAAFFFFFFAFFFFAFFFFFFFFFFAFAFFFFFAFFFFFFFFFFFFFFFFAFFFFFFFFFFFFFAFFFFFFFAFFFFFFF/FFFFFFFFFFFF
@XX00341:10259:6342 1:N:0:AACGTTAA+TTGCAATT

+

@XX00341:6685:6342 1:N:0:AACGTTAA+TTGCAATT
CATTGGAAGGCAAGCCAGAACAAGGCAAGAATATTCCAGATGACATCGTGCGCGTTCGCATCGATCGCAACAGCGGTCTGCTGACTCATAAAGTGGATAGCACGTCCATGTTTGAATACTTTGAGAAAGG
+
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF6FFFFAFFFFFFFFFFFFFFFFFFFFFFFFFFFAFFFFFFFFFFFFFFFFFFFFFFFFAFFFFFFFFFFFFFFFFFFFFAFFFFFFAFFFFFFFFFFFFF
@XX00341:4051:6343 1:N:0:AACGTTAA+TTGCAATT
TCACCATGATCGGATTTATGAATGGTTTAGTGGACAGCATGATCAAAAATGCGATTGCTTGGCAAACCAGCCATTTGCAGATTCATCAAAGTGCTTATCTCGTTAATCCTGAACTGAAAGACACCATACC
+
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
@XX00341:12307:6344 1:N:0:AACGTTAA+TTGCAATT
TCCAAATTGAGAGTTAATGTGAAAAAAGAATGACTTTTTGCTTGTCATGCAGCGGATTTGTGTGATACCACTAATGACGCAAACATTTTCGTAGAACATTACACAATACTATTTAACGAAAAAAGAACGA
+
FAAFFAFAAFFAFFF/FF/FFAFFFFFFFFFAAFFF=F=AFFFFFFFFFFFFAFFFFFFFFFFAFFFFFFFFFFAFFFFFAAFFFFFFFFFF/FAFFFFAFFFFFFFFFFFFAAAFFAF///FAFFFFFF
@XX00341:24250:6345 1:N:0:AACGTTAA+TTGCAATT
CGAACATAGAGCAAGCTCTGGTAAGTCCCGATGGGAGCTTAAAGACACAAGTAGACCAAAAGCTCGCAGAACATGGCTTGAGCCGTAAAGTCACCGTGGCGTCGCGCAACTTTCTCACCATTCGGCATCT
+
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF

file_r2.fastq (characterized with = .... 2:N:0:AACGTTAA+TTGCAATT)
@XX00341:4450:6341 2:N:0:AACGTTAA+TTGCAATT
GCGGCTTTGGTAGCGAAGCGCGTCTACCAACCGCAGCCATGAAACAACTGGCGTTTGAAGTGGAAAAAACGGCAGCGGGCAGTATTCCGGTACTGATTGAAGCCATCGAACAAGTGGCGGTGCCTACCGC
+
AFFFFFFFFFFFFFFFFFFFFFFFFFFFFAFFFF/FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAFFFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
@XX00341:14420:6341 2:N:0:AACGTTAA+TTGCAATT
GCGGTTCGAGTGGCCAACGTTGAACTTCATGCTCGGTAAAAAAGCAACCATTTAACGTGGTGATGACAATTAAATATAGGAATAAATGAGAAATTCTTTGCATCACATCTAATAATCCGGTTTGTGTCTT
+
AFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF/FFFAFAFFFFFFFF/FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAFFFFF
@XX00341:10259:6342 2:N:0:AACGTTAA+TTGCAATT
TCTTTTTTCGTTAAATAGTATTGTGTAAT
+
FFFFFFFFFFFFFAFFFFFFFFFFFFFFF
@XX00341:6685:6342 2:N:0:AACGTTAA+TTGCAATT
GAATAAATGCTGTCTTCGAGGCTGTTACCAACGTATTCGGTTGGCTCCGTGCCTTTCTCAAAGTATTCAAACATGGACGTGCTATCCACTTTATGAGTCAGCAGACCGCTGTTGCGATCGATGCGAACGC
+
AFFFFFFFFAFFFFAFFFFFFFFFFFFFFFFFFFFFFFF/FF/FFFFFFFFAFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFAFFFF=FF=FFFFFFFAFFFFFFF
@XX00341:4051:6343 2:N:0:AACGTTAA+TTGCAATT
GAAGCTATCATGCCATCGGCGAGAAACCGCTCCGATACGGCTTTCACGCTTTGATGCTTGTCTAACGTTGTCACGATGCTTTGCGAGTCAGGTATGGTGTCTTTCAGTTCAGGATTAACGAGATAAGCAC
+
AFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
@XX00341:12307:6344 2:N:0:AACGTTAA+TTGCAATT
GTTCATCTGTCTGTCGTTCTTTTTTCGTTAAATAGTATTGTGTAATGTTCTACGAAAATGTTTGCGTCATTAGTGGTATCACACAAATCCGCTGCATGACAAGCAAAAAGTCATTCTTTTTTCACATTAA
+
AFFFFFFFFFAFFFFFFFFAFFFFFFFFFFFFFAFFFFFFFFFFFFFFFFFFFFFFFFFFFF=FFFFFFFAFFFFFFFAFFFFFFFFFF=FAFFFFFFFFAFFFAFFAFFFFFFFFA=AFF6AFFAFAFF
@XX00341:24250:6345 2:N:0:AACGTTAA+TTGCAATT
CCATAGCATGGCAATATCAAAATCCGCAACGGCGATCGGCGGCTTAACAGTAATGAGATCGTCTGAAAAGCCCTCCGCCAACGCCATTTTTTCTGGCACGATGGCAATGAGATCGCGCTTTTTCAATAGA
+
AFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF/FFFFFFFFFFFFFFFFFFFFFFFFFFF

in this case, one read is empty in the file_1.fastq (@XX00341:10259:6342 1:N....), the second and fourth line are empty (sequence and quality), but not in the file_2.fastq (@XX00341:10259:6342 2:N....); in this example both sequences (the 4 lines in each file) must be omited !!!
This is the code that I´m trying to finish:
#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;

my ($fastQ_R1, $fastQ_R2);
      GetOptions (
            'R1|r1=s'   =>\$fastQ_R1,
            'R2|r2=s'   =>\$fastQ_R2,

      );

    sub extract_list {
        my ($file_in) = @_;
        open FILE, '<', $file_in or die "cant open the $file_in\n";

        my (@elements, @list, @seq);
        while(
            defined(my $head    =   <FILE>) &&   # 1 line
            defined(my $seq     =   <FILE>) &&   # 2 line
            defined(my $qhead   =   <FILE>) &&   # 3 line
            defined(my $quality =   <FILE>)      # 4 line
        ){
            if ($seq=~ m/^$/g){
                next;
            }
            else {  push @seq, $head;   }
         }
        close FILE;
        foreach (@seq){
            chomp;
            @elements = split '\s', $_;
                push @list, $elements[0]; # split to eliminate 1:N... (file_1) and 2:N... (file_2)
        }
        return @list;
    }

    my @list_R1 = extract_list ($fastQ_R1);

    my @list_R2 = extract_list  ($fastQ_R2);

So far I have the list of No empty sequences (@list_R1 and @list_R2) in both files, the comparison the both arrays will give the No empty reads (with 4 lines !!) that are present in both files (@common_elements) obtained from the comparison of both array.
@list_R2=
@XX00341:4450:6341
@XX00341:14420:6341
@XX00341:6685:6342
@XX00341:4051:6343
@XX00341:12307:6344
@XX00341:24250:6345

@list_R2=
@XX00341:4450:6341
@XX00341:14420:6341
@XX00341:10259:6342
@XX00341:6685:6342
@XX00341:4051:6343
@XX00341:12307:6344
@XX00341:24250:6345

@common_elemnts=
@XX00341:4450:6341
@XX00341:14420:6341
@XX00341:6685:6342
@XX00341:4051:6343
@XX00341:12307:6344
@XX00341:24250:6345

so the new array (@common_elemnts) will be used to search and extract the common reads (4 lines) foreach file and will give tow output files: Files_R1_common.fastq (obtained from the File_R1.fastq) and File_R2_common.fastq (obtained from the File_R2.fastq).
Any suggestion, will be appreciated !!!!
Thanks so much

A: You'd better use hash maps to check for item existence in lists.
Construct common hash map:
my %list1_map = map { $_, 1 } @list_R1;
my %common_map = map { $list1_map{$_} ? ($_, 1) : () )} @list_R2;

Then process your lists:
for my $item(@list_R1) {
if (defined ($common_map{$item})) {
    # ... process ...
}

A: In the following solution, I've moved the FASTQ parsing to a separate class, which will read 4 lines from the file and return a hashref of id, hdr, seq, and qual representing one record.  I've left writing this class to you as an exercise.  Doing so makes the logic below easy to follow.  Readability is important.
This code simply saves the IDs (i.e. the $1 in $hdr=~/^@(\S+)/) of empty seqs from file1.  Then it reads file2 and outputs complete records and also saves IDs of empty records.  Finally, you read file1 again and output the complete records by removing those indicated by the %filtered hash.
This solution is inefficient in that it reads file1 twice.  Not mentioned in the original question was that FASTQ files typically contain millions of records, so saving all the unfiltered records from file1 in the %filtered hash would require a lot of RAM but if you have a lot of RAM, you could alter to suit, but personally I wouldn't worry about reading the file twice.
# SAVE IDS OF EMPTY RECORDS FROM FILE1 IN HASH
my %filter;
my $fq = new Fastq($file1);
while (my $rec = nextSeq($fq))
{
    $rec->{seq} or $filter{$rec->{id}} = undef; # not using value
}

# ADD IDS OF EMPTY RECORDS FROM FILE2 TO HASH AND OUTPUT FILTERED_FILE2
open(my $out, '>', "$file2.filtered") or die($!);
$fq = new Fastq($file2);
while (my $rec = nextSeq($fq) )
{
    if ( $rec->{seq} )
    {
        # READ2 FOR THIS PAIR IS NOT EMPTY
        if ( ! exists($filter{$rec->{id}}) )
        {
             # READ1 FOR THIS PAIR IS ALSO NOT EMPTY
             print $out join("\n", $rec->{hdr}, $rec->{seq}, '+', $rec->{qual}), "\n";
        }
    } else
    {
         # READ2 IS EMPTY, ADD TO FILTERED HASH
         $filtered{$rec->{id}} = undef;
    }
}
close($out);

# OUTPUT FILTERED_FILE1
open($out, '>', "$file1.filtered") or die($!);
$fq = new Fastq($file1);
while (my $rec = nextSeq($fq) )
{
    if ( $rec->{seq} and ! exists($filter{$rec->{id}}) )
    {
         print $out join("\n", $rec->{hdr}, $rec->{seq}, '+', $rec->{qual}), "\n";
    }
}
close($out);


text:
Q: select multiple files in django with single  filefield How can I select multiple files in a single fileField in django? I want to select different file formats  in a single filefiled in django admin.
**models.py**
 class FileModel(models.Model):
    name = models.CharField(max_length=100)
    file_upload = models.FileField(upload_to=settings=PATH)

**admin.py**
 admin.site.register(FileModel,FileAdmin);

In the admin I want to customize the file field to select multiple files to store in given path? Could you please help me?

A: You can't? The FileField was not designed for that purpose.
You would have to define your own field (possibly extended from FileField) that pickles the internal data (paths to multiple files) and stores them in the database and unpickles them back.
Of course, I don't see a reason to do this at all, when you can simply define one to many relationship or even many to many relationship between a new filelist model and existing filemodel. Then you could make an inline admin handler attached to the uploader model and you can add multiple files easily that way.
See inline admin models for details.

A: In newer versions of Django, this is now possible.
See the documentation at https://docs.djangoproject.com/en/3.2/topics/http/file-uploads/#uploading-multiple-files

A: I know this is old, but it comes up at the top of Google search so I thought I'd comment. You can use django-multiupload to do this.
# forms.py
from django import forms
from multiupload.fields import MultiFileField

class UploadForm(forms.Form):
     attachments = MultiFileField(min_num=1, max_num=3, max_file_size=1024*1024*5)

Hope that helps.


text:
Q: requiring a file within a method I was looking at the contents of the Ransack ruby gem. Basically, it calls a method called require_constants. And that method itself requires a file:
# ransack.rb
require 'ransack/adapters'
Ransack::Adapters.object_mapper.require_constants

# adapters.rb
module Ransack
  module Adapters

    def self.object_mapper
      @object_mapper ||= instantiate_object_mapper
    end

    def self.instantiate_object_mapper
      if defined?(::ActiveRecord::Base)
        ActiveRecordAdapter.new
      elsif defined?(::Mongoid)
        MongoidAdapter.new
      end
    end

    class ActiveRecordAdapter
      def require_constants
        require 'ransack/adapters/active_record/ransack/constants'
      end
      ...

# constants.rb
module Ransack
  module Constants

The first require copies the content of adapters.rb in ransack.rb, I believe. Hence, we can then reference Ransack::Adapters without an undefined error.
However, when we call require_constants, it appears to copy the contents of Ransack::Constants into the method definition of require_constants.
I find that kind of confusing. We are copying a module inside of a method. What benefit do we get of copying a module inside of a method, rather than just doing it like the other require? Second, I know the module is not a local variable, but I couldn't even define a module in the console when I tried it:
class A
  def a
    module B end
  end
end
SyntaxError: (irb):14: module definition in method body

So what is require doing that does not cause the syntax error?

A: "Copy" is the wrong word here. require does not copy anything. It reads the source code in the given file and executes that code in Ruby's global ("main") context (unless the file has already been required; then it does nothing and returns false). To quote the docs (emphasis mine):

Any constants or globals within the loaded source file will be available in the calling program's global namespace.

require does not behave differently inside a method call, or inside a module, or anywhere else, than it does at the top of a file.
When you see require inside a method call the reason is usually that the module is only needed in a particular scenario, and loading it before that scenario occurs would be wasteful (because, for example, the module takes a long time to load or accesses, during loading, resources that are only available in that scenario—think different database drivers or OSes). It does not mean that the module is being loaded "into" the method or the surrounding code, because that's not what require does.
To demonstrate, suppose we have a module like this:
# baby_module.rb
module BabyModule
  NAME = "Baby"
end

And suppose we run the following program:
module TheCorner
  def self.load_baby_module
    require File.expand_path("baby_module", __dir__)
  end
end

TheCorner.load_baby_module

if defined?(TheCorner::BabyModule)
  puts "#{TheCorner::BabyModule::NAME} is in TheCorner"
elsif defined?(BabyModule)
  puts "Nobody puts #{BabyModule::NAME} in TheCorner"
end

As you have perhaps already guessed, this program's output will be:

Nobody puts Baby in TheCorner

A:
So what is require doing that does not cause the syntax error?

Simple: it runs the file.


text:
Q: Bash: How to check if dynamic env variable is set? I'm writing a script where I want to dynamically create an environment variable name, and check if it has been set.
#!/bin/bash

#######################################
# Builds options string
# Globals:
#   JVM_OPTS_DIR
# Arguments:
#   1. Options env variable name
#   2. File containing options defaults
# Returns:
#   Options
#######################################
function buildOpts() {
  declare -n opts=$1
  declare -n excludeOpts="EXCLUDE_$1"
  local -r optsFile=$2
  local x=
  if [ -z ${excludeOpts+x} ]; then
    while read -r o; do
      if [ -n "${o// }" ]; then
        x+=" $o"
      fi
    done <"$JVM_OPTS_DIR/$optsFile"
  fi
  if [ -n "$opts" ]; then
    for o in $opts; do
      x+=" $o"
    done
  fi
  printf '%s' "$x"
}

# https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html

# Standard options
stdOpts=$(buildOpts STD_OPTS std.opts)

...

javaCmd="java $stdOpts $nonStdOpts $advRtOpts $advCompOpts $advServOpts $advGcOpts -jar $APP_DIR/app.jar"

printf '%s' "$javaCmd"

# eval $javaCmd "$@"

The above script serves as a Docker entrypoint
docker build -t jdk . && docker run --rm -it jdk -e APP_NAME=test -e APP_LOG_DIR=test -e APP_DIR=test -e STD_OPTS='a b' -e EXCLUDE_STD_OPTS=true

However, I don't see a and b included in the javaCmd, neither do I see the EXCLUDE working. Basically, none of the if conditions in function buildOpts are working.
I'm a backend programmer, and not a Bash wizard. Help.

A: You need to put the envs flags before the image name.
Syntax of docker run is:
docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]

Anything after the image name will be treated as [COMMAND][ARG...]


text:
Q: java.lang.IndexOutOfBoundsException: Invalid index 2, size is 2 in Arraylist? I have a listener, when i click on the dates it will search for the arraylist and get the dates of what i click then when i change the month i will removed the dates then add the dates in my current month.
public void onSelectDate(Date date, View view) {
    JSONObject jsonObj = new JSONObject(jsonStr);
    JsonArray datesIn = jsonObj.getJSONArray(TAG_SCHEDULE);
    for (int i = 0; i < datesIn.length(); i++) {
        JSONObject c = datesIn.getJSONObject(i);
        String dateD = c.getString(TAG_DATED);
        String statusD = c.getString(TAG_STATUS);
        HashMap<String, String> contact = new HashMap<String, String>();
        contact.put("Tag_dated", dateD);
        contact.put("Tag_status", statusD);
        contactList.add(contact);
        Date s = formatter.parse(dateD);

        ArrayList<HashMap<String, String>> contactList= new ArrayList<HashMap<String,String>>();;
        if(formatter.format(date).equals(contactList.get(0).get(TAG_DATED))){
            if(contactList.get(0).get(TAG_STATUS).equals("Occupied")){
                Toast.makeText(getApplicationContext(),"S",Toast.LENGTH_SHORT).show();
            }else if(contactList.get(0).get(TAG_STATUS).equals("Reserved"))
                Toast.makeText(getApplicationContext(),"R",Toast.LENGTH_SHORT).show();
        }else if(formatter.format(date).equals(contactList.get(1).get(TAG_DATED))){
            if(contactList.get(1).get(TAG_STATUS).equals("Occupied")){
                Toast.makeText(getApplicationContext(),"S",Toast.LENGTH_SHORT).show();
            }else if(contactList.get(1).get(TAG_STATUS).equals("Reserved")){
                Toast.makeText(getApplicationContext(),"R",Toast.LENGTH_SHORT).show();
            }
        }else if(formatter.format(date).equals(contactList.get(2).get(TAG_DATED))){
            if(contactList.get(2).get(TAG_STATUS).equals("Occupied")){
                Toast.makeText(getApplicationContext(),"S",Toast.LENGTH_SHORT).show();
            }else if(contactList.get(2).get(TAG_STATUS).equals("Reserved")){
                Toast.makeText(getApplicationContext(),"R",Toast.LENGTH_SHORT).show();
            }
        }else if(formatter.format(date).equals(contactList.get(3).get(TAG_DATED))){
            if(contactList.get(3).get(TAG_STATUS).equals("Occupied")){
                Toast.makeText(getApplicationContext(),"S",Toast.LENGTH_SHORT).show();
            }else if(contactList.get(3).get(TAG_STATUS).equals("Reserved")){
                Toast.makeText(getApplicationContext(),"R",Toast.LENGTH_SHORT).show();
            }
        }else if(formatter.format(date).equals(contactList.get(4).get(TAG_DATED))){
            if(contactList.get(4).get(TAG_STATUS).equals("Occupied")){
                Toast.makeText(getApplicationContext(),"S",Toast.LENGTH_SHORT).show();
            }else if(contactList.get(4).get(TAG_STATUS).equals("Reserved")){
                Toast.makeText(getApplicationContext(),"R",Toast.LENGTH_SHORT).show();
            }
        }else if(formatter.format(date).equals(contactList.get(5).get(TAG_DATED))){
            if(contactList.get(5).get(TAG_STATUS).equals("Occupied")){
                Toast.makeText(getApplicationContext(),"S",Toast.LENGTH_SHORT).show();
            }else if(contactList.get(5).get(TAG_STATUS).equals("Reserved")){
                Toast.makeText(getApplicationContext(),"R",Toast.LENGTH_SHORT).show();
            }
        }else{
            Toast.makeText(getApplicationContext(),"NP",Toast.LENGTH_SHORT).show();
        }
    }

my problem is when i change the  month then click for the dates it has error.
public void onChangeMonth(int month, int year) {
    contactList.clear();
    HashMap<String, String> contact = new HashMap<String, String>();
    contact.put("Tag_dated", dateD);
    contact.put("Tag_status", statusD);
    contactList.add(contact);
}

Logcat error:
http://i.stack.imgur.com/Is35y.png

A: You're creating a new ArrayList called contactList, and adding one element to it; then you're trying to retrieve several elements from it!

A: Error is strait forward, size is two. Index starts at 0, so indexes available are 0 and 1 not 1 and 2.
Your loop may need size - 1.
Instead of hardcoding your statements such as :
if(formatter.format(date).equals(contactList.get(0).get(TAG_DATED))){
Try doing it in a loop where you go
public void updateToast(Date date, ArrayList<HashMap<String, String>> contactList) {
    String formattedDate = formatter.format(date);
    for (int i = 0; i < contactList.size(); i++)
    {
        if (formattedDate.equals(contactList.get(i).get(TAG_DATED)))
        {
           if(contactList.get(i).get(TAG_STATUS).equals("Occupied"))
           {
              Toast.makeText(getApplicationContext(),"S",Toast.LENGTH_SHORT).show();
              return;
           } else if(contactList.get(i).get(TAG_STATUS).equals("Reserved"))
           {
              Toast.makeText(getApplicationContext(),"R",Toast.LENGTH_SHORT).show();
              return;
           }
        }
    }
    // If here then its not found in any lists throw up your other text.
    Toast.makeText(getApplicationContext(),"NP",Toast.LENGTH_SHORT).show();
}

Some of this may be a bit out as its done free hand in here.

A: In your code onSelectDate you are saying:
contactList.add(contact);

It will add Hashmap into your list just once, so you could use contactList.get(0) on your Arraylist. But going  forward you are saying
contactList.get(1);//even two

So it doesn't have element beyond first and hence it throws exception.

A: lets refactor your code little bit, lets get rid of this ugly nasty and unsafe if/else horror, and change it to nice and lovely loop
    boolean found = false;
    String formattedDate = formatter.format(date);
    for (int i = 0; i < contactList.size(); i++) {
        if (formattedDate.equals(contactList.get(i).get(TAG_DATED))) {
            if (contactList.get(i).get(TAG_STATUS).equals("Occupied")) {
                Toast.makeText(getApplicationContext(), "S",
                        Toast.LENGTH_SHORT).show();
            } else if (contactList.get(1).get(TAG_STATUS)
                    .equals("Reserved")) {
                Toast.makeText(getApplicationContext(), "R",
                        Toast.LENGTH_SHORT).show();
            }
            found = true;
            break;
        }
    }
    if (!found) {
        Toast.makeText(getApplicationContext(), "NP",
                Toast.LENGTH_SHORT).show();
    }

this code should do exactly same thing as yours but it shouldnt give you ArrayIndexOutOfBoundsException exception


text:
Q: Every irreducible recurrent Markov chain has a positive recurrent state? I know the statement in the title is only true for finite-state Marove chains: if the chain has infinitely many states, all states can be null recurrent, e.g., one-dimensional symmetric random walks. However, I don't see where the proof goes wrong with countably many states. Can you help me point it out?
Let us suppose the Markov chain is irreducible and recurrent with state space $S$, which can be either finite or countably infinite. According to (6.6.1) in Durrett's textbook, for any $x,y \in S$, we have
$$
\frac{1}{n}\sum_{m=1}^{n}p^{m}(x,y) \overset{n\to \infty}{\longrightarrow} \frac{1}{\mathbb{E}_{y}[T_y]}, \tag{1}\label{1}
$$
where $p^m(x,y)$ is the $m$-step transition probability and $T_y$ is the time of the first return to state $y$.
Suppose all states are null recurrent, i.e., $\mathbb{E}_{y}[T_y] = \infty$ for all $y \in S$. Sum over $y \in S$ on both sides of (\ref{1}).
On the left-hand side, we have for any $n$,
$$
\sum_{y\in S}\frac{1}{n}\sum_{m=1}^{n}p^{m}(x,y) = \frac{1}{n}\sum_{m=1}^{n}\sum_{y\in S}p^{m}(x,y) = 1.
$$
On the right-hand side, we have
$$\sum_{y\in S} \frac{1}{\mathbb{E}_{y}[T_y]} = \sum_{y\in S} 0 = 0.$$
Thus above implies that $1 \to 0$, which is impossible. Thus we must have a positive recurrent state.
I was wondering what is wrong with the above statement?

A: First of all, 6.6.1 in Durrett says
$$\frac{1}{n}\sum_{m=1}^n p^m(x,y) \to \frac{1}{E_yT_y} 1_{\{T_y<\infty\}}.$$
Second of all, the sum over $y$ does not necessarily commute with the limit if there are infinitely many $y$'s. The essence of this statement is that for each $y$ and each $n$, we have some value $a_n(y)$, and $a_n(y) $ converges to some $a(y)$ as $n \to \infty$. You want to conclude that
$$\sum_{ y} a_n(y) \to \sum_{y} a(y)$$
but this is not necessarily the case.
For instance, suppose that the $y$'s take on values in $\mathbb{N}$ and $a_n(y) = \frac{1}{n+y}$. Then $a_n(y) \to 0$ for each $y$, but for any fixed value of $n$ we have
$$\sum_y a_n(y) = \frac{1}{n+1}+\frac{1}{n+2}+\frac{1}{n+3}+\cdots = \infty.$$


text:
Q: Raid controller not claimed after CentOS 8 upgrade I had a CentOS 7 installed on a machine, and MegaRaid storcli64 was able to detect the controller and disks. At that time, lshw shown:
*-raid
    description: RAID bus controller
    product: MegaRAID SAS 2108 [Liberator]
    vendor: Broadcom / LSI
    physical id: 0
    bus info: pci@0000:01:00.0
    version: 05
    width: 64 bits
    clock: 33MHz
    capabilities: raid pm pciexpress vpd msi msix bus_master cap_list rom
    configuration: driver=megaraid_sas latency=0
    resources: irq:24 ioport:e000(size=256) memory:fb360000-fb363fff memory:fb300000-fb33ffff memory:fb340000-fb35ffff

After upgrading to CentOS 8, storcli64 no longer is able to detect the controller. Now, lshw shows:
*-raid UNCLAIMED
    description: RAID bus controller
    product: MegaRAID SAS 2108 [Liberator]
    vendor: LSI Logic / Symbios Logic
    physical id: 0
    bus info: pci@0000:01:00.0
    version: 05
    width: 64 bits
    clock: 33MHz
    capabilities: raid pm pciexpress vpd msi msix bus_master cap_list
    configuration: latency=0
    resources: ioport:e000(size=256) memory:fb360000-fb363fff memory:fb300000-fb33ffff memory:fb340000-fb35ffff

Note the UNCLAIMED, and note the lack of a driver. Nevertheless:
$ lsmod|grep sas
megaraid_sas          155648  0

Any hint on what might be going on?
NOTE: noted this in dmesg: '[    3.208471] Warning: megaraid_sas 0000:01:00.0 [1000:0079] - Support for this device has been removed in this major release. Please check the removed functionality section of the release notes.' It seems I need to go back to CentOS 7.

A: It looks like support for this specific hardware was removed. I found this post, where the community is requesting for the driver to be readded, as it is still widely used.
While no official answer is presented, some user RPMs for the kernel with support for this hardware is available at that same URL. After installing them raid is back.


text:
Q: What's the purpose of this gen_server.erl code? unregister_name({local,Name}) ->
    _ = (catch unregister(Name));
unregister_name({global,Name}) ->
    _ = global:unregister_name(Name);
unregister_name({via, Mod, Name}) ->
    _ = Mod:unregister_name(Name);
unregister_name(Pid) when is_pid(Pid) ->
    Pid.

This is from gen_server.erl. If _ always matches and the match always evaluates to the right hand side expression, what are the _ = expression() lines doing here?

A: Typically _ = ... matches are used to quiet dialyzer warnings about unmatched function return values when its -Wunmatched_returns option is used. As the documentation explains:
-Wunmatched_returns
    Include warnings for function calls which ignore a structured return value or
    do not match against one of many possible return value(s).

By explicitly matching the return value against the _ "don't care" variable, you can use this useful dialyzer option without having to see warnings for return values you don't care about.

A: In Erlang, last expression of function is its return value, so someone might be tempted to check, what global:unregister_name/1 or Mod:unregister_name(Name) return and try to pattern match on that.
The _ = expression() doesn't do anything in particular, but hints, that this return value should be ignored (for example, because they are not documented and might be subject to change). However in the last expression, Pid is returned explicitly. This means, that you can pattern match like this:
case unregister_name(Something) of
    Pid when is_pid(Pid) -> foo();
    _ -> bar()
end.

To sum up: those lines aren't doing anything there, but when someone else is reading the source code, they show original programmer intent.
Unfortunately, this particular function is not exported and in the original module never used in pattern match, so I don't have an example to back this up :)

A: And I'll note that I've since come across this:

The Power of Ten – Rules for Developing Safety Critical Code
Gerard J. Holzmann
NASA/JPL Laboratory for Reliable Software Pasadena, CA
91109
[...]

*Rule: The return value of non-void functions must be checked by each calling function, and the validity of parameters must be checked
  inside each function.
Rationale: This is possibly the most frequently
  violated rule, and therefore somewhat more suspect as a general rule.
  In its strictest form, this rule means that even the return value of
  printf statements and file close statements must be checked. One can
  make a case, though, that if the response to an error would rightfully
  be no different than the response to success, there is little point in
  explicitly checking a return value. This is often the case with calls
  to printf and close. In cases like these, it can be acceptable to
  explicitly cast the function return value to (void) – thereby
  indicating that the programmer explicitly and not accidentally decides
  to ignore a return value. In more dubious cases, a comment should be
  present to explain why a return value is irrelevant. In most cases,
  though, the return value of a function should not be ignored,
  especially if error return values must be propagated up the function
  call chain. Standard libraries famously violate this rule with
  potentially grave consequences. See, for instance, what happens if you
  accidentally execute strlen(0), or strcat(s1, s2, -1) with the
  standard C string library – it is not pretty. By keeping the general
  rule, we make sure that exceptions must be justified, with mechanical
  checkers flagging violations. Often, it will be easier to comply with
  the rule than to explain why noncompliance might be acceptable.


text:
Q: inner join to find number of items in the same revision number I have the following tables
tblMainequipment
asset_id   rev    equipment_name
123        0      box
123        1      box
124        0      box
125        0      bottle

tblmainswablocation
asset_id   rev   swab_location
123        0     cover
123        0     base
123        1     cover
123        1     base
123        1     lock
124        0     cover
124        0     base
125        0     tube
125        0     cover

I did like to get the total count of swablocations for the maximum rev for a particular asset_id. For example, the total number of swab location for asset_id 123 rev 0 is 2 but for rev 1 its 3.  I have been trying to figure out for the past few hours but cant seem to find a solution. I am pretty bad with joins. The following shows the what i am trying to get,
query
asset_id   maxrev    #swablocation  equipment_name
123        1         3              box
124        0         2              cover
125        0         2              bottle

I use the following sql
SELECT MEQ.*
FROM tblMainEquipment AS MEQ
INNER JOIN (Select asset_id, max(rev) as maxrev
            From tblmainequipment  GROUP By asset_id)  AS groupmeq ON
            (MEQ.asset_id = groupmeq.asset_id) AND (MEQ.rev = groupmeq.maxrev)

I am not sure how i can add the #swablocation into my query.

A: You need a count and a group by
SELECT MEQ.asset_id maxrev, MEQ.maxrev,
    count(blmainswablocations.swab_location), MEQ.equipment_name
FROM tblMainEquipment AS MEQ
INNER JOIN (Select asset_id, max(rev) as maxrev
        From tblmainequipment  GROUP By asset_id)  AS groupmeq ON
        (MEQ.asset_id = groupmeq.asset_id) AND (MEQ.rev = groupmeq.maxrev)
Inner join blmainswablocations on MEQ.asset_id =  blmainswablocations.asset_id
Group by MEQ.asset_id maxrev

A: Here is a method that uses correlated subqueries:
select me.*,
       (select count(*)
        from tblmainswablocation as sl
        where sl.asset_id = me.asset_id
       ) as numSwabs
from tblMainEquipment as me
where me.rev = (select max(me2.rev) from tblMainEquipment as me2 where me2.asset_id = me.asset_id);

The advantage is that the outer query does not require aggregation.


text:
Q: How to update a value in a Cache withour removal? I want to update a value in a non-loading cache:
Cache<String, Session> cache = CacheBuilder.newBuilder().expireAfterAccess( 30l, TimeUnit.MINUTES ).removalListener( removalListener ).build()

cache.put id, s

or
cache.asMap().put id, s

in both cases the removalListener get's called and this is what I want to avoid.
How can I do that?

A: It's not possible to prevent a RemovalListener from being called when you replace an element. As the documentation says (emphasis added):

The removal resulting in notification could have occured to an entry being manually removed or replaced, or due to eviction resulting from timed expiration, exceeding a maximum size, or garbage collection.

However, you can examine the cause field of the RemovalNotification object. If the cause is REPLACED, then the entry was removed as a result of a call to put, replace or refresh.


text:
Q: How to check all roles/user/group_role have what privileges in postgres database? I have postgres database.
I want the list of users with access privileges they are being assigned.
I tried to find query and also looked in to psql command line help. (\nu and all) but I haven't found any usefull information.
Is anyone knows about that can help me out.
Thanks.

A: There are few basic command like \du and \l that will provide the general information.
For getting the detailed information you may use the below function.
CREATE OR REPLACE FUNCTION database_privs(text) RETURNS table(username text,dbname name,privileges  text[])
AS
$$
SELECT $1, datname, array(select privs from unnest(ARRAY[
( CASE WHEN has_database_privilege($1,c.oid,'CONNECT') THEN 'CONNECT' ELSE NULL END),
(CASE WHEN has_database_privilege($1,c.oid,'CREATE') THEN 'CREATE' ELSE NULL END),
(CASE WHEN has_database_privilege($1,c.oid,'TEMPORARY') THEN 'TEMPORARY' ELSE NULL END),
(CASE WHEN has_database_privilege($1,c.oid,'TEMP') THEN 'CONNECT' ELSE NULL END)])foo(privs) WHERE privs IS NOT NULL) FROM pg_database c WHERE
has_database_privilege($1,c.oid,'CONNECT,CREATE,TEMPORARY,TEMP') AND datname not in ('template0');
$$ language sql;

and then call the same function by providing the username/role that you get from \du
postgres=# \du
                                   List of roles
 Role name |                         Attributes                         | Member of
-----------+------------------------------------------------------------+-----------
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 test      |                                                            | {}
 test2     |                                                            | {}
 test3     |                                                            | {}

postgres=# select * from database_privs('test');
 username |  dbname   |         privileges
----------+-----------+-----------------------------
 test     | postgres  | {CONNECT,TEMPORARY,CONNECT}
 test     | template1 | {CONNECT}
 test     | test      | {CONNECT,TEMPORARY,CONNECT}
(3 rows)

A: Here as a supplement to the previous.
To check the privileges of user by following:
SELECT * FROM pg_user;

As the same way, to check roles:
SELECT * FROM pg_roles;


text:
Q: Ошибка Cannot implicitly convert type 'string' to 'double' private void button1_Click(object sender, EventArgs e)
    {
        double x = (double.Parse(textBox1.Text));
        double a = x / 1000;
        double b = x / 100 % 10;
        double c = x / 10 % 10;
        double d = x % 10;

        x = (a + b == c + d) ?label1.Text = "Сумма двух первых чисeл = сумме двух последних": label1.Text = "Сумма двух первых чисел не равна сумме двух последних";

    }

A: Проблема в неверном использовании тернарного оператора.
Тернарный оператор (condition)? result1: result2 возвращает значение, в данном случае - возвращаемое значение имеет тип "string". Это значение присваивается переменной x, которая имеет тип double, отсюда и возникает ошибка указанная в вопросе.
Для решения достаточно заменить тернарный оператор на if
if (a + b == c + d)
    label1.Text = "Сумма двух первых чисел = сумме двух последних";
else
    label1.Text = "Сумма двух первых чисел не равна сумме двух последних";

либо присваивать результат непосредственно в label:
label1.Text = (a + b == c + d) ? "Сумма двух первых чисел = сумме двух последних" : "Сумма двух первых чисел не равна сумме двух последних";


text:
Q: How to use geom_signif from ggpubr with a chi-square test I am trying to use geom_signif(), from the package ggpubr. I am attempting to use it to do a Chisq test on my data (here is a sample) :
df_test= data.frame(cat = c("A","D","R"), count1 = c(10,12,23),count2 = c(9,3,4))

I am trying to see if there are some categories that are statistically enriched in certain categories in count2, which is a subset of count1.
I've not seen an example online of geom_signif being used for another test than the wilcoxon, so I don't know the correct syntax to tell it what my variables are.
here is the one I attempted :
melt_count = data.table::melt(df_test, id.vars = "cat")
ggplot(melt_count, aes( x =cat,fill=variable,  y=value))+geom_bar(stat = "identity", position = "dodge")+
  geom_signif(comparisons = list(c("A","D"),c("count1","count2")), test = "chisq.test")

Warning :
Computation failed in stat_signif():
missing value where TRUE / FALSE is required

I know this mostly doable by doing the test outside of ggpubr but I specifically want to use it, or another ggplot-affiliated package able to do statistical test by itself.

A: The problem is that the test argument requires a function that takes two vectors to compare, whereas chisq.test takes a single matrix. We could therefore create a little wrapper function:
chi.test <- function(a, b) {
  return(chisq.test(cbind(a, b)))
}

ggplot(melt_count, aes( x =cat,y=value))+
  geom_bar(aes(fill=variable), stat = "identity", position = "dodge")+
  geom_signif(comparisons = list(c("A","D")),
              test = "chi.test")

Created on 2022-06-14 by the reprex package (v2.0.1)


text:
Q: scrollTo doesn't work when it is behind a view with alpha I can't make scrollTo to work when the EditText is behind a LinearLayout with alpha background.
I wanted to avoid uiautomator cause I think it doesn't work sometimes
<RelativeLayout ...>
<ScrollView>
 <LinearLayout>
   <EditText />
   <EditText />
   <EditText />
   <EditText />
   ....
   <EditText android:id="@+id/name" />
 </LinearLayout>
</ScrollView>

<LinearLayout
            android:id="@+id/button_group"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp"
            android:layout_alignParentBottom="true"
            android:background="@color/white80">

</RelativeLayout>

onView(withId(R.id.name)).perform(scrollTo(), typeText(name), closeSoftKeyboard());

It says that it can't find the id name. It works fine if the screen is big but if it's small and the edittext name is behind the button_group which has an alpha backgroound, it always fail.

A: Maybe you could alter the button_group visibility with a custom ViewAction before performing the scroll.
Firstly, you need the custom ViewAction that performs the change in the visibility:
private static ViewAction setViewVisibitity(final boolean value) {
    return new ViewAction() {
        @Override
        public Matcher<View> getConstraints() {
            return null;
        }

        @Override
        public String getDescription() {
            return "Show / Hide View";
        }

        @Override
        public void perform(UiController uiController, View view) {
            view.setVisibility(value ? View.VISIBLE : View.GONE);
        }
    };
}

And then:
onView(withId(R.id.button_group)).perform(setViewVisibitity(false));

onView(withId(R.id.name)).perform(scrollTo(), typeText(name), closeSoftKeyboard());

And later on you can restore the button_group visibility whenever you want:
onView(withId(R.id.button_group)).perform(setViewVisibitity(true));

Give it a try. As the button_group will have its visibility set to GONE it should not interfere with the scroll.


text:
Q: Can I install php-ldap 5.3.3 when my php version is 5.4.31? I have php 5.4.31 installed on a Centos 6 machine.
When I use
yum install php-ldap
The information yum provides me after I run the command is in the picture.

So yum asks whether I want to install php-ldap version 5.3.3-49 and php-common version 5.3.3-49. Can I let yum install these suggested packages?
My server has php version  5.4.31 and I want to keep it like that for now.


text:
Q: Strange border with gradient around submit button. How do I remove? I have this weird problem, which I can't seem to get around and I'm not sure why it is here.
I am trying to style my form button and upon styling I have this weird outline that I didn't code in
http://imgur.com/QpCPRju
Here is the code:
button {
  background: #3e779d;
  padding: 12.5px 25px;
  -webkit-border-radius: 40px;
  -moz-border-radius: 40px;
  border-radius: 40px;
  color: white;
  font-size: 18px;
  text-decoration: none;
  vertical-align: middle
}
button:hover {
  background: #28597a;
  color: #ffffff;
}

Can anyone shed some light into why this is happening please.
Thank you
HUGE EDIT: Thank you to all. I was missing a semi colon so the code wasn't running for me. All the answers below are correct (its a sign you shouldn't spend so long in front of the screen)

A: You need to set the border:none; in your button.
button {
  background: #3e779d;
  padding: 12.5px 25px;
  -webkit-border-radius: 40px;
  -moz-border-radius: 40px;
  border-radius: 40px;
  color: white;
  font-size: 18px;
  text-decoration: none;
  border:none;
  vertical-align: middle
}

JSFIDDLE DEMO

A: That's the default button border. You can remove it with
button
{
    border: none;
}

Demo with your CSS: http://jsfiddle.net/c76mkcaq/

A: The border is likely coming from the default style of the browser. If you're not using a reset like normalize.css (which you should), you can use the following to reset it:
button {
  border: 0 none;
  outline: 0 none;
}

If that doesn't solve it, you can use something like Chrome Developer Tools to find out where the style is coming from. Just right click the button and choose inspect element. You can then see all CSS selectors applied to the right in the developer tools pane.

A: The trouble isn't that you didn't code this boder in, it's that you didn't code it OUT. Browsers have a default set of styles and that's what you're seeing. The default here looks like it's border: 3px outset #ccc but you don't want that.
Just add border: none; so your final code looks like this:

button {
  background: #3e779d;
  padding: 12.5px 25px;
  -webkit-border-radius: 40px;
  -moz-border-radius: 40px;
  border-radius: 40px;
  color: white;
  font-size: 18px;
  text-decoration: none;
  vertical-align: middle;
  border: none;
}
button:hover {
  background: #28597a;
  color: #ffffff;
}
<button>Submit</button>

A: If you want to take no chances, and destroy every chance of a border; Updated for clarity, your welcome guys. (taking all situations into consideration)
button {
  border: none; // traditional fix
  border: 0px !important; // if you got something weird goin on
  outline: 0px; // if you got something really weird goin on
}

and:
button:hover, button:active, button:focus {
  /* styling for any way a link is about to be used */
      border: none; // traditional fix
      border: 0px !important; // if you got something weird goin on
      outline: 0px; // if you got something really weird goin on
}

A: When you can delete border gradient from button you can set border style to solid.
   border-style: solid;


text:
Q: Can a private store support the Android App Bundle format? My app is both on Google play store and on company's private store.
Sadly after importing a new library (40 mb of aar extension) the apk's size is grown over 100mb, also with shrink and minify enabled.
I thought to use apk expansion, but I have read that is only for resource and not for executable code. I suppose only way is Android App Bundle, but the question is:
Is there a way to use aab format on private store ?
What do you suggest ?

A: I don't know of other stores supporting the AAB today, however this shouldn't prevent you from using AAB since you can generate a universal APK using bundletool which you can publish on other stores. You will soon be able to download this universal APK straight from the Play Console as well for convenience.


text:
Q: Pass variable id into Modal I have used this code to load a list of IDs in a foreach loop into a modal. I am have an issue where only the first ID is being populated rather than the ID for the clicked element. What is the correct var to set on appointment ID so that it loads the related id.
$('#appointmentModal').on('show.bs.modal', function(e) {
        //get data-id attribute of the clicked element
        var appointmentID = ($('[data-id]').val());
        //populate the textbox
        $(e.currentTarget).find('input[name="appointmentID"]').val(appointmentID);
        });

Button
<button type="button" class="btn btn-sm btn-teal " data-toggle="modal" data-target="#appointmentModal" data-appointment="{{ $item->appointmentID }}" data-id="{{ $item->appointmentID }}" id="appointmentID" value="{{ $item->appointmentID }}">
            <i class="fa fa-edit"></i> {{ trans('translate.edit') }}
            </button>

A: Suggestion:
I would suggest to get the value of your DOM element click like this:
$(document).ready(function() {
    $('.btn-teal').click(function() {
        // 1) Use .attr() method to get the given value based on what [attribute] (e.g data-id)
        // This will get the appointment value of the element click
        var appointmentID = $(this).attr('data-id');

        // 2) Then by the time you open the modal, You can assign it
        // on another DOM element
        $('#appointmentModal').find('input[name="appointmentID"]').val(appointmentID);

        // 3) After assigning it, Open that modal box
        $('#appointmentModal').modal('show');
    });
});

Hope this helps for your case


text:
Q: How to validate text in Extjs6 ? and where to add the code? I was following tutorial in Extjs , i had this view (YourTurn.js)
Ext.define('Student.view.main.YourTurn', {
  extend: 'Ext.window.Window',
  xtype: 'mainyour',

  requires: [
    'Student.view.main.YourTurnController',
    'Ext.form.Panel'
  ],

  autoShow: true,
  height: 170,
  width: 360,
  layout: {
    type: 'fit'
  },
  iconCls: 'key',
  title: "Login",
  closeAction: 'hide',
  closable: false,
  items: [{
    xtype: 'form',
    frame: false,
    bodyPadding: 15,
    defaults: {
      xtype: 'textfield',
      anchor: '100%',
      labelWidth: 60
    },
    items: [{
      name: 'user',
      fieldLabel: "User",
      allowBlank:false,
      vtype:'alphanum',
      minLenght:3,
      msgTarget:'under',

    }, {
      inputType: 'password',
      name: 'password',
      fieldLabel: "Password",
      maxLength:15,
      allowBlank:false,
      vtype:'alphanum',
      minLenght:3,
      msgTarget:'under',

    }]
  }]

});

and I had the controller of this view (YourTurnController.JS) like this :
Ext.define('Student.view.main.YourTurnController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.yourturncontroller',

    Ext.apply(Ext.form.field.VTypes, {
        customPass: function(val, field) {
            return /^((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})/.
            test(val);
        },
        customPassText: 'Not a valid password.  Length must be at least
        6 characters and maximum of 20 Password must contain one digit,
        one
        letter lowercase,
        one letter uppercase,
        onse special symbol @ # $ % and
        between 6 and 20 characters.
        ',
    });

Its should validate that the enter vlaue to the textfield should be between 0-9,with small and capital letter..etc , but it did not working i got this error in brower (chrome) :
YourTurnController.js?_dc=1477341018794:5 Uncaught SyntaxError: Unexpected token .
ext-all-rtl-debug.js?_dc=1477341016439:9126 [E] [Loader] The following classes failed to load:log @ ext-all-rtl-debug.js?_dc=1477341016439:9126logx @ ext-all-rtl-debug.js?_dc=1477341016439:9162Ext.apply.log.log.error @ ext-all-rtl-debug.js?_dc=1477341016439:9165(anonymous function) @ ext-all-rtl-debug.js?_

please can any one help me to understadn what i did wrong ?

A: you should consider using a listener to validate the input type of your password.
Try this link to the doc for the change listener:
http://docs.sencha.com/extjs/6.2.0/classic/Ext.form.field.Text.html#event-change


text:
Q: Querying "highest" RowKey I use a RowKey which is a number (as string).
How can I get the highest number (RowKey) with a query ?
Max operator is not supported. But is there another possibility ?

A: All entries in table are ordered by PartitionKey and then by RowKey. So your highest number should always be the last item (if you are using the same PartitionKey for all entries).
Also you can you can get all data by using .ToList() and then call .Max() method. But this method could be inefficient and slow if you got lots of entries.


text:
Q: How to convert " to double qoutes I have a ruby json object. for example
In controller
@my_hash = {"5":{"id":5,"name":"ANKLOS","code":"724.9","description":"Ankylosis of spine (Spine Fusion)","title":"ANKLOS - 724.9 - Ankylosis of spine (Spine Fusion)"},"3":{"id":3,"name":"Loren Lipsum","code":"Test","description":"Test t2 stest","title":"Loren Lipsum - Test - Test t2 stest"}}

I used @my_hash in view. I content comes dynamically from the table.
<script type="text/javascript">
    var my_hash = <%= @my_hash.to_json %>;
</script>

but the result of the my_hash is like
var diagnosisCodes = {"":{"code":"\u0026larr;","description":""},"5":{"id":5,"name":"ANKLOS","code":"724.9","description":"Ankylosis of spine (Spine Fusion)","title":"ANKLOS - 724.9 - Ankylosis of spine (Spine Fusion)"},"3":{"id":3,"name":"Loren Lipsum","code":"Test","description":"Test t2 stest","title":"Loren Lipsum - Test - Test t2 stest"}};

I need output same like @my_hash. How can I do that?

A: Use
@my_hash.to_json.html_safe

as said on:
Handling JSON in JS/ERB template in Rails 3


text:
Q: Using Amazon MWS Merchant Fulfilment API PHP SDK to buy shipping I am attempting to use the Amazon MWS Merchant Fulfilment API PHP SDK to buy shipping.
https://developer.amazonservices.com/doc/merchantfulfillment/merchantfulfillment/v20150601/php.html/132-2116251-7478560
My code looks something like this, with some personal details changed for privacy:
// Configure
require_once('sdks/Amazon/.config.inc.php');
$serviceUrl = "https://mws.amazonservices.com/MerchantFulfillment/2015-06-01";
$config = array(
'ServiceURL' => $serviceUrl,
'ProxyHost' => null,
'ProxyPort' => -1,
'ProxyUsername' => null,
'ProxyPassword' => null,
'MaxErrorRetry' => 3
);

// Create service
$merchant_service = new Amazon_Merchant_Client(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, APPLICATION_NAME, APPLICATION_VERSION, $config);

// Create request object
$request = new Amazon_Merchant_Model_CreateShipmentRequest();

// Set SellerId
$request->setSellerId(MERCHANT_ID);

// Define shipping info
$package_dimensions = array(
    'Length' => 5,
    'Width' => 5,
    'Height' => 5,
    'Unit' => 'inches',
);
$weight = array(
    'Value' => 5,
    'Unit' => 'ounces',
);
$ship_from_address = array(
    'Name' => '904Custom',
    'AddressLine1' => 'foobar',
    'AddressLine2' => 'foobar',
    'Email' => 'foobar@foobar.com',
    'City' => 'foobar',
    'StateOrProvinceCode' => 'FL',
    'PostalCode' => '12345',
    'CountryCode' => 'US',
    'Phone' => '(888) 555-5555',
);
$shipping_service_options = array(
    'DeliveryExperience' => 'DeliveryConfirmationWithoutSignature',
    'CarrierWillPickUp' => true,
);
$shipping_details_array = array(
    'AmazonOrderId' => '114-1234567-1234567',
    'SellerOrderId' => '114-1234567-1234567',
    'ShipFromAddress' => $ship_from_address,
    'PackageDimensions' => $package_dimensions,
    'Weight' => $weight,
    'ShippingServiceOptions' => $shipping_service_options,
);
$request->setShipmentRequestDetails($shipping_details_array);

// Set shipping service id
$request->setShippingServiceId('1234');

// Invoke request
// invokeCreateShipment is a wrapper for $service->CreateShipment($request);
$result = $this->invokeCreatehipment($merchant_service, $request);

This gives me
Fatal error: Call to a member function _toQueryParameterArray() on a non-object in /var/www/hydra/sdks/Amazon/Merchant/Model.php on line 276
The details may not be correct, but right now I'm only trying to send a request to the API, which the SDK isn't allowing me to do because of the fatal PHP error it's running into. For what it might be worth, I removed $request->setShipmentRequestDetails() to see what result I would get. I did get a response from the API, but it was a InternalFailure XML:
<ErrorResponse xmlns="https://mws.amazonservices.com/MerchantFulfillment/2015-06-01">
    <Error>
        <Type>Receiver</Type>
        InternalFailure
    </Error>
    <RequestId>b1f5a04c-54ac-442c-ab88-f2f1c9374377</RequestId>
</ErrorResponse>

I've read all of the following documentation
I've viewed the sample files included in the SDK, but they aren't complete examples.
I've done exhaustive googling, but can't find any usage of this SDK in the wild.
http://docs.developer.amazonservices.com/en_US/merch_fulfill/MerchFulfill_Overview.html
http://docs.developer.amazonservices.com/en_US/merch_fulfill/MerchFulfill_HowToUseForPrime.html
http://docs.developer.amazonservices.com/en_US/merch_fulfill/MerchFulfill_CreateShipment.html
http://docs.developer.amazonservices.com/en_US/merch_fulfill/MerchFulfill_Datatypes.html#ShipmentRequestDetails
http://docs.developer.amazonservices.com/en_US/merch_fulfill/MerchFulfill_Datatypes.html#ShippingServiceOptions
I've trying var_dump()ing in the source code to try to figure out what's going on, but it's very abstract and difficult to work with. For instance, toQueryParameterArray() calls _toQueryParameterArray() which calls __toQueryParameterArray() which calls both _toQueryParameterArray() and __toQueryParameterArray(). The code is difficult to understand and attempts to code a workaround have fallen flat.
For reference, here is a mirror of the official Amazon MWS Merchant Fulfilment API PHP SDK
https://github.com/AustinMaddox/mws-merchant-fulfillment-php-client-library
I've used the Orders, Feed, and Reports API in dozens of ways for years now, but on the Merchant API, I am stumped and I need some help.
How can I use the Amazon MWS Merchant Fulfilment API PHP SDK to buy shipping?

A: Thanks to Bullcom over on the Amazon forums, I figured it out.
I needed to create objects and use setter and getters, not just pass arrays of data
So my new code looks more like this
    $shipping_details = new Amazon_Merchant_Model_ShipmentRequestDetails();
    $weight = new Amazon_Merchant_Model_Weight();
    $weight->setValue(5);
    $weight->setUnit('ounces');
    $shipping_details->setWeight($weight);

This should definitely be in the sample folder for the SDK, rather than vague the comment that they currently have "// object or array of parameters"


text:
Q: Ng2-NoUISlider getting same range values I'm tring to use multiple sliders on the same page but for some reason all slider gets the same range as the first slider range values. This is my html:

{{property.propertyName}}

                  <nouislider #slider [min]="minSliderValue" [max]="maxSliderValue" [step]="stepSliderValue" [config]="conf" [tooltips]="[true, true]" (end)="onSliderChange($event)"></nouislider>

And my this is my ts file:
conf: any = {
    start: [0, 10],
    behaviour: 'drag'
  };

..
..
  setSliderValues(sliderFilter: FilterList) {
    if (sliderFilter.propertyName === 'enginePower' || sliderFilter.propertyName === 'wheelBase') {
      this.minSliderValue = sliderFilter.propertyValues[0];
      this.maxSliderValue = sliderFilter.propertyValues[sliderFilter.propertyValues.length - 1];
      this.stepSliderValue = 5;
      return true;
    } else {
      return false;
    }

  }

For example the first slider has values between 0-730 and second slider values 2300-12000. But both slider ends up with the range values of 0-730. I even tried to hard code to sliders with different values instead of looping to see if the outcome would be different but I still get the same problem. I'm using Angular 6.

A: Because you set the same min and max values. When setSliderValues() function is called, you set one value to max and min. this.minSliderValue always gets the value from the last *ngFor loop.

{{property.propertyName}}

     <nouislider #slider [min]="property.propertyValues[0]" [max]="property.propertyValues[sliderFilter.propertyValues.length - 1]" [step]="stepSliderValue" [config]="conf" [tooltips]="[true, true]" (end)="onSliderChange($event)"></nouislider>

A: No, that's not it. Even if I hardcode 2 sliders like this it'll give the same problem:
<nouislider #slider [min]="0" [max]="730" [step]="10" [config]="conf" [tooltips]="[true, true]"></nouislider>
<nouislider #slider [min]="2300" [max]="12000" [step]="100" [config]="conf" [tooltips]="[true, true]"></nouislider>

Only the step is working correctly.
I just noticed that the issue is related to me using the same config variable. If I use 2 different configs, with the same values, it works. I'm I missing something?


text:
Q: Machine learning, applying training model to testing Political science grad student who is way over his head (ambitious but rubbish as they say). Basically, I am trying to do an attractiveness prediction on a set of politicians for political science purposes. I followed this guide.
Having extracted landmarks and generated features, I have used my learning set (CFD, 400 images with ratings) for a model predicts ratings that correlate 0.49 (good enough for my purposes) with actual ratings through cross validation. This is that code:
import numpy as np
from sklearn import decomposition
from sklearn import linear_model
features = np.loadtxt('C:\\Users\\bruker\\Desktop\\Data\\CFD_features.txt', delimiter=',')
ratings = np.loadtxt('C:\\Users\\bruker\\Desktop\\Data\\CFD_ratings.txt', delimiter=',')
predictions = np.zeros(ratings.size);

for i in range(0, 400):
    features_train = np.delete(features, i, 0)
    features_test = features[i, :]
    ratings_train = np.delete(ratings, i, 0)
    ratings_test = ratings[i]
    pca = decomposition.PCA(n_components=13)
    pca.fit(features_train)
    features_train = pca.transform(features_train)
    features_test = pca.transform(features_test)
    regr = linear_model.LinearRegression()
    regr.fit(features_train, ratings_train)
    predictions[i] = regr.predict(features_test)
    print 'number of models trained:', i+1

np.savetxt('C:\\Users\\bruker\\Desktop\\Data\\CFDN_cross_valid_predictions.txt', predictions, delimiter=',', fmt = '%.04f')

corr = np.corrcoef(predictions, ratings)[0, 1]
print corr

Now I have a another features.txt with feature data for politicians (142 images), for which I have no ratings. What I am trying to do is use the training set/model constructed by the forgoing code to generate predicted attractiveness ratings for my politicians, but I have absolutely no idea how to proceed. The guide is silent on this, probably because its intended for people who know Python :).  I've spent a lot of hours trying to figure out ways to modify/build this code to make it happen, but my lack of Python/general coding knowledge makes it very hard to figure out.
Given the significant brainpower and knowledge on this site I am hoping someone knows a solution and could help me out. Apologies for my cluelessness, and thanks in advance for any help.

A: Without the for loop, it becomes pretty easy.
import numpy as np
from sklearn import decomposition
from sklearn import linear_model

features_train = np.loadtxt('C:\\Users\\bruker\\Desktop\\Data\\CFD_features.txt', delimiter=',')
ratings_train = np.loadtxt('C:\\Users\\bruker\\Desktop\\Data\\CFD_ratings.txt', delimiter=',')

pca = decomposition.PCA(n_components=13)
pca.fit(features_train)
features_train = pca.transform(features_train)
regr = linear_model.LinearRegression()
regr.fit(features_train, ratings_train)

features_test = np.loadtxt('C:\\Users\\bruker\\Desktop\\Data\\CFD_features_Test.txt', delimiter=',')

features_test = pca.transform(features_test)
predictions = regr.predict(features_test)


text:
Q: Excel -- Comparing dates in different formats I'm trying to run a formula that essentially compares two different date columns to determine if another formula needs to be run but I'm running into trouble because the dates are in different formats. For example, I have column A with dates in DD-MMM-YY format and column B where the dates are in QYY format.
DATE    INCOME_QTR  STATUS
22-Feb-05   1Q18
13-Oct-17   1Q18
29-Apr-08   1Q18
03-Oct-16   1Q18
05-Apr-19   1Q18
02-Mar-15   1Q18
Essentially I want to do an IF statement to determine if the date in column A is greater than or equal to the quarter to determine if the data tied to the first date should be incorporated into the Quarter shown in column B. In simpler terms, only row 6 would be "yes" in this case because the date in column A is greater than the Quarter in column B.
I've been trying to run =IF(TEXT([@[date]],"YYYYMMDD">TEXT([@[income_qtr]],"YYYYMMDD")),"YES","No") but I haven't been successful.
Ideally I'd like to be able to do this without adding any modules or using VBA.
Thanks for your help!

A:
=IF(RIGHT(A1,2)>RIGHT(B1,2),"Yes",IF(RIGHT(A1,2)<RIGHT(B1,2),"No",IF(IF(OR(MID(A1,4,3)="Jan",MID(A1,4,3)="Feb",MID(A1,4,3)="Mar"),1,IF(OR(MID(A1,4,3)="Apr",MID(A1,4,3)="May",MID(A1,4,3)="Jun"),2,IF(OR(MID(A1,4,3)="Jul",MID(A1,4,3)="Aug",MID(A1,4,3)="Sep"),3,4)))>=RIGHT(B1,1),"Yes","No")))

That's the formula for A1 and B1...


text:
Q: Can't change any system settings via Chrome Remote Desktop on Xubuntu I'm connecting to my remote server running Xubuntu. When I log in directly to the box, all is fine - the problem appears when I connect using Chrome Remote Desktop. If I try and do anything important (e.g restart, change networks, install software) through the GUI I get a permissions error. For example trying to enable my OpenVPN connection returns:
VPN Connection Failed
Not authorized to control networking
In terminal, it seems I'm logged in as my usual user. But I can't reboot (can't remember if this normally requires sudo - changing networks certainly doesn't):
foo@bar:~$ reboot
reboot: Need to be root
As soon as I sudo I can do anything through the command line - but this doesn't do me any good for all the stuff in the GUI I'd like to be able to do remotely.
I tried adding my user to netdev, but that didn't solve the problem:
foo@bar:~$ groups
foo adm cdrom sudo dip plugdev netdev lpadmin sambashare chrome-remote-desktop
My theory is that I'm not actually logged in as my user, or that the GUI at least is being triggered by another user that doesn't have proper permissions.

*

*How can I find out what "user" has triggered the xfce session I'm in?

*How can I give that user appropriate permissions? I know it's poor practice to add non-root users to root but I'm tempted ;)
Looked for a chrome-remote-desktop user but that doesn't seem to exist - although there is a group by that name:
foo@bar:~$ grep 'chrome-remote-desktop' /etc/group
chrome-remote-desktop:x:1001:foo
Any ideas? Thanks in advance!

A: This happens because of the way Chrome Remote Desktop works. It creates a new session which you can access remotely in parallel to the other sessions. Normally the X server/GUI runs on session 7 (you can try and change sessions with Ctrl + Alt + Fn, where n is the session number), and Chrome Remote Desktop uses a different one. So whenever you're asked to enter your password using a GUI, the window appears on the main GUI session (session 7), and there's no way to access it from Chrome Remote Desktop directly.
Fortunately, there's a bit of hacking you can do to circumvent this. As mentioned here, you could edit /opt/google/chrome-remote-desktop/chrome-remote-desktop (create a backup of this file first in case anything goes wrong):
FIRST_X_DISPLAY_NUMBER = 0 # Replace 20 by 0

Then comment out the while loop:
def get_unused_display_number():
    """Return a candidate display number for which there is currently no
    X Server lock file"""
    display = FIRST_X_DISPLAY_NUMBER
    # while os.path.exists(X_LOCK_FILE_TEMPLATE % display):
    # display += 1
    return display

Another solution is to run applications from terminal with sudo, e.g. sudo google-chrome (not recommended).
Hopefully the team developing Chrome Remote Desktop will hear us all out and soon change this behaviour.

A: you might want to try adding your user self to the user group chrome-remote-desktop - this worked for me with the command
sudo /opt/google/chrome-remote-desktop/chrome-remote-desktop --add-user-as-root $USER


text:
Q: How does this implicit conversion in C++ takes place? I'm new to C++.When I was reading, I came across this snippet.
#include "iostream"
using namespace std;
void swap(int& num1,int& num2)
{
    cout<<&num1<<"\n";
    int temp=num1;
    num1=num2;
    num2=temp;
}

int main()
{
    int num1=1,num2=4;
    swap(num1, num2);
    cout<<num1<<"\n"<<num2<<"\n";
    return 0;
}

My doubt is we are passing only the values.How does the address get passed?Kindly clear me this basic doubt.

A: There is no implicit conversion taking place. You are just passing an int by reference instead of by value.
Have a look through this tutorial. It's relatively short and gets the idea across.

A: You are basically passing by reference and reference is just an alias to that int ( You can say another name assigned to that memory ). So, anything you do with that alias is reflected to the memory for which it is alias to ( in this case your original int )

A: Re

" How does the address get passed?

it isn't, necessarily.
For example, chances are that your compiler will inline the function call in the machine code, and treat each reference as simply an alias for whatever's referred to.
But in many cases such optimization isn't possible, and ad hoc schemes such as numbering the possible bindings and so on aren't really practical, so the general implementation of a reference, at the machine code level, is a memory address.


text:
Q: Expanding variables in file contents I have a file template.txt which contains the following:
Hello ${something}

I would like to create a PowerShell script that reads the file and expands the variables in the template, i.e.
$something = "World"
$template = Get-Content template.txt
# replace $something in template file with current value
# of variable in script -> get Hello World

How could I do this?

A: I've found this solution:
$something = "World"
$template = Get-Content template.txt
$expanded = Invoke-Expression "`"$template`""
$expanded

A: Another option is to use ExpandString() e.g.:
$expanded = $ExecutionContext.InvokeCommand.ExpandString($template)

Invoke-Expression will also work.  However be careful.  Both of these options are capable of executing arbitrary code e.g.:
# Contents of file template.txt
"EvilString";$(remove-item -whatif c:\ -r -force -confirm:$false -ea 0)

$template = gc template.txt
iex $template # could result in a bad day

If you want to have a "safe" string eval without the potential to accidentally run code then you can combine PowerShell jobs and restricted runspaces to do just that e.g.:
PS> $InitSB = {$ExecutionContext.SessionState.Applications.Clear(); $ExecutionContext.SessionState.Scripts.Clear(); Get-Command | %{$_.Visibility = 'Private'}}
PS> $SafeStringEvalSB = {param($str) $str}
PS> $job = Start-Job -Init $InitSB -ScriptBlock $SafeStringEvalSB -ArgumentList '$foo (Notepad.exe) bar'
PS> Wait-Job $job > $null
PS> Receive-Job $job
$foo (Notepad.exe) bar

Now if you attempt to use an expression in the string that uses a cmdlet, this will not execute the command:
PS> $job = Start-Job -Init $InitSB -ScriptBlock $SafeStringEvalSB -ArgumentList '$foo $(Start-Process Notepad.exe) bar'
PS> Wait-Job $job > $null
PS> Receive-Job $job
$foo $(Start-Process Notepad.exe) bar

If you would like to see a failure if a command is attempted, then use $ExecutionContext.InvokeCommand.ExpandString to expand the $str parameter.

A: Since I really don't like the idea of One More Thing To Remember - in this case, remembering that PS will evaluate variables and run any commands included in the template - I found another way to do this.
Instead of variables in template file, make up your own tokens - if you're not processing HTML, you can use e.g. <variable>, like so:
Hello <something>

Basically use any token that will be unique.
Then in your PS script, use:
$something = "World"
$template = Get-Content template.txt -Raw
# replace <something> in template file with current value
# of variable in script -> get Hello World
$template=$template.Replace("<something>",$something)

It's more cumbersome than straight-up InvokeCommand, but it's clearer than setting up limited execution environment just to avoid a security risk when processing simple template. YMMV depending on requirements :-)


text:
Q: Importing Data from Outlook 2010 into Excel 2010 I have form on my website which gets emailed when the customer completes it, then looks like this:-
You got mail from  Mr Kelley McIntyre.

Here is the form data:
First Name   : Mr XXXXX
Last Name    : XXXXXX
Company Name     : Army
Email Address    : XXXX@hotmail.co.uk
Telephone/Mobile No      : 0123456789
Date of Event    : 14/12/2013
Number of Guests     : 80
Budget   : 6500-7000
Type of Event    : Other
Catering Required    : Yes
Drinks and Entertainment Requirements    : christmas meal, welcome drink, wine at table

British Army Warrant Officers & Sergeants plus wives and partners
How Did You Hear About Us?   : Google
As you can see its fairly simple form, however I need to export this data into Excel every time I get one of these emails, so I can keep a record of all the enquiries we get.
Can someone help?
I know how to do a Macro, but if its VBA, then I'm lost, so its needs to be in idiot format if possible!

A: You can start with writing a macro to process an mail item. And setup Outlook Rule to pickup this type of email from Subject/Account then run the macro. Change sExcelFile, sRecordSheet, iC as you see fit. I have made assumptions.
This Code below is for Outlook, please note you need a running Outlook all the time to have this automation. It should get you started half way. Note you need "Microsoft Excel x.0 Object Library" in your References.
Public Sub Rules_WebSiteFormRecord(oMail As MailItem)

    Const sExcelFile As String = "C:\Test\Record.xlsx"
    Const sRecordSheet As String = "Record" ' Worksheet name

    Dim oExcel As Excel.Application, oWB As Excel.Workbook, oWS As Excel.worksheet
    Dim arrTxt As Variant, oLine As Variant, iR As Long, iC As Long, bWrite As Boolean

    Set oExcel = CreateObject("excel.application")
    Set oWB = oExcel.Workbooks.Open(FileName:=sExcelFile)
    Set oWS = oWB.Worksheets(sRecordSheet)
    ' Make Excel visible for Debug purpose:
    oExcel.Visible = True
    ' Find next row of Last used row in Excel worksheet
    iR = oWS.Cells(Rows.Count, 1).End(xlUp).Row + 1
    ' Process email body and store it into columns of worksheet "sRecordSheet"
    'Debug.Print oMail.Body
    ' Store received time of email in Column A
    oWS.Cells(iR, 1).Value = oMail.ReceivedTime
    ' Split the email body into lines then process each
    arrTxt = Split(oMail.Body, vbCrLf)
    For Each oLine In arrTxt
        bWrite = False
        ' store data according to text in line
        If InStr(1, oLine, "First Name", vbTextCompare) Then
            iC = 2 ' Column of First Name
            bWrite = True
        ElseIf InStr(1, oLine, "Last Name", vbTextCompare) Then
            iC = 3 ' Column of First Name
            bWrite = True
            ' Add the rest of the fields...
        End If
        If bWrite Then
            oWS.Cells(iR, iC).Value = Split(oLine, ":")(1)
            iR = iR + 1
        End If
    Next
    Set oWS = Nothing
    ' Close the workbook with saving changes
    oWB.Close True
    Set oWB = Nothing
    Set oExcel = Nothing
    ' mark it as Read if no error occurred
    If Err.Number = 0 Then
        oMail.UnRead = False
    Else
        MsgBox "ERR(" & Err.Number & ":" & Err.Description & ") while processing " & oMail.Subject
        Err.Clear
    End If
End Sub


text:
Q: Cleaning up date data I have a dataset where the value for date is either looking like "updated 11 April 2022" or "11-Apr-22".
anyway to unify the dates and make them all the exact same format?
I know I can remove the "update" with regex but how do I turn "11 April 2022" to "11-Apr-22" or vice versa?

A: IIUC, you can use pandas.to_datetime combined with str.replace:
df['col'] = (pd.to_datetime(df['col'].replace(r'updated\s*', '', regex=True))
               .dt.strftime('%d-%b-%y')
             )

For 11 April 2022 use %d %B %Y as strftime format
output:
0    11-Apr-22
1    11-Apr-22
Name: col, dtype: object

Input data:
df = pd.DataFrame({'col': ["updated 11 April 2022", "11-Apr-22"]})


text:
Q: Column not found: 1054 Unknown column after upgrading to CC 1.7 in custom module I am upgrading a site from 1.6 community to 1.7. A custom module that was working is now breaking with the error:
    SQLSTATE[42S22]: Column not found: 1054 Unknown column 'fulfilled' in 'where clause'";i:1;s:5421:"#0 lib/Varien/Db/Statement/Pdo/Mysql.php

app/code/local/FP/Giftcard/Block/Adminhtml/Rewrite/Sales/Order/Grid.php(102): Varien_Data_Collection_Db->load()

The queries that are running:
SELECT `main_table`.* FROM `magento_sales_order_status` AS `main_table`

SELECT COUNT(*) FROM `magento_sales_flat_order_grid` AS `main_table` WHERE

(`fulfilled` = '1') GROUP BY `main_table`.`entity_id`

The correct queries which are running before the upgrade:
SELECT COUNT(*) FROM (SELECT `main_table`.*, MIN(if(magento_sales_flat_order_giftcardproduct.type = 'PHYSICAL', ifnull(fulfilled,0), 0)) AS `fulfilled` FROM `magento_sales_flat_order_grid` AS `main_table`
 LEFT JOIN `magento_sales_flat_order_giftcardproduct` ON magento_sales_flat_order_giftcardproduct.order_id = main_table.entity_id AND magento_sales_flat_order_giftcardproduct.type = 'PHYSICAL' WHERE (`fulfilled` = '1') GROUP BY `main_table`.`entity_id`) AS `a`

SELECT `main_table`.*, MIN(if(magento_sales_flat_order_giftcardproduct.type = 'PHYSICAL', ifnull(fulfilled,0), 0)) AS `fulfilled` FROM `magento_sales_flat_order_grid` AS `main_table`
 LEFT JOIN `magento_sales_flat_order_giftcardproduct` ON magento_sales_flat_order_giftcardproduct.order_id = main_table.entity_id AND magento_sales_flat_order_giftcardproduct.type = 'PHYSICAL' WHERE (`fulfilled` = '1') GROUP BY `main_table`.`entity_id` ORDER BY created_at DESC LIMIT 20

The sales order grid rewrite code:
Class FP_Giftcard_Block_Adminhtml_Rewrite_Sales_Order_Grid
//    extends Mage_Adminhtml_Block_Sales_Order_Grid
    extends Mage_Adminhtml_Block_Sales_Order_Grid
{
    /**
     * Prepare the order grid columns by adding the totals including the giftcard amount
     */
    protected function _prepareColumns()
    {
        parent::_prepareColumns();

        /**
         * @todo
         * Waiting on client specs
         */
        #$this->_addGiftcardColumns();
        $this->_addGiftcardproductColumns();

        $this->sortColumnsByOrder();
        return $this;
    }

    protected function _addGiftcardColumns()
    {

        $_baseTotal = & $this->getColumn("base_grand_total");
        $_baseTotal["index"] = "base_grand_total_incl_gc";

        $_total = & $this->getColumn("grand_total");
        $_total["index"] = "grand_total_incl_gc";
    }

    protected function _addGiftcardproductColumns()
    {
        $this->addColumnAfter('giftcard_status', array(
            'header' => Mage::helper('sales')->__('Giftcard Fulfillment Status'),
            'index' => 'fulfilled',
            'type'  => 'options',
            'width' => '100px',
            'options' => Mage::helper("fp_giftcard/adminhtml")->getCollectionStatusMap()
        ), 'status');
    }

    /**
     * Prepare grid collection object
     *
     * @return this
     */
    protected function _prepareCollection()
    {
        $collection = Mage::getResourceModel($this->_getCollectionClass());
        $this->setCollection($collection);
        if ($this->getCollection()) {

            $this->_preparePage();

            $columnId = $this->getParam($this->getVarNameSort(), $this->_defaultSort);
            $dir      = $this->getParam($this->getVarNameDir(), $this->_defaultDir);
            $filter   = $this->getParam($this->getVarNameFilter(), null);

            if (is_null($filter)) {
                $filter = $this->_defaultFilter;
            }
            $_pseudo_filter = false;

            if (is_string($filter)) {

                // this line is broken
                $data = $this->helper('adminhtml')->prepareFilterString($filter);

                if (isset($data['giftcard_status']) && $data['giftcard_status'] == 0)
                {
                    $alias = $this->getCollection()->getTable("fp_giftcard/sales_giftcardproduct");
                    $this->getCollection()->getSelect()->where("{$alias}.type IS NULL OR {$alias}.type = '" . FP_Giftcard_Helper_Product::GCTYPE_VIRTUAL."'");

                    foreach($data as $k=>$v)
                    {
                        $_pseudo_filter[$k] = $v;
                    }

                    unset($data['giftcard_status']);
                }
                $this->_setFilterValues($data);

            }
            else if ($filter && is_array($filter)) {
                $this->_setFilterValues($filter);
            }
            else if(0 !== sizeof($this->_defaultFilter)) {
                $this->_setFilterValues($this->_defaultFilter);
            }

            if (isset($this->_columns[$columnId]) && $this->_columns[$columnId]->getIndex()) {
                $dir = (strtolower($dir)=='desc') ? 'desc' : 'asc';
                $this->_columns[$columnId]->setDir($dir);
                $this->_setCollectionOrder($this->_columns[$columnId]);
            }

            if (!$this->_isExport) {
                $this->getCollection()->load();
                $this->_afterLoadCollection();
            }
            if ($_pseudo_filter)
            {
                $this->_setFilterValues($_pseudo_filter);
            }
        }

        return $this;
    }
}

Wondering if anyone can help me track down what the issue might be and how to fix it?


text:
Q: Db2 database creation problem I've just installed DB2 v8.1.18.980. Now I try to create new database. I'm getting the error with the following sql codes:
 sqlcode :  -902

 sqlstate :  58005

Unfortunately the error itself in Russian, as a result, I cannot paste it here. Official site says the following about the problem:
"The statement cannot be processed. The application program is not permitted to issue additional SQL statements. For example, a recovery routine associated with the application program may not issue additional SQL statements.
Programmer response
Rebind the failing application program and try again. If the problem persists, examine your DBRM and make sure it matches your program."
http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/topic/com.ibm.db2z9.doc.codes/src/tpc/n902.htm
But, it's not clear to me. Any ideas, what can be wrong and how to resole it?
I'm using Windows 7 Ultimate if it may be an issue.

A: The documentation you linked to is for db2 v9 for z/os, not db2 v8 for Windows. So that's the first problem.
The documentation for v8 has this to say about SQL 902:

A system error (reason code = reason-code) occurred. Subsequent SQL statements cannot be processed.
Explanation:
A system error occurred.
User Response:
Record the message number (SQLCODE) and reason code in the message.
If trace was active, invoke the Independent Trace Facility at the operating system command prompt. Then contact your technical service representative with the following information:
Problem description
SQLCODE and embedded reason code
SQLCA contents if possible
Trace file if possible.
Federated system users: isolate the problem to the data source failing the request (refer to the Troubleshooting Guide to determine which data source is failing to process the SQL statement) and take the necessary diagnostic steps for that data source. The problem determination procedures for data sources vary, so refer to the applicable data source manuals.
sqlcode: -902
sqlstate: 58005

Which brings us to the second problem: it's asking you to contact IBM and open a ticket, and as far as I know v8 is out of support so it won't be that easy.
I think installing v9, v9.5 or v9.7 would be your best bet, unless you have a really compelling reason to stick with 8.


text:
Q: REST path design for resources having multiple IDs I'm trying to define the API for the REST paths of a new service where I have devices, and each device has a current location.
It needs a bit of background to understand the problem:

*

*This is about pushing current device locations to a central server

*Position updates are sometimes calculated on the device itself (GPS) and sent from the device (smartphone) to a server, but sometimes also via an external service (e.g. WiFi positioning system) and send from that system to a server

*Each device has a unique id which the smartphone knows. The WiFi positioning system cannot know this id, it just knows the WiFi mac address.

*Each device has several interfaces for position updates (mac addresses)

*Regardless of where / from which interface location updates come, all location data should be linked to the same unique device id

So much for the background. Now about the API design. As mentioned above, I may get location updates where only the mac address is known, and I may get location updates where the unique device id is known. In both cases I can assume the id I get is unique and theoretically I can say that mac address x belongs to device y. Practically, this means I have a non-unique index to my location REST API:
For an example, consider I have a device with ID "123" and two mac addresses "abc" and "xyz". Commonly, my REST API path would group locations under the unique device:
/devices/$id/location

Now the problem is that there are multiple (unique) ids, each however related to one same device.
Like for example this would push a location by unique device id from the smartphone (where I know that unique ID, but do NOT know the mac address of the interface):
PUT /devices/123/location

And this is where an external system which only knows the mac address is pushing the location update using the mac address as key:
PUT /devices/abc/location
PUT /devices/xyz/location

You can assume that internally I can relate mac addresses and unique device IDs to one unique internal device. I could update and return location and device info using either a mac address and a device id.
For example the following GET requests using either the unique device id or unique mac will return the same location object:
GET /devices/123/location
GET /devices/abc/location
GET /devices/xyz/location

But is that a valid REST design where I can have multiple paths to the same resource? Should I rather change my REST paths, and how?

A: It might be useful to think about how you would design a web site that supports this behavior...
You might design that protocol this way: the client loads a known bookmark URI.  Available in the representation of that page are two links, one for clients that know the mac address, a different link for those that know the identifier.  The client would choose the appropriate link to follow.  The representation returned by that would be a form, customized for the specific use case; the description of the form would specify the expected fields.  The client would fill in the known fields (ignoring any unknown fields, which presumably have reasonable default values), and submit the form.  The browser would use standard processing rules to produce the appropriate HTTP request to the action specified in the form.
In this case, where what we are interested in is (effectively) looking up the URI of the resource we want based on the information we have, we would normally use GET as the form method.  That would send a query to the server, and from there the server can communicate (perhaps via re-direct) the appropriate URI to use for that device.
Once you've got the correct URI to use, GET/PUT/POST/PATCH/DELETE should all work as you would expect.

is that a valid REST design where I can have multiple paths to the same resource?

If the identifiers are different, then the resources are different.  You are, of course, allowed to have more than one resource that expresses some concept (or, to put it another way, two different resources are allowed to share a single semantic mapping).
For your specific case, it would probably be OK to have a resource for clients that know the device by id, and another for clients that know the device by location.  However, sharing a single resource identifier for both cases simplifies the server side caching story.
Part of the point of REST: if you define your media types and relations carefully, the server should be able to change the caching strategies used without breaking any clients (because the clients are just following links and submitting forms provided by the server).