text:
Q: how to extract integer from a string? c++ i have this line taken from a txt file (first line in the file):
#operation=1(create circle and add to picture) name X Y radius.

why does this code doesnt take the integer 1 and puts it into k?
Circle Circle::CreateCirc(Circle c){
    int k;
    ifstream myfile("cmd.txt");
    if (!myfile.is_open())
        cout<<"Unable to open the requested file "<<endl;
    string line,line2="create circle";
    for (int i=1;i<countrows();i++)
    {
        getline(myfile,line);
        if (line.find(line2)!=string::npos)
        {
             istringstream ss(line);
             ss>>k;
             cout<<k<<endl;

        }

    }
    return c;

}

instead im getting adress memory...help plz

A: Because the line doesn't start with a number. You'll need to skip over the #operation= part before extracting a number.
You should check the result of the extraction, and of getline, to help identify what's going wrong when these fail.
Also, if countrows() returns the expected number of rows in the file, then your loop would miss out the last one. Either loop from zero, or while i <= countrows(); or, if you want to process every line in the file, you could simply loop while (getline(myfile,line)).

A: If the actual text in the file you try to read starts with "#operation=1" and you want the number 1 from that, you can't use the simple input operator. It will read the character '#' first, which isn't a digit and so the parsing will fail and k will not be initialized. And if k is not initialized, it will be of indeterminate value, and reading that value will lead to undefined behavior and seemingly random output.
You need to check that the extraction worked:
if (ss >> k)
    std::cout << k << '\n';

That won't solve your problem though, as like I said above, you can't use the simple input operator here. You need to parse the string using other methods. One way might be to find the equal character '=' and get a sub-string after that to try and extract the number.

A: EDIT: A way to do it not much bit a little closer to the way you were trying to do it using atoi() rather than streams.
#include <iostream>
#include <cstdlib> // for atoi()
int main(){

    std::string str = "#operation=1(create circle and add to picture) name X Y radius.";
    int k;

    std::string line=str, line2="(create circle";

    std::size_t fnd = line.find(line2);
    if (fnd!=std::string::npos)
    {
         k = atoi(&str[fnd-1]); // int atoi(const char *str) == argument to integer
         std::cout<< k << " " << str[fnd-1] << str[fnd] << " ";
    }
}

There are a few ways to extract an integer from a string but i like to filter out the digit from the string;
#include <iostream>

int main(){

    std::string str = "#operation=1(create circle and add to picture) name X Y radius.";
    int k = 0;

    // an array of our base10 digits to filter through and compare
    const char digit[] = {'0','1','2','3','4','5','6','7','8','9'};

    for(int s_filter = 0; s_filter<str.size(); ++s_filter){
        for(int d_filter = 0; d_filter<10; ++d_filter){
        // filter through each char in string and
        // also filter through each digit before the next char

            if(digit[d_filter] == str[s_filter]) {
            // if so the char is equal to one of our digits

                k = d_filter;// and d_filter is equal to our digit
                break;

            } else continue;
        }
    }
    switch(k) {
        case 1:
            std::cout<< "k == 1";
            // do stuff for operation 1..
            return 0;
        case 2:
            std::cout<< "k != 1";
            // do more stuff
            break;
        //case 3: ..etc.. etc..
        default:
            std::cout<< "not a digit";
            return 1;
    }
}

A: try this:
Circle Circle::CreateCirc(Circle c){
 const std::streamsize ALL = std::numeric_limits< std::streamsize >::max(); // #include <limits> needed
 int k;
 ifstream myfile("cmd.txt");
 if (!myfile.is_open())
    cout<<"Unable to open the requested file "<<endl;
 for (int i=1;i<countrows(); ++i, myfile.ignore(ALL,'\n') ) // skip rest of the line
 {
    if( myfile.ignore(ALL,'=') >> k  )
    {
         cout<<k<<endl;
    }
    else
        break; // read error
 }
 return c;
}

A: // find_num.cpp (cX) 2015 adolfo.dimare@gmail.com
// http://stackoverflow.com/questions/21115457/

#include <string> // std::string
#include <cctype> // isnum

/// Find the number in 'str' starting at position 'pos'.
/// Returns the position of the first digit of the number.
/// Returns std::string::npos when no further numbers appear within 'str'.
/// Returns std::string::npos when 'pos >= str.length()'.
size_t find_num( const std::string str, size_t pos ) {
    size_t len = str.length();
    bool   isNegative = false;
    while ( pos < len ) {
        if ( isdigit(str[pos]) ) {
            return ( isNegative ? pos-1 : pos );
        }
        else if ( str[pos]=='-' ) {
            isNegative = true;
        }
        else {
            isNegative = false;
        }
        ++pos;
    }
    return std::string::npos;
}

#include <cassert>     // assert()
#include <cstring>     // strlen();

int main() {
    std::string str;

    str = "";
    assert( std::string::npos == find_num( str, 0 ) );
    assert( std::string::npos == find_num( str, 9 ) );

    str = "#operation=1(create circle and add to picture) name X Y radius.";
    assert( strlen("#operation=") == find_num( str, 0 ) );

    str = "abcd 111 xyx 12.33 alpha 345.12e-23";
    ///    0123456789.123456789.123456789.123456789.
    assert(     5 == find_num( str, 0 ) );
    assert(            13 == find_num( str, 5+3 ) );
    assert(                        25 == find_num( str, 20 ) );

    str = "abcd-111 xyx-12.33 alpha-345.12e-23";
    ///    0123456789.123456789.123456789.123456789.
    assert(    4 == find_num( str, 0 ) );
    assert(           12 == find_num( str, 5+3 ) );
    assert(                       24 == find_num( str, 20 ) );

    str = "-1";
    assert( 0 == find_num( str, 0 ) );
    assert( 1 == find_num( str, 1 ) );
    assert( std::string::npos == find_num( str, 2 ) );
    assert( std::string::npos == find_num( str, strlen("-1") ) );

    return 0;
}


text:
Q: Limit RANGE with condition in Window function Take an example I have the following transaction table, with transaction values of each department for each trimester.
    TransactionID  | Department | Trimester | Year | Value | Moving Avg
    1              | Dep1       |     T1    | 2014 |   13  |
    2              | Dep1       |     T1    | 2014 |   43  |
    3              | Dep1       |     T2    | 2014 |   36  |

   300             | Dep1            T1 |    2017 |   28  |
   301             | Dep2            T1 |    2014 |   24  |

I would like to calculate moving average for each transaction from the same department, taking the window as from the 6 trimesters to 2 trimesters before the current line's trimester. Example for transaction 300 in T1 2017, I'd like to have the average of transaction values for Dep1 from T1-2015 to T2-2016.
How can I achieve this with sliding window function in SQL Server 2014. My thought is that I should use something like
SELECT
AVG(VALUES) OVER
(PARTITION BY DEPARTMENT ORDER BY TRIMESTER,
YEAR RANGE [Take the range from previous 6 to 2 trimesters])

How would we define the RANGE clause. I suppose I could not use ROWS due to the number of rows for the window is unknown.
The same question for median. How would we rewrite for calculating the median instead of mean ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL Date and Recent Entry Records I have a datetime field "Insurance_Start_Date" in TableA and I need the following qualifications to be added in to the query.

*

*Get all the records starting April 1st of previous year. Example: Insurance_Start_Date >= 2017-04-01. But I don't want the value to be hardcoded.

*If a same member has 2 entries with different Insurance_Start_Date. Then I want to see only the recent record in my output.

A: You can use a variable...
declare @startDate datetime = cast(datepart(year,dateadd(year,-1,getdate())) as char(4)) + '0401'

select...from...where Insurance_Start_Date >= @startDate

For the second question, you can used a window function...
;with cte as(
select *, RN = row_number() over (partition by memberColumnID order by Insurance_Start_Date desc)
from YourTable
where Insurance_Start_Date >= @startDate)

select * from cte where RN = 1


text:
Q: How to define a NFS root in a discrete directory tree? I would like to setup a NFS-server for multiple docker containers and I found documentation on the archlinux-wiki.
I thought of this project as an useful example to get to know NFS-configuration and it's security details.
I am not sure what the following sentence means and how to do it.

A good security practice is to define a NFS root in a discrete directory tree which will keep users limited to that mount point.

Does that just mean to create a specific directory for the shared data and not have it accross multiple users home directory?
server OS: centos7 or 8

A: I think I know what's going on here and why the Arch wiki is confusing.
Ancient versions of NFS from back in the 1990s (version 3 and previous) could simply export arbitrary directories which were located anywhere in the filesystem. This changed with NFSv4, which requires all exported directories to be subdirectories of a top-level "root" export which is defined by the system administrator and carries the export option fsid=0 to distinguish it as the root. There is no predefined root; the admin makes an explicit choice to define the root.
Thus if you define /srv/nfs as the root, all other NFSv4 exports must be subdirectories of that directory.
However, it is likely that the directory you want to export is not actually under /srv/nfs. For example you may want to export /var/lib/docker/volumes. To do this, instead of moving the files around which might break things that depend on them being in their original location, you can create a bind mount so that the files remain in their original place in the filesystem but are also visible under the bind-mounted path.
mkdir /srv/nfs/volumes
mount --bind /var/lib/docker/volumes /srv/nfs/volumes

Now the files are available in both places in the filesystem tree, and because of that, NFSv4 can export them.
The only bit I am still confused about is why the Arch wiki calls it a "good security practice" when it is just how NFSv4 works.


text:
Q: Why is this reject_if in my model not rejecting blank records? In the following class...
class Parent < ActiveRecord::Base
  has_many :relatives
  has_many :kids, through: :relatives

  accepts_nested_attributes_for :relatives,
    :reject_if => lambda { |a| a['kid_id'].blank? },
    :allow_destroy => true
end

...I've added some code which I expected to prevent 'relatives' from saving on the parent model if their fields were blank. It doesn't seem to work. It saved both blank and non-blank fields.
I.e. when I go into the console and query the database, I can pull out the parent record and run queries like so:
2.2.2 :004 > p.relatives.find(17)
  Relative Load (5.4ms)  SELECT  "relatives".* FROM "relatives" WHERE "relatives"."parent_id" = ? AND "relatives"."id" = ? LIMIT 1  [["parent_id", 24], ["id", 17]]
 => #<Relative id: 17, relationship: "yes", parent_id: 24, kid_id: 1, created_at: "2015-11-12 09:56:07", updated_at: "2015-11-12 09:56:07">

That's what I expected - I entered data for that 'kid'.
2.2.2 :005 > r = p.relatives.find(18)
  Relative Load (3.4ms)  SELECT  "relatives".* FROM "relatives" WHERE "relatives"."parent_id" = ? AND "relatives"."id" = ? LIMIT 1  [["parent_id", 24], ["id", 18]]
 => #<Relative id: 18, relationship: "", parent_id: 24, kid_id: nil, created_at: "2015-11-12 09:56:07", updated_at: "2015-11-12 09:56:07">

This record should never have saved because it violates the lambda above, i.e. ...
2.2.2 :006 > r.relationship.blank?
 => true
2.2.2 :007 > r.kid.blank?
 => true

...the fields are blank!
Here's the controller in question (extract):
class ParentsController < ApplicationController
  before_action :set_parent, only: [:show, :edit, :update, :destroy]
  before_action :lookup_kids, only: [:new, :edit]

  # GET /parents/new
  def new
    @parent = Parent.new
    4.times { @parent.relatives.build }
  end

  # POST /parents
  # POST /parents.json
  def create
    logger.debug(" SANITY CHECK ")
    logger.debug(parent_params)

    @parent = Parent.new(parent_params)
    parent_params[:relatives_attributes].each do |k,r|
     @parent.relatives.build(r.except(:_destroy))
    end

    respond_to do |format|
      if @parent.save
        format.html { redirect_to @parent, notice: 'Parent was successfully created.' }
        format.json { render :show, status: :created, location: @parent }
      else
        format.html { render :new }
        format.json { render json: @parent.errors, status: :unprocessable_entity }
      end
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_parent
      @parent = Parent.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def parent_params
      params.require(:parent).permit(:name,
       relatives_attributes: [:parent_id, :kid_id, :relationship, :_destroy])
    end

    def lookup_kids
      @kids = Kid.all
    end
end

A: I think this might help
https://fabianosoriani.wordpress.com/2011/06/07/accepts_nested_attributes_for-3-0-5-reject_if-still-have-gotchas/
There are some gotchas behind accepts_nested_attributes_for with validations.

A: Based on my understanding since model kid is associated by Relative, you should do like this. Try this in your Parent Model
  accepts_nested_attributes_for :relatives, :allow_destroy => true

Then in Your Relative Model,
accepts_nested_attributes_for :kids,
    :reject_if => lambda { |a| a['kid_id'].blank? },
    :allow_destroy => true

A: Thanks to @user5554692, discovered the only way to do this is as follows:
Adding this to the parent controller:
parent_params[:relatives_attributes].delete_if { |k,v| v['kid_id'].blank?}

Removed all blank records, then...
@parent = Parent.new(parent_params)

Creates the parent object as usual.
Apparently, reject_if just doesn't work in this particular scenario, for some reason.


text:
Q: About the intersection of two commutator subgroups I'm reading an example in Lennox & Stonehewer's book "Subnormal Subgroup of Group".
There (p.144/145) they construct the following example. Let $L$ be an infinite elemetary abelian $2$-group and let $K=\langle x\rangle$ be a cyclic group of order $2$. Form the wreath product $W=L\wr K$. Let $F$ be the field of two elements, $B=FW$ (the group ring), and form the split extension $G=B\rtimes W$ (the action is by multiplication), so essentially $G$ is $C_2\wr (L\wr C_2)$. They claim $$[B,L]\cap[B,L^x]=[B,L,L^x].$$ I cannot understand why the equality holds. It is clear that $[B,L]\cap[B,L^x]\geq[B,L,L^x]$, but I do not see the other inequality. I thought I could see $[B,L]$ as $B(1-L)$ in the group ring $B$, so as a left-ideal, but why the intersection should then be $B(1-L)(1-L^x)$? I think there must be some smart way to see this, but I cannot see it.

A: This is an attempt at a reasonably simple-minded explanation (which may not be sufficiently rigorous).
The base group $B$ is freely generated (as a vector space over ${\mathbb F}_2$) by elements $b_{(l,m)}$ with $l \in L$ and $m \in L^x$. So elements  $g \in B$ are uniquely represented as sums $$g=\sum_{l \in L,\, m \in L^x}{a_{(l,m)} b_{(l,m)}},$$
where each $a_{(l,m)}=0$ or $1$, and all but finitely many
$a_{(l,m)}$ are $0$.
Writing all of the groups $B$, $L$, and $L^x$ additively, we have, for $l' \in L$, $[b_{(l,m)},l'] = b_{(l+l',m)} + b_{(l,m)}$. It follows from this that $[B,L]$ consists of all elements $g$ of the form above in which, for each fixed $m \in L^x$, the number of $l \in L$ for which $a_{(l,m)}$ is nonzero is even.
Similarly, $[B,L^x]$ consists of all sums of the form above in which, for each fixed $l \in L$, the number of $m \in L^x$ for which $a_{(l,m)}$ is nonzero is even.
So $[B,L] \cap [B,L^x]$ consists of the elements $g$ represented by sums that both of the above two conditions hold.
To prove the result we need to show that an element $g$ satisfying these two conditions lies in $[B,L,L^x]$. We do this by induction on the number of $m \in L^x$ for which there exists $l \in L$ with $a_{(l,m)} \ne 0$. In the base case, when there no such $m$, we have $b=0$.
Suppose that $m \in L^x$ is such that there exists $l \in L$ with $a_{(l,m)} \ne 0$. Then $h := \sum_{l \in L,}{a_{(l,m)} b_{(l,m)}}$ has an even number of nonzero $a_{(l,m)}$, and so it lies in $[B,L]$. By assumption, there exists some $m' \in L^x$ with $m \ne m'$ such that $a_{(l,m')} \ne 0$.
Now $h' := [h,m+m']$ lies in $[B,L,L^x]$, it has the same coefficients $a_{l,m}$ for that fixed value of $m$ as $g$ and all other nonzero coefficients of $h'$ are of the form  $a_{l,m'}$.
So the expression for $g + h'$ has no nonzero coefficients of the from $a_{l,m}$ for the chosen value of $m$, and we can apply induction to $g + h'$ to complete the proof.


text:
Q: How to split a mark-down Japanese string into atomic parts? Consider I have a string as follows.
string input = "合{あい}気{き}道{どう}生{う}まれる昨日{きのう}から揚{あ}げそば";

What I want to get is an array as follows.
string[] output = {"合{あい}", "気{き}", "道{どう}",
                   "生{う}", "まれる", "昨日{きのう}",
                   "から", "揚{あ}", "げそば"};

The pseudo rules to find the atomic parts:

*

*one or more kanji charactes followed by { followed by one or more hiragana characters followed by }

*one or more hiragana characters that are not enclosed between { and }.
I am not familiar with regex. I also have no idea how to distinguish kanji from hiragana. Could you help me to solve it in C#?

A: You can use the following regex:
[一-龯]+{\p{IsHiragana}+}|\p{IsHiragana}+(?![^{}]*})

See the regex demo
It contains two alternatives:

*

*[一-龯]+{\p{IsHiragana}+} - matches 1 or more Kanji ([一-龯]+, borrowed from terrancesnyder) followed by 1 or more Hiragana symbols inside {...} or...

*\p{IsHiragana}+(?![^{}]*}) - 1 or more Hiragana that is not followed by characters other than { or } and then a }.


text:
Q: Force runtime array allocation and initialization with list syntax I am working on an atmega328 that only has 2K of RAM.
I use a script to create 10bytes arrays from 10 bitmaps that represent 10 digits of my LCD timer. Those byte arrays are stored in my source code but since I only write one digit at time there is no reason to keep all of them in RAM. This way I can use bigger digits and consume less RAM!
This is what I am trying to do:
void load_digit_ba(uint8_t digit, uint8_t digit_ba[]) {

  // from 0 to 9 I copy the current digit in the byte array form into digit_ba
  if (digit == 0) {
    uint8_t digit_ba_tmp[10] = { 24, 40, 0, 0, 0, 224, 240, 248, 252, 254 };

    memcpy(digit_ba, digit_ba_tmp, 10);
  }
...

}

But it seems that the compiler is statically reserving memory for all the arrays. In my case 122 bytes * 10 digits = ~1K, more than half of my RAM.
Sketch uses 7,310 bytes (23%) of program storage space. Maximum is 30,720 bytes.
Global variables use 1,695 bytes (82%) of dynamic memory, leaving 353 bytes for local variables. Maximum is 2,048 bytes

If I add a cell to the array [11] instead of [10] and just pass 10 value as initializers it will instead allocate the memory at runtime (it seems):
void load_digit_ba(uint8_t digit, uint8_t digit_ba[]) {

  if (digit == 0) {
    uint8_t digit_ba_tmp[11] = { 24, 40, 0, 0, 0, 224, 240, 248, 252, 254 };

    memcpy(digit_ba, digit_ba_tmp, 10);
  }
...

}

Aurdino IDE says:
Sketch uses 11,396 bytes (37%) of program storage space. Maximum is 30,720 bytes.
Global variables use 597 bytes (29%) of dynamic memory, leaving 1,451 bytes for local variables. Maximum is 2,048 bytes.

Same behavior if I do uint8_t digit_ba_tmp[] letting the compiler figure the length, it reserves ~1K RAM.
Why adding a cell does that and is it clean? Doesn't seem to me.
The assumption here is that since the length of the digit array is fixed for every digit, just changes the content, and I send one digit at time over serial to the display, it makes sense to just load the current digit into ram and then send it. I don't see any heap/stack memory fragmentation issue here, am I right? smiley-sad


text:
Q: AWS - Disconnected : No supported authentication methods available (server sent :publickey) I am facing the issue in connecting server via putty. The error is showing me is "Server Refused our key: AWS - Disconnected: No supported authentication methods available (server sent:publickey)".
I am logging in with username " ubuntu ".I checked lots of websites but I didn't find any solution. I create a new key-pair file( .pem ) and tried again that's also is not working.
I am using the same key name for the pem file. Then using pem file I am creating a ppk  file and then it is not working

A: When we convert your .pem file to .ppk it creates a public and private key of it's own inside the .ppk file like this:
PuTTY-User-Key-File-2: ssh-rsa
Encryption: none
Comment: imported-openssh-key
Public-Lines: 6
AAAA***
***
***
***
...
Private-Lines: 14
AAA***
***
***
***
...
Private-MAC: ***

To connect to the server, you need to append the six lines of public key above into authorized_keys file in server user's /home/.ssh directory.
Note: Make sure the syntax is correct in authorized_keys file. For rsa keys it is like this:
ssh-rsa AAA***(whole public key in one line without pressing enter)***

A: i had the same problem, I decided to look at the public key for the root user, it had the following appearance "rsa-ssh YOUR KEY name of .pem file" in one line, the public key generated by the putty from .pem for the new user looked different: the comments and the key were written in about 6 lines when I edited the putty key as root and copied it in /nome/nevuser/.ssh/authorizade_key it work

A: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#replacing-key-pair
You have an EC2 instance it looks like, follow the instructions above to create a key pair for this instance. A PEM file is a form of password that is shared by only those who have the files configured. You have to create this on the EC2 instance in Amazon, so the EC2 knows that those who connect with this file are authorized, and then download it to your own computer, and convert it to something Putty can use.
Then, determine what operating system your EC2 instance is using. Depending on what it is, you will use a different user, for example with Ubuntu, the user is ubuntu, or Amazon Linux, the user is ec2.

A: AWS – Disconnected : No supported authentication methods available (server sent :publickey)
x
1.After uploading *pem file dont click on generate  public or private key pair.

*Just click on save private key

3.Just upload this file in auth, this will solve above issue
Please on this link for further details
https://computerlogics931.blogspot.com/2018/04/aws-disconnected-no-supported.html


text:
Q: Show that every maximal solution to $x'=G(x)$ is defined in an interval $(a,\infty)$ There is a function $G:\mathbb{R}^d\to\mathbb{R}^d$ locally lipschitz, suppose there exists $R>0$ such that $x\cdot G(x)\leq 0 , \forall x\in \mathbb{R}^d$ with $||x||\geq R$. Show that every maximal solution to $x'=G(x)$ is defined in an interval $(a,\infty)$.
By the Picar's theorem I know there exists a solution to $x'=G(x)$ on the shape of $\gamma:(a,b)\to \mathbb{R}^d$. And $a,b$ can be infinite. I don't know how to get to the proof.
Any help is appreciated.

A: Hint: For the existence of the solution define $x'=f(t,x)=G(x)$, since $G$ is Lipschitz on $x$ it follows that $f$ is Lipschitz on the second variable, so the Theorem of Picard applies. This solution is maximal, on the interval $(a,\infty)$ because the norm of $x$ is decreasing for $\|x\|\geq R$. To see this, notice that $$\frac{d}{dt}\langle\, x,x\rangle = 2\langle\,x,x'\rangle = 2\langle\,x,G(x)\rangle=2x\cdot G(x)\leq 0 $$


text:
Q: How to remove text in character vector which do not start with select text So to begin I have a df of metabolic pathways from PATRIC which contains a column called Product which looks like:
Glycyl-tRNA synthetase beta chain (EC 6.1.1.14)
1,3-propanediol dehydrogenase (EC 1.1.1.202)
Glycine dehydrogenase [decarboxylating] (glycine cleavage system P2 protein) (EC 1.4.4.2)
2',3'-cyclic-nucleotide 2'-phosphodiesterase (EC 3.1.4.16) / 3'-nucleotidase (EC 3.1.3.6)
1,4-alpha-glucan (glycogen) branching enzyme, GH-13-type (EC 2.4.1.18)

I have extracted the EC numbers using the second answer here. Some of the text above had more than one set of parentheses, so I now have a vector which looks like:
[[1]]
[1] "EC 6.1.1.14"

[[2]]
[1] "EC 1.1.1.202"

[[3]]
[1] "glycine cleavage system P2 protein" "EC 1.4.4.2"

[[4]]
[1] "EC 3.1.4.16" "EC 3.1.3.6"

[[5]]
[1] "glycogen"    "EC 2.4.1.18"

How do I remove text within"" that does not start with EC. Also lines with two EC numbers should be divided with a /, if possible.
Desired output as per Mr. Flicks answer
# [1] "EC 6.1.1.14"            "EC 1.1.1.202"           "EC 1.4.4.2"

# [4] "EC 3.1.4.16/EC 3.1.3.6" "EC 2.4.1.18"

My working example:
nan <- structure(list(Accession = structure(c(1L, 2L, 1L, 1L, 3L), .Label = c("1485.142.con.0001","1485.142.con.0002", "1485.142.con.0009"), class = "factor"),PATRIC.ID = structure(c(2L, 3L, 1L, 5L, 4L), .Label = c("fig|1485.142.peg.1066","fig|1485.142.peg.1362", "fig|1485.142.peg.2123", "fig|1485.142.peg.3103","fig|1485.142.peg.561"), class = "factor"), Product = structure(c(5L,1L, 4L, 3L, 2L), .Label = c("1,3-propanediol dehydrogenase (EC 1.1.1.202)","1,4-alpha-glucan (glycogen) branching enzyme, GH-13-type (EC 2.4.1.18)","2,3-cyclic-nucleotide 2-phosphodiesterase (EC 3.1.4.16) / 3-nucleotidase (EC 3.1.3.6)","Glycine dehydrogenase [decarboxylating] (glycine cleavage system P2 protein) (EC 1.4.4.2)","Glycyl-tRNA synthetase beta chain (EC 6.1.1.14)"), class = "factor")), .Names = c("Accession","PATRIC.ID", "Product"), row.names = c(NA, 5L), class = "data.frame")

#Extract text from parentheses and make into list
blah <- regmatches(nan$Product,gregexpr("(?<=\\().*?(?=\\))", nan$Product, perl=TRUE))

A: If you want to match only those with EC's then just add that to your expression
blah <- regmatches(nan$Product,gregexpr("(?<=\\()EC.*?(?=\\))", nan$Product, perl=TRUE))

if you want to join multiples with a slash, use paste()
sapply(blah, paste0, collapse="/")
# [1] "EC 6.1.1.14"            "EC 1.1.1.202"           "EC 1.4.4.2"
# [4] "EC 3.1.4.16/EC 3.1.3.6" "EC 2.4.1.18"


text:
Q: Why is import of class not needed when calling method on instance (Java) Something that's confused me - an example:
Thing.java:
import java.util.Date;

class Thing {
    static Date getDate() {return new Date();}
}

(same package) TestUsesThing.java:
// not importing Date here.

public class TestUsesThing {

    public static void main(String[] args) {
        System.out.println(Thing.getDate().getTime()); // okay
        // Date date = new Date(); // naturally this wouldn't be okay
    }

}

Why is it not necessary to import Date to be able to call getTime() on one of them?

A: Importing in Java is only necessary so the compiler knows what a Date is if you type
Date date = new Date();

Importing is not like #include in C/C++; all types on the classpath are available, but you import them just to keep from having to write the fully qualified name. And in this case, it's unnecessary.

A: Good question !!
I think the result is the difference between how java compiler handles expressions vs statements.
Date d = new Date(); // a statement

where as
new Thing().getDate().getTime()

is an expression as it occurs inside println method call. When you call getDate on new Thing() the compiler tries to handle the expression by looking at the type info for Thing class, which is where it gets the declaration of type Date.
But when you try to use Date separately in a statement like
Date d = new Thing().getDate();

you are assigning the result to a type in the current scope (class TestUsesThing ), compiler tries to resolve the type within that scope. As a result, you see the compiler error for unknown type.

A: Are Thing and TestUsesThing in the same package?  If so then you don't have to import Thing.  The reason you have to import Date is because it's in a different package.

A: import statements are used for couple of things.

*

*Compiler type checking and avoid naming collision.

*Ensures byte code linkage

Whenever we say
System.out.println( new Thing().getDate().getTime() )

The compiler parses this statement left to right and gets into that class.
First level compiler parsing.

*

*Go to thing class

*compile doesn't have any linkage or ClassVersion error from Thing.class

*Check Thing.class has getDate method.

*if #3 is good then compiler pointer is still in Thing.class (which has date import statements) and I could invoke Time method.

*As a consumer TestUsesThing gets only long variable.
System.out.println( new Thing().getDate() )

5.1 In this case we are implicitly accessing .toString() method

A: Actually, that was an ideal example, since there's two different standard Java Date classes: java.util.Date and java.sql.Date.
How does it know which one to use? Simple. The getDate() method is declared as part of the definition of the Thing class, and part of that declaration is its returntype:
public java.util.Date getDate() {
  return this.date;
}

Of course, if you have an import in the definition of the Thing class - and it's not ambiguous, you simply say:
public Date getDate() {

If you were to decode the binary of the Thing class, you'd see the method signature of the getDate method, and it includes the fully-qualified class name (including package) of the return type.
An import is simply a way of telling the compiler what package(s) you want to assume when referring to classes without explicit qualifications. The list of imports will be scanned whenever an unqualified class name is seen, and the packages will be searched. If there's no ambiguity (such as importing both java.util.date and java.sql.Date), that class will be used. If you can determine the class implicitly, or if the class name is fully qualified, you don't need to import.


text:
Q: Commutative Ring Ideals So I'm having some issues on fully believing my response to the following:

Let $R$ be a commutative ring. Is $xR$ always an ideal? Prove or show a counterexample.

So at first glance I believe this is true because if we have a right ideal, then by commutativity it follows that it is also a left ideal and thus a two sided ideal. But I also have this thought that unity has some importance for ideals but I have not found a counterexample to this statement with this key property.

A: Yes, it is always an ideal. As for the importance of unity, two things come to my mind that may have something to do with this.

*

*Assuming all rings are required to be unital, a subring would have to contain the unity, but not an ideal. Maybe you're confusing these two definitions with each other?

*Also, there's this property (theorem, lemma) that if an ideal contains the unity, then it's the entire ring.

A: The subset $xR=\{xr:r\in R\}$ is certainly an ideal of $R$:

*

*$0=x0$

*$xr-xs=x(r-s)$

*$(xr)s=x(rs)$

Thus $xR$ is a right ideal, which is automatically also a left ideal in case $R$ is commutative.
What can fail when $R$ is not supposed to have an identity, is that $x\in xR$. For instance in the ring (without identity) $R=2\mathbb{Z}$, if $x=4$, then $x\notin xR$, because $4(2\mathbb{Z})=8\mathbb{Z}$.
In this case, if you want the least ideal containing $x$, you have to consider
$$
xR+\mathbb{Z}x=\{xr+nx:r\in R, n\in\mathbb{Z}\}.
$$
When $R$ has an identity, $xR+\mathbb{Z}x=xR$.

A: If you mean a proper ideal, then $x$ must be non-invertible, but if you just say an ideal, then $xR$ is always an ideal.


text:
Q: Create an indexed datetime from date/time info in 3 columns using pandas First off, here is a sample of my data, a csv with Year, Julian Day, 2400hr, and then 2 value columns.
2014,92,1931,6.234,10.14
2014,92,1932,5.823,9.49
2014,92,1933,5.33,7.65
2014,92,1934,4.751,6.19
2014,92,1935,4.156,5.285
2014,92,1936,3.962,4.652
2014,92,1937,3.74,4.314
2014,92,1938,3.325,3.98
2014,92,1939,2.909,3.847
2014,92,1940,2.878,3.164

So, I start by loading libraries
    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    from datetime import datetime

then I run the parser (correct me if i'm wrong, this is the bit I format to match my data?)
def parser(x):
    return pd.datetime.strptime(x, '%Y %j %H%M')

then I go to create the variable "data", which is a read in and, hopefully, datetime indexed pandas dataframe...
data = pd.read_csv('sorted.dat',parse_dates=[0,1,2], date_parser=parser,index_col=0, header=None )

The resulting data frame looks like this:
dt  3   4
0   2014 92 1931    6.234   10.140
1   2014 92 1932    5.823   9.490
2   2014 92 1933    5.330   7.650
3   2014 92 1934    4.751   6.190
4   2014 92 1935    4.156   5.285
5   2014 92 1936    3.962   4.652
6   2014 92 1937    3.740   4.314
7   2014 92 1938    3.325   3.980
8   2014 92 1939    2.909   3.847
9   2014 92 1940    2.878   3.164
10  2014 92 1941    2.303   3.020
11  2014 92 1942    2.078   2.700
12  2014 92 1943    2.078   2.161
13  2014 92 1944    1.784   2.157
14  2014 92 1945    1.319   1.902
15  2014 92 1949    1.077   1.294
16  2014 92 1950    0.838   1.262
17  2014 92 1951    0.703   0.949
18  2014 92 1952    0.436   0.834
19  2014 92 1953    0.416   0.564
20  2014 92 1954    0.416   0.431
21  2014 92 1955    0.416   0.431
22  2014 92 1956    0.416   0.431
23  2014 92 1957    0.416   0.431
24  2014 92 1958    0.416   0.431
25  2014 92 1959    0.416   0.431
26  2014 92 2000    0.416   0.431
27  2014 92 2001    0.416   0.431
28  2014 92 2002    0.405   0.431
29  2014 92 2003    0.360   0.421
... ... ... ...
337887  2014 355 2330   0.000   0.000
337888  2014 355 2331   0.000   0.000
337889  2014 355 2332   0.000   0.000
337890  2014 355 2333   0.000   0.000
337891  2014 355 2334   0.000   0.000
337892  2014 355 2335   0.000   0.000
337893  2014 355 2336   0.000   0.000
337894  2014 355 2337   0.000   0.000
337895  2014 355 2338   0.000   0.000
337896  2014 355 2339   0.000   0.000
337897  2014 355 2340   0.000   0.000
337898  2014 355 2341   0.000   0.000
337899  2014 355 2342   0.000   0.000
337900  2014 355 2343   0.000   0.000
337901  2014 355 2344   0.000   0.000
337902  2014 355 2345   0.000   0.000
337903  2014 355 2346   0.000   0.000
337904  2014 355 2347   0.000   0.000
337905  2014 355 2348   0.000   0.000
337906  2014 355 2349   0.000   0.000
337907  2014 355 2350   0.000   0.000
337908  2014 355 2351   0.000   0.000
337909  2014 355 2352   0.000   0.000
337910  2014 355 2353   0.000   0.000
337911  2014 355 2354   0.000   0.000
337912  2014 355 2355   0.000   0.000
337913  2014 355 2356   0.000   0.000
337914  2014 355 2357   0.000   0.000
337915  2014 355 2358   0.000   0.000
337916  2014 355 2359   0.000   0.000

When I run this I get an error
  ValueError: time data 'dt' does not match format '%Y %j %H%M'

A: Try adding a parser to your read_csv
#assuming the order is year, month, day.  if you have time too, '%Y-%m-%d %H:%M:%S'
parser = lambda p: pd.datetime.strptime(p, '%Y-%m-%d')

df = pd.read_csv('sorted.dat',
                  parse_dates={'datetime': [1,2,3]},
                  date_parser=parser,
                  header=None)

Update
Parser looks correct.  I believe your current problem is in your read_csv().  The parse_dates arg is not formatted corrected (see excerpt from the doc string below).
If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a separate date column.
If [[1, 3]] -> combine columns 1 and 3 and parse as a single date column.
So your parser was expecting all 3 columns at once, but was getting them 1 at a time.  I discovered this when I added a print x statement to the parser func.  Try this modification that uses a list of lists approach
data = pd.read_csv('sorted.dat',parse_dates=[[0,1,2]], date_parser=parser,index_col=0, header=None )


text:
Q: How to check for user agent for all requests? I have a function that defines a user_agent:
func getUserAgent(c *gin.Context) bool {
    ua := ua.Parse(c.Request.UserAgent())
    if ua.Bot {
        return false
    } else {
        return true
    }
}

Also, I have routes, and I need to call getUserAgent in each route and if it true - use my routes , if false -  return smth else. How can i do this?
Routes:
func Routes(router *gin.Engine) {

    router.GET("/user_agent", getUserAgent)

    router.GET("/", func(c *gin.Context) {

        c.HTML(http.StatusOK, "index.html", nil)
    })
    router.GET("/:some_urls", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", nil)
    })

    categories := router.Group("/categories")
    {
        categories.GET("/", controller.GetAllCategories)
    }
    router.GET("/category_detail", controller.GetCategoriesById)
    products := router.Group("/products")
    {
        products.GET("/", controller.GetAllProducts_by_multi_params)
    }
...

A: Maybe you can make the getUserAgent  as middleware like below
every router will go into the getUserAgent first then run the handler.
router.Use(getUserAgent)


text:
Q: Rails: UrlHelpers in js.erb I want to keep things dry, so I'm thinking of creating a config file and put there all urls, etc.. It should be something like:
# configure.js.erb
some_url = <%= some_url.inspect %>

But there's a problem: url's hlper methods aren't included by default. I've already tried:
# config/initialializer/sprockets_js_erb.rb
module Sprockets::Rails::Helpers
  include ::Rails.application.routes.url_helpers
end

That broke the all method, setting the internal _routes to nil and raising an error when call _routes.optimize_routes_generation? in lib/action_dispatch/routing/url_for.rb:167 (and I don't know why)
There's a clean solution to this problems? Thanks

EDIT
Ok, I've just changed to class Sprockets::Context and it works, but I'm still searching for a better solution, whishfull ones that alters ERBTemplate's Context only :)


text:
Q: Can two temporary tables with the same name exist in separate queries I was wondering, if it is possible to have two temp tables with the same name in two separate queries without them conflicting when called upon later in the queries.
Query 1: Create Temp Table Tmp1 as ...
Query 2: Create Temp Table Tmp1 as ...
Query 1: Do something with Tmp1 ...
I am wondering if postgresql distinguishes between those two tables, maybe through addressing them as Query1.Tmp1 and Query2.Tmp1

A: Each connection to the database gets its own special temporary schema name, and temp tables are created in that schema. So there will not be any conflict between concurrent queries from separate connections, even if the tables have the same names. https://dba.stackexchange.com/a/5237 for more info
The PostgreSQL docs for creating tables states:

Temporary tables exist in a special schema, so a schema name cannot be given when creating a temporary table.


text:
Q: Display colorbox at the top of the page Is there a way to displat colorbox not in the middle of the page but at the top? By default the colorbox popup window is shown in the middle of the page but I want to set my own coordinates in order to display it a bit higher.
Can anyone please help?

A: for Dynamic change position
$(".example").colorbox({ top: 100, left: "50%" })

A: #colorbox{ top:0 !important; }

#colorbox{ top:100px !important; left:0 !important }

if you want to position it a bit highter from the center you could use
#colorbox{ margin-top:-30px; }


text:
Q: How to print certain lines of an input text file to another file in VB I have a large file which i am writing to a smaller file in VB, i just dont know how to select lines from an input file that i opened.
I would like to keep the first 12 lines of the large file and them copy every 3rd line into the new output.
Any help?!

A: You can do this with a StreamReader - just open one on the file, then you can call ReadLine() on it as many times as you need.
Easiest implementation would probably be a 0-to-11 (or 1-to-12) For loop, then a While where you read 2 and ignore them, then read the 3rd and write it.
Writing the new file can be done with StreamWriter, which just has a WriteLine() method to write the text.
The StreamReader and StreamWriter are generally the easiest ways to read and write text files.


text:
Q: Google Analytics api not returning data as Google Analytics interface I've been running the following
query run through google api
However, the results I get are very different from what I see in Google Analytics interface. The query returns only 2 event categories, whereas in the interface there are 6 of them.
I've checked the time frame, the view id and the segment, but everything matches. Why doesn't google analytics api retrieve the same information as the interface?


text:
Q: How to modify csv data in amcharts export I want to modify csv data while export from amcharts.
Scenario is like : I have 2 column 1 with values and other with 0. Now i dont want that column to display in the csv which have 0 values.
I did not find anything for this.

A: You could use processData for that. See more here: https://github.com/amcharts/export#changing-the-dataprovider-when-exporting
  "export": {
        "enabled": true,
        "processData": function (data, cfg) {

              if (cfg.format === 'CSV') {
                    return data.map(function (item) {
                          // Ignore the second column
                          return {
                                firstColumn: item.firstColumn
                          };
                    });
              }

              return data;
        }
  }

A: The processData way is fine for datas that do not much differ to the dataProvider.
Amcharts's doc is not very well documented about this, but after a bit of digging, I found this way :
var myChart = AmCharts.makeChart('chart-id', {
    dataProvider: myDatas, // Some datas
    export: {
        enabled: true,
        // Using the 'menu' option in order to override its behavior ...
        menu: [{
            class: 'export-main',
            menu: [{
                label: 'Download as ...',
                menu: ['PNG', 'JPG', 'SVG', 'PDF']
            }, {
                label: 'Save as ...',
                menu: [{
                    label: 'CSV',
                    // Overriding CSV export behavior :
                    click: function exportCSV() {
                        // This will export the 'myDatas' datas to a string formatted as a CSV.
                        // Feel free to change the 'data' option of the 'toCSV()' method for a different CSV.
                        myChart.export.toCSV({ data: myDatas }, function(data) {
                            // 'data' is a string containing the CSV
                            // This will download the CSV to the file MyCSV.csv !
                            this.download(data, this.defaults.formats.CSV.mimeType, 'MyCSV.csv');
                        });
                    }
                }]
            }, {
                label: 'Annotate ...',
                action: 'draw',
                menu: [{
                    class: 'export-drawing',
                    menu: ['PNG', 'JPG']
                }]
            }]
        }]
    }
});

This will export and download a CSV file with the desired datas !


text:
Q: Using an array in SELECT IN query? I want to know if it is possible to create a query where the WHERE clause has one condition but the value is an array.
This is the code & image related table in the database:

//array in user.id_lokasi => (PL001,PL002,PL003)
SELECT * FROM `lokasi`
         WHERE `id_lokasi` IN (SELECT id_lokasi FROM user WHERE id_user='admin')

A: Your query above should work already. Regarding your question if you have a set of id_lokasi you want to use in the WHERE you can do this:
SELECT * FROM `lokasi`
     WHERE `id_lokasi` IN ('PL001', 'PL002', 'PL003');

As to your original query, you could rewrite it like this to avoid the subquery:
SELECT l.* FROM `lokasi` l
LEFT JOIN user u ON
    u.id_lokasi = l.id_locasi AND u.id_user = 'admin'


text:
Q: ssh timeout in shell script workaround I have a script that loops through a list of hosts
/usr/local/bin/ssh -q -o "StrictHostKeyChecking=no" -o "BatchMode=yes" -n ${host} "/usr/bin/uptime" > /dev/null 2>&1
if [ $? -ne 0 ]
then
echo ${host}:FAILED
fi
fi
done

The problem is that when it comes across a host that is offline it hangs for some time.
I am running SSH Tectia Server 4.4.12 on i686-pc-linux-gnu
And the ConnectTimeout option is not available.
Any ideas for a workaround?
Thanks

A: Perform a task for a given length of time by using the & operator, backgrounding the process and killing its PID.:
/usr/local/bin/ssh -q -o "StrictHostKeyChecking=no" -o "BatchMode=yes" -n ${host} "/usr/bin/uptime" & PID="$!"

# Allow 5 seconds to elapse before killing the command
sleep 5

kill "$PID"


text:
Q: android webrtc cannot connected between LTE hostspot and wifi using coturn server I'm developing android webRTC with coturn trun server. There is a problem in connection.
Case 1. no problem
Offer(LTE hotspot wifi connected device) -> <- Answer(WIFI connected device)
=> Always connected well
Case 2. problem in connection
Offer(WIFI connected device) -> <- Answer(LTE hotspot wifi connected device)
=> Always iceConnectionState failed.
my coturn server running command is
turnserver -X <publicip>/<privateip> --no-tls --no-dtls --min-port 50000 --max-port 60000 -r my.domain --no-auth --syslog -l stdout --relay-ip <privateip>

turn server is running aws amazon linux ec2 instance.
any idea?

A: I found a problem. when use --no-auth option, TCP connection always can't be made.
remove --no-auth option, and use authentication method.
I used lt-cred-mech option. and make user with turnadmin command.


text:
Q: Questions regarding Google API Can somebody please answer the question below regarding the Google API for Charts?
1- Is Google Charts API completely independent of any other JS libraries or software like Flash etc?
2- Does it work completely offline (using the new version)?
3- Is it completely free for commercial usage?
Thank you.

A: *

*The API is dependent on Google's internal libraries (nothing you have to specifically load), but generally not any external libraries.  The exceptions are for the AnnotatedTimeLine and Motion charts, which are Flash-based.  3rd-party visualizations may be dependent on other libraries.

*You cannot use the API offline.  Downloading the API and hosting it locally is strictly forbidden in the Terms of Service.

*The API is free for almost all commercial usage, see Terms of Service for details.

A: *

*The google charts api uses js libraries.

*You can't use it offline

your computer must have live access to http://www.google.com/jsapi in order to use charts. This is because the visualization libraries that your page requires are loaded dynamically before you use them. The code for loading the appropriate library is part of the included jsapi script, and is called when you invoke the google.load() method. Our terms of service do not allow you to download the google.load or google.visualization code to use offline.

(https://developers.google.com/chart/interactive/faq#offline)
3 . The api is completly free (https://developers.google.com/chart/terms?hl=nl#license)


text:
Q: How can I derive from a class with a non-virtual destructor? I have the following problem. I would like to derive a class Derived from Base, but unfortunately Base has a non-virtual destructor (and I am not allowed to touch Base):
class Base{
public:
~Base(); //not virtual, cannot be changed
}

class Derived : public Base{
public:
~Derived();
// more stuff
}

The problem with this would be:
Base* tmp = new Derived();
delete tmp;

which would compile, but not call the right destructor. Thus my question:  How could I prevent a downcast of the derived pointer to the base class? Is there maybe another clever solution for this problem? Or is deriving from a class with non-virtual destructors just an absolute no-go?


text:
Q: How to compare byte to byte of two bitmap screenshots in c++ IN THE END OF THE QUESTION MY LAST EDIT
Hi all,
I have to implement a function that compares two shots of a portion of the screen in order to know if there are differences/variations. I wrote something like the following code but I can't manage it to work. In the code COORDINATES_RECT is a struct
typedef struct _COORDINATES_RECT {
int     x;
int     y;
int     sizeX;
int     sizeY;
} COORDINATES_RECT;

that in input holds data to know which is the portion of the screen to analyze, and in output returns the data of the biggest rectangle in which the function found variations. To better explain the problem, I saw that if construct in the end:
if(lpbitmap1[(i*bmpScreen1.bmWidth)+j] != lpbitmap2[(i*bmpScreen1.bmWidth)+j])

never get executed. I don't know if it is the right way to compare two bitmaps (converted into char arrays). I googled and searched in msdn but with no result.
Full code follows:
void testBitmapVariations(COORDINATES_RECT *c)
{
HDC hdcScreen = GetDC(NULL);
HDC hdcMemDC1 = CreateCompatibleDC(hdcScreen);
HDC hdcMemDC2 = CreateCompatibleDC(hdcScreen);
HBITMAP hBmpScreen1 = NULL;
HBITMAP hBmpScreen2 = NULL;
BITMAP bmpScreen1;
BITMAP bmpScreen2;

if(!hdcMemDC1 || !hdcMemDC2)
{
    MessageBox(NULL,L"CreateCompatibleDC failed", L"Failed", MB_OK);
    ReleaseDC(NULL, hdcMemDC1);
    ReleaseDC(NULL, hdcMemDC2);
    return;
}
hBmpScreen1 = CreateCompatibleBitmap(hdcMemDC1, c->sizeX, c->sizeY);
hBmpScreen2 = CreateCompatibleBitmap(hdcMemDC2, c->sizeX, c->sizeY);

SelectObject(hdcMemDC1,hBmpScreen1);

if(!BitBlt(hdcMemDC1,
           0,0,
           c->sizeX, c->sizeY,
           hdcScreen,
           c->x,c->y,
           SRCCOPY))
{
    MessageBox(NULL,L"BitBlt failed", L"Failed", MB_OK);
    ReleaseDC(NULL, hdcMemDC1);
    ReleaseDC(NULL, hdcMemDC2);
    return;
}

GetObject(hBmpScreen1,sizeof(BITMAP),&bmpScreen1);

BITMAPFILEHEADER   bmfHeader;
BITMAPINFOHEADER   bi;

bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = bmpScreen1.bmWidth;
bi.biHeight = bmpScreen1.bmHeight;
bi.biPlanes = 1;
bi.biBitCount = 32;
bi.biCompression = BI_RGB;
bi.biSizeImage = 0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrUsed = 0;
bi.biClrImportant = 0;

DWORD dwBmpSize = ((bmpScreen1.bmWidth * bi.biBitCount + 31) / 32) * 4 * bmpScreen1.bmHeight;

// Starting with 32-bit Windows, GlobalAlloc and LocalAlloc are implemented as wrapper functions that
// call HeapAlloc using a handle to the process's default heap. Therefore, GlobalAlloc and LocalAlloc
// have greater overhead than HeapAlloc.
char *lpbitmap1 = (char *)malloc(dwBmpSize);

// Gets the "bits" from the bitmap and copies them into a buffer
// which is pointed to by lpbitmap1.
GetDIBits(hdcScreen, hBmpScreen1, 0,
    (UINT)bmpScreen1.bmHeight,
    lpbitmap1,
    (BITMAPINFO *)&bi, DIB_RGB_COLORS);

Sleep(200);

SelectObject(hdcMemDC2,hBmpScreen2);

if(!BitBlt(hdcMemDC2,
           0,0,
           c->sizeX, c->sizeY,
           hdcScreen,
           c->x,c->y,
           SRCCOPY))
{
    MessageBox(NULL,L"BitBlt failed", L"Failed", MB_OK);
    ReleaseDC(NULL, hdcMemDC1);
    ReleaseDC(NULL, hdcMemDC2);
    return;
}

GetObject(hBmpScreen2,sizeof(BITMAP),&bmpScreen2);

char *lpbitmap2 = (char *)malloc(dwBmpSize);

// Gets the "bits" from the bitmap and copies them into a buffer
// which is pointed to by lpbitmap2.
GetDIBits(hdcScreen, hBmpScreen2, 0,
    (UINT)bmpScreen2.bmHeight,
    lpbitmap2,
    (BITMAPINFO *)&bi, DIB_RGB_COLORS);

int i, j, minX = bmpScreen1.bmWidth, minY = bmpScreen1.bmHeight, maxX = 0, maxY = 0;
bool changed = false;

for(i = 0; i < bmpScreen1.bmHeight; i++)
{
    for(j = 0; j < bmpScreen1.bmWidth; j++)
    {
                    // I don't know why this if never get executed
        if(lpbitmap1[(i*bmpScreen1.bmWidth)+j] != lpbitmap2[(i*bmpScreen1.bmWidth)+j])
        {
            changed = true;

            if(i < minY)
                minY = i;
            if(i > maxY)
                maxY = i;
            if(j < minX)
                minX = j;
            if(j > maxY)
                maxY = j;
        }
    }
}
if(changed)
{
    c->x = minX;
    c->y = minY;
    c->sizeX = maxX - minX;
    c->sizeY = maxY - minY;
}
else
{
    c->sizeX = 0;
    c->sizeY = 0;
}
//Frees from the heap
free(lpbitmap1);
free(lpbitmap2);
ReleaseDC(NULL, hdcMemDC1);
ReleaseDC(NULL, hdcMemDC2);
}

Thanks
Francesco
Ps. Variables declarations are put next to the block they refers to only to achieve more clarity in this question..
EDIT:
I rewrote it like this and it seems to work :) Thanks to all, however any correction is appreciated
void testBitmapVar(COORDINATES_RECT *c)
{
HDC     screenDC = GetDC(0),
        memDC = CreateCompatibleDC(screenDC);
HBITMAP hBm = CreateCompatibleBitmap(screenDC, c->sizeX, c->sizeY),
        oldHBm;
BITMAP  bm;
BITMAPFILEHEADER   bmfHeader;
BITMAPINFOHEADER   bi;
UINT    *pixels = (UINT*) malloc ((c->sizeX*c->sizeY) * sizeof(UINT));
std::ostringstream ss;
std::wstring str;
int     i, j, minX, maxX, minY, maxY;

if(!pixels)
{
    c->sizeX = 0;
    c->sizeY = 0;
    return;
}
memset(pixels, 0, (c->sizeX*c->sizeY) * sizeof(UINT));
oldHBm = (HBITMAP) SelectObject(memDC, hBm);

// copies to bitmap
BitBlt(memDC, 0, 0, c->sizeX, c->sizeY, screenDC, c->x, c->y, SRCCOPY);

Sleep(500);

BitBlt(memDC, 0, 0, c->sizeX, c->sizeY, screenDC, c->x, c->y, SRCINVERT);
GetObject(hBm, sizeof(BITMAP), &bm);

bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = bm.bmWidth;
bi.biHeight = bm.bmHeight;
bi.biPlanes = 1;
bi.biBitCount = 32;
bi.biCompression = BI_RGB;
bi.biSizeImage = 0;
bi.biXPelsPerMeter = 0;
bi.biYPelsPerMeter = 0;
bi.biClrUsed = 0;
bi.biClrImportant = 0;

GetDIBits(memDC, hBm, 0,
    (UINT)bm.bmHeight,
    pixels,
    (BITMAPINFO *)&bi, DIB_RGB_COLORS);

for(i = 0, minY = c->sizeY, maxY = -1; i < c->sizeY; i++)
{
    for(j = 0, minX = c->sizeX, maxX = -1; j < c->sizeX; j++)
    {
        if(pixels[(i*c->sizeX)+j])
        {
            if(i < minY)
                minY = i;
            if(i > maxY)
                maxY = i;
            if(j < minX)
                minX = j;
            if(j > maxX)
                maxX = j;
        }
    }
}
if(maxX != -1 && maxY != -1)
{
    c->x = minX;
    c->y = minY;
    c->sizeX = maxX - minX;
    c->sizeY = maxY - minY;
}
else
{
    c->sizeX = 0;
    c->sizeY = 0;
}

free(pixels);
SelectObject(memDC, oldHBm);
DeleteObject(hBm);
ReleaseDC(0, screenDC);
DeleteDC(memDC);
}

A: Rather than comparing the two bitmaps entirely on your own, consider using BitBlt to combine them using the SRCINVERT operator, which XORs the two together, so the parts that are identical will show up as zeros, and all the non-zero areas will be differences.

A: gc5, thanks for example! I'll add 2bit of mine:
you should define bi as:
BITMAPINFO bi;
memset(&bi, 0, sizeof(BITMAPINFO));
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bi.bmiHeader.biWidth = bm.bmWidth;
bi.bmiHeader.biHeight = bm.bmHeight;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = 32;
bi.bmiHeader.biCompression = BI_RGB;

and then no need to define a type:
GetDIBits(memDC, hBm, 0, (UINT)bm.bmHeight, pixels, &bi, DIB_RGB_COLORS);


text:
Q: c# foreach loop for downloading image just works once I am creating a pc window application that downloads image from a website url. The user is allowed to select which folder to download to.
But the problem I have is that the foreach loop only does this process once...
public bool Url_checker(string link)
{
    try
    {
        //Creating the HttpWebRequest
        HttpWebRequest request = WebRequest.Create(link.Trim()) as HttpWebRequest;
        //Setting the Request method HEAD, you can also use GET too.
        request.Method = "HEAD";
        //Getting the Web Response.
        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        //Returns TRUE if the Status code == 200
        return (response.StatusCode == HttpStatusCode.OK);
    }
    catch (WebException)
    {
        return false;
    }
}

private void submit_Click(object sender, EventArgs e)
{
    FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
    folderBrowserDialog1.ShowDialog();
    string saveToThisFolder = folderBrowserDialog1.SelectedPath ;
    int i = 0;
    var di = new DirectoryInfo(saveToThisFolder);
    di.Attributes &= ~FileAttributes.ReadOnly;

    int counter = 0;
       foreach (string x in urllist.Lines)
       {
           string EndOfURL = x.Substring(x.Length - 4);
           if (Url_checker(x) && (EndOfURL == ".jpg" || EndOfURL == ".gif" || EndOfURL == ".jpeg" || EndOfURL == ".png"))
           {
              byte[] data;
             //using (WebClient client = new WebClient())
              //{
              WebClient client = new WebClient();
                  data = client.DownloadData(x);
             // }

              File.WriteAllBytes(saveToThisFolder + @"\" + (i++ + EndOfURL), data);
              counter++;
              workingURL.Text += x; //+ System.Environment.NewLine
           }
          else
          {

              errorURL.Text += (x + System.Environment.NewLine);
          }
       }

    folderBrowserDialog1.Dispose();
}

GUI design is here.

The last result is this,

It only prints and downloads once. Its as if, its only reading the 1st line of the textbox. Or The foreach loop is wrong.
Thanks
Here is the new CODE, CLeaned
 private void submit_Click(object sender, EventArgs e)
        {
        FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
        folderBrowserDialog1.ShowDialog();
        string saveToThisFolder = folderBrowserDialog1.SelectedPath;
        int i = 0;
        var di = new DirectoryInfo(saveToThisFolder);
        di.Attributes &= ~FileAttributes.ReadOnly;

        int counter = 0;
        foreach (string x in urllist.Lines)
        {
            try
            {
                string EndOfURL = x.Substring(x.Length - 4);
                if (Url_checker(x) && (EndOfURL == ".jpg" || EndOfURL == ".gif" || EndOfURL == ".jpeg" || EndOfURL == ".png"))
                {

                    byte[] data;
                    using (WebClient client = new WebClient())
                    {
                      data = client.DownloadData(x);
                      File.WriteAllBytes(saveToThisFolder + @"\" + ("MotivatinalQuoteImage" + (i++) + EndOfURL), data);
                      counter++;
                      workingURL.Text += x + System.Environment.NewLine;
                    }
                }
                else
                {
                    errorURL.Text += (x + System.Environment.NewLine);
                }
            }
            catch (Exception ex)
            {
                errorURL.Text += ex;
            }

        }
        folderBrowserDialog1.Dispose();
    }

So after debugging, I FOUND OUT THAT the mistake is SOMEWHERE between
                       byte[] data;
                       using (WebClient client = new WebClient())
                       {
                           data = client.DownloadData(x);
                           File.WriteAllBytes(saveToThisFolder + @"\" + ("MotivatinalQuoteImage" + (i++) + EndOfURL), data);
                           counter++;
                           workingURL.Text += x + System.Environment.NewLine;
                       }

Here is what happened when I waited. After it only downloaded 1 image.

A: I think that it's actually your Url_checker method returning false when it catches an exception.
When I test your code verbatim I get the same results, it only downloads the first image.
If I use the following Url_checker which disposes the HttpWebResponse each time it works.
    public bool Url_checker(string link)
    {
        try
        {
            HttpWebRequest request = WebRequest.Create(link.Trim()) as HttpWebRequest;
            request.Method = "HEAD";

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                return (response.StatusCode == HttpStatusCode.OK);
            }
        }
        catch (WebException)
        {
            return false;
        }
    }

This is because you must dispose of the response when it's done, otherwise the underlying infrastructure doesn't know what you did with the result and can't reuse the connection for the next response.
Edit: Can someone smarter than me clarify whether this is because the response is not being read in it's entirety so you must explicitly dispose it?
Edit 2: Never mind. From the documentation on HttpWebResponse:
https://msdn.microsoft.com/en-us/library/system.net.httpwebresponse%28v=vs.110%29.aspx

You should never directly create an instance of the HttpWebResponse class. Instead, use the instance returned by a call to HttpWebRequest.GetResponse. You must call either the Stream.Close or the HttpWebResponse.Close method to close the response and release the connection for reuse. It is not necessary to call both Stream.Close and HttpWebResponse.Close, but doing so does not cause an error.

Edit 3: Oops, turns out OP is also right. I habitually wrapped his WebClient in a using (which he had done originally) when testing and it works too. For the record you can also put a using against your FolderBrowserDialog rather than disposing it yourself, although either works.
byte[] data;
using (WebClient client = new WebClient())
{
    data = client.DownloadData(x);
}
File.WriteAllBytes(saveToThisFolder + @"\" + (i++ + EndOfURL), data);
counter++;
workingURL.Text += x + System.Environment.NewLine;

A: Try to put the content of foreach under try/catch...
Starting from string EndOfUrl =....

A: I mean
foreach (string x in urllist.Lines)
   {
try
{
       string EndOfURL = x.Substring(x.Length - 4);
       if (Url_checker(x) && (EndOfURL == ".jpg" || EndOfURL == ".gif" || EndOfURL == ".jpeg" || EndOfURL == ".png"))
       {
          byte[] data;
         //using (WebClient client = new WebClient())
          //{
          WebClient client = new WebClient();
              data = client.DownloadData(x);
         // }

          File.WriteAllBytes(saveToThisFolder + @"\" + (i++ + EndOfURL), data);
          counter++;
          workingURL.Text += x; //+ System.Environment.NewLine
       }
      else
      {

          errorURL.Text += (x + System.Environment.NewLine);
      }
   }
}
catch(Exception ex)
{//todo : add some logging here}

so you can check if there's an error on the SubString method

A: The problem is that this program only LOOPS through ONCE! However, without the code below. The FOR LOOP WORKS PERFECTLY. The code below is the problem.
byte[] data;
                        using (WebClient client = new WebClient())
                        {
                          data = client.DownloadData(x);
                          File.WriteAllBytes(saveToThisFolder + @"\" + ("MotivatinalQuoteImage" + (i++) + EndOfURL), data);
                          counter++;
                          workingURL.Text += x + System.Environment.NewLine;
                        }


text:
Q: Flash FLVPlayback CuePoint problem I have a flash app that plays movies. It loads subtitles and subtitle times from an xml file. Now the problem is this: in one or two of the films the first subtitle disappears after only one second even though it's in and out times are correct and it should be displayed for 5 s.
I have no idea why this is happening since all the other films + subs work fine.
Does anyone have any idea what is happening?
Any help is much appreciated!
m.

A: I just found out the reason: somewhere in the xml file where the subs and times are, a time was broken due to the default line length of antiword. I'm using antiword to transform the subtitle files coming in doc format into .txt files. Since the word files are all tables, in the text file the column wasn't wide enough so the time got chopped off. Have no idea though why this affected the first sub of the film rather than the one that actually had the broken time.


text:
Q: List losing an element somewhere between 2 points, when nothing is being done to that list in that area   print liveCoords                                      # displays [(0,0),(1,0),(2,0)]
  if population > 3 or population < 2:
      if (j,i) in liveCoords:
          try:
              del liveCoords2[liveCoords2.index((j,i))]
          except:
              pass
  elif population == 3:
      if (j,i) in liveCoords:
          pass
      else:
          liveCoords2.append((j,i))
  print liveCoords                                       # displays [(1,0),(2,0)]

My question is not about how to do something specific, it is how my list liveCoords could possible be changed between those 2 points, from what I can see, nothing is being done that could possibly alter liveCoords, yet it is being altered.

A: Did you create liveCoords2 with the line liveCoords2 = liveCoords?  If so then they are both references to the same list, so adding or removing elements in liveCoords2 would affect liveCoords as well.
If this is the case, then changing the assignment to liveCoords2 = list(liveCoords) or liveCoords2 = liveCoords[:] would fix this.  Note that both of these methods will create a shallow copy, if any elements in listCoords are mutable objects then listCoords2 will have references to the same objects as listCoords, this should be fine for your current code but if you do end up needing to create a deep copy you can use the copy module:
import copy
liveCoords2 = copy.deepcopy(liveCoords)


text:
Q: animate background image with background size - jsfiddle updated I'm trying to animate a background of a div element and I've got it to animate from some one else's code. The problem is the background's css attribute is background-size:cover so it show a duplicate of that image in it's animation, how do I create an animation of horizontal and vertical position of an image and not have a duplicate image showing after the animation is done? Is there a piece of code that can make it work the way I want it to or is there a plugin that can do this that has a zoom effect for background-size, P.S the background has to be background-size:cover because of an elastic web design, here is the code.
jsfiddle
$({temporary_x: 0, temporary_y: 0}).animate({temporary_x: -20, temporary_y: -20}, {
duration: 350,
step: function() {
    var position = Math.round(this.temporary_x) + "px " + Math.round(this.temporary_y) + "px";
    $("#image").css({"background-position":  position, backgroundSize: 'auto !important'});
    }
});

A: I changed the css a bit to stop the image from repeating itself.
#image {
 background-size: cover;
 background: url(http://ts2.mm.bing.net/th?id=H.4546305711735429&w=240&h=133&c=7&rs=1&pid=1.7) no-repeat;
 width: 240px;
 height: 133px;

}
Here's the fiddle.
Hope it helps.

A: I think you're going to have an easier time without using the background image.  The background-size property is kinda new and behaves different in every browser.  I think just using an img element and scaling it on hover would be a little easier.
You would need to set the parent element to overflow:hidden

A: This can be done using a pseudo element to contain the background.
It allows you to set the pseudo element to 100% size initially, but afertwards change it to whatever you want.
If you set the position thru the right and bottom properties, then you need to move it very little (or may be nothing at all).
This is the CSS
#image {
    width:240px; height:133px;
    position: relative;
    overflow: hidden;
}

#image:before {
    background-size:cover;
       background-image:url(http://ts2.mm.bing.net/th?id=H.4546305711735429&w=240&h=133&c=7&rs=1&pid=1.7);
        content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    right: 0px;
    bottom: 0px;
    transition: 0.3s all;
}

#image:hover:before {
    width: 110%;
    height: 110%;
    right: -5px;
    bottom: -5px;
}

and the Javascript is gone.
updated fiddle


text:
Q: Given three arrays of data, interpolate I made a dataset by measuring three parameters, T, P, and V.  Here's a snippet (below), where a measured T of 10 corresponds to a P of 5000 and a V of 0.986894603.
T      P       V
20    5950    1.253243668
20    3000    1.07099136
22    3000    0.959660925
40    5000    1.011413134
10    5000    0.986894603

I wrote a Python code for doing calculations based on the dataset.  But so far I'm restricted to using the values in the dataset.  I would like to be able to enter any T and P and get a V via interpolation.
I'm worried that this may be impossible because all the information I have come across so far seems to suggest that the T and P arrays have to vary linearly for this to work in Python. They don't in my case.  However, I'm new to interpolation and maybe I'm not understanding what is going on.
Could anyone please point me in the right direction?


text:
Q: jquery get click button value send it to listbox I need to have click buttons values and send it to listbox.Below is my code and i comment in the middle of the code that i need to get the values of the buttons which is clicked and send it to a listbox
<asp:ListBox ID="ListBox2" runat="server"></asp:ListBox>

        $(function () {
            var count = 0;
            $('input[type=button]').on('click', function (e) {
                e.preventDefault();
                count += 1;
                if (count % 2 === 0) {
                    $(this).css('background-color', '#6FA478');
                   //I have to get here the value of every click button and send it to listbox

                }
                else {
                    $(this).css('background-color', '');
                }
            });
        });

A: Try This, where you have comment
var value = $(this).val();
$("[id$=ListBox2]").append('<option value="'+value+'">'+value+'</option>');

So code should be like
$(function () {
    var count = 0;
    $('input[type=button]').on('click', function (e) {
        e.preventDefault();
        count += 1;
        if (count % 2 === 0) {
            $(this).css('background-color', '#6FA478');
            //I have to get here the value of every click button and send it to listbox
            var value = $(this).val();
            $("[id$=ListBox2]").append('<option value="'+value+'">'+value+'</option>');
        }
        else {
            $(this).css('background-color', '');
        }
    });
});

A: try this to get current clicked button value
$(this).val();

or
 this.value


text:
Q: Are the open and close methods in itemreader and itemwriter the right places to open and close database connection in jsr-352 java batch job? Are the open and close methods in itemreader and itemwriter the right places to open and close database connection in jsr-352 java batch job? I couldn't find in spec that when those two methods will be invoked, especially in exceptional senario

A: Database is one of many data sources for batch jobs, so the batch spec wouldn't prescribe requirements specific to database connection. The answer to your question depends much on how you implement your jdbc item reader and jdbc item writer.
In general, database connections are scarce and expensive resource, and therefore are shared resources. You don't want any part of your application to hold on to connections for long period of time. So a typical pattern is to acquire database connection on-demand, and release (close) it immediately after.
Now look at the lifecycle of jdbc item reader and jdbc item writer.  They belong to a step execution, and so their life will span the whole step execution.  It is not a good idea to hold on to connection for such a long period of time, especially for connection used in jdbc item writer for updating database records.  For example, when implementing JdbcItemWriter, we chose to obtain connection on-demand when ready to write the chunk of data and release connection immediately after usage (i.e., not in open or close methods).  In this case, there is no need to keep the connection open between chunks.
For JdbcItemReader, we chose to open connection in item reader open method and close it in close method. This is because our implementation is based on a live jdbc ResultSet from which to continuously fetch data. Of course, other implementations can choose to cache or detach data and thus not rely on a live ResultSet, and instead use the on-demand pattern for better resource utilization.


text:
Q: Compare Arraylist of Strings with String I tried Arrays.asList().contains(string) to compare array items with string but return is false every time even emailid matches .
This is my array:
List<String> arraySE = new ArrayList<String>();

if(Arrays.asList(arraySE).contains(c.getString(c.getColumnIndex(KEY_EMAIL)))){
    user.setSelected(true);
} else{
    user.setSelected(isSelect);
}

Sample ARRAY:
 [user1@gmail.com, user2@gmail.com, user3@gmail.com]

NO ERROR, returning false

A: A primitive example that works correctly:
import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        List<String> arrayList = new ArrayList<>();
        arrayList.add("Hello");
        arrayList.add("Hola");
        arrayList.add("Hallo");

        boolean contains = arrayList.contains("Hello");

        System.out.println(contains);
    }
}

I would recommend that you debug through your code and especially see what c.getString(c.getColumnIndex(KEY_EMAIL)) returns.

A: boolean isThere = Arrays.asList(yourArray).contains("test");

if(isThere){

}
else{

}

A: At first, your list in your example is empty.
Sencodly, you don't need to use Arrays.asList(arraySE), because it is already a list.
You can simply use the contains function to check:
    List<String> arraySE = Arrays.asList("user1@gmail.com", "user2@gmail.com", "user3@gmail.com");

    if (arraySE.contains("user1@gmail.com")) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }

A: import java.util.ArrayList;
import java.util.Arrays;

public class Test2 {
  public static void main(String[] args) {
    String str[] = {"A","B","C","D"};
    ArrayList a = new ArrayList(Arrays.asList(str));
    System.out.println(a.contains("A"));
  }
}

A: You already have a list of strings, call contains on it. It will work if a match is found.
Why it is failing now is basically when you are calling asList the returned list is not a list of strings, so equals method works differently in that case.


text:
Q: Java: Access method of another instance of same class I'm new to this so sorry if i don't explain it great.
I have 2 class Interface and Depot.
I can call depot1.getName() and depot2.getName() in Instance class.
But I can't call them in Depot class as I am trying to check no instance of that class has the entered name:(tempname.equals(depot1.getName()) || tempname.equals(depot2.getName()))
Could it be because depot1 and depot2 haven't been created yet?
Here is getName
public String getName(){
    return name;
}

I think it may have to do with the fact that depot2 may not exist so i tried:
(depot2 != null && tempname.equals(depot2.getName()))

but that still gives more erors and won't let me compile
I am getting the following error "cannot find symbol - variable depot1"
Can I use isInstance? https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#isInstance%28java.lang.Object%29
Any help would be greatly appreciated, Thanks

A: Looks like your code don't have instance of depot1 create a instance using new like following snippet: This is not exact answer but it will help you.
package com.test;
class Depot
{
   private String name;

   public String getName()
   {
      return name;
   }

   public void setName( String name )
   {
      this.name = name;
   }

}

public class Test
{
   public static void main( String[] args )
   {
      Depot depot1 = new Depot();
      depot1.setName( "depot1" );

      Depot depot2 = new Depot();
      depot2.setName( "depot2" );

      // Rest of code
      //(tempname.equals(depot1.getName()) || tempname.equals(depot2.getName()))
   }
}


text:
Q: How can I specify several examples for the FastAPI docs when response_model is a list of models? I am writing a FastAPI app in python and I would like to use the openapi docs which are automatically generated. In particular, I would like to specify examples for the response value. I know how to do it when the response_model is a class that inherits from pydantic's BaseModel, but I am having trouble when it is a list of such classes. Here's a minimal example:
from fastapi import FastAPI

from typing import List
from pydantic import BaseModel, Field

class Person(BaseModel):
    name: str = Field(
        ...,
        title="Name",
        description="The name of the person",
        example="Alice"
    )

    age: int = Field(
        ...,
        title="Age",
        description="The age of the person",
        example=83
    )

    class Config:
        schema_extra = {
            'examples': [
                {
                    "name": "Alice",
                    "age": 83
                },
                {
                    "name": "Bob",
                    "age": 77
                }
            ]
        }

app = FastAPI()

@app.get('/person', response_model=Person)
def person():
    return {
        "name": "Alice",
        "age": 83
    }

@app.get('/people', response_model=List[Person])
def people():
    return [
        {
            "name": "Alice",
            "age": 83
        },
        {
            "name": "Bob",
            "age": 77
        }
    ]

In the automatically generated openapi docs, the example value for a successful response for /person is
{
  "name": "Alice",
  "age": 83
}

which is what I want. However, for /people it is
[
  {
    "name": "Alice",
    "age": 83
  }
]

but I would prefer for it to be
[
  {
    "name": "Alice",
    "age": 83
  },
  {
    "name": "Bob",
    "age": 77
  }
]

Is there any way to achieve that? Thank you in advance!

A: You can specify your example in responses parameter:
@app.get('/people', response_model=List[Person], responses={
    200: {
        "description": "People successfully found",
        "content": {
            "application/json": {
                "example": [
                    {
                        "name": "Alice",
                        "age": 83
                    },
                    {
                        "name": "Bob",
                        "age": 77
                    }
                ]
            }
        }
    },
    404: {"description": "People not found"}
})
def people():
    return [
        {
            "name": "Alice",
            "age": 83
        },
        {
            "name": "Bob",
            "age": 77
        }
    ]

With this code, the example is specified for status code 200, but you can also configure example for errors (or you can remove 404 entry if you do not want it to appear in your openapi).
For more information you can check FastAPI documentation: https://fastapi.tiangolo.com/advanced/additional-responses/


text:
Q: spark join change equalTo function I have two datasets and I would like to merge the tables if the element of a column contains the element of the other.
How can I do?
val df = df1.join(df2,
    df1.col("Complete Name").equalTo(df2.col("Name")))

Into
val df = df1.join(df2,
    df1.col("Complete Name").ifContain(df2.col("Name")))

A: How about:
Dataset<Row> d1 = datasetFromJsonStrings(listOf("{\n" +
    "  \"key\": \"name\",\n" +
    "  \"origin\": \"left\"\n" +
"}"));

Dataset<Row> d2 = datasetFromJsonStrings(listOf("{\n" +
    "  \"key\": \"complete name\",\n" +
    "  \"origin\": \"right\"\n" +
"}"));

// [name,left,complete name,right]
List<Row> rows = d1.join(d2, d2.col("key").contains(d1.col("key"))).collectAsList();

Note: I did it in Java out of convenience because my entire codebase is in Java, not Scala.

A: What if you do something like this
{
df1.join(df2, df1.col("Complete Name").ifContain(df2.col("Name")), "left_anti)
.union(df2.join(df1, df1.col("Complete Name").ifContain(df2.col("Name")), "left_anti))
}

Didn't test it though.


text:
Q: pause and resume jmeter execution I am looking for an option to pause and resume JMeter execution (single/multiple threads).
1. Pausing and Resuming through command line
2. From the Jmeter UI
3. By coding in some language in a sampler of Jmeter
4. Using a JMeter plugin

Any of the above methods is fine.
Any thoughts and solutions are greatly appreciated.

A: I would suggest going for Constant Throughput Timer
Despite word "constant" in its name, you can use i.e. JMeter Property via __P() function as "Target Throughput" value.

*

*Command-line: you can pass this property value via -J command-line argument like:

*

*in JMeter define i.e. throughput property as: ${__P(throughput,)}

*"tell" property value to JMeter as jmeter -Jthroughput=100 -n -t ....

*There is no way to do it from JMeter GUI without restarting the test. In general it is not recommended to run JMeter test in GUI mode.

*You can also amend the property value during the runtime

*

*for example from Beanshell Test Elements using the following script:
props.put("throughput", "300");

*using Beanshell Server

I'm pretty much sure that you'll receive a number of suggestions to use Test Action sampler from not very competent people who didn't bother to familiarize themselves with documentation which states:

TargetCurrent Thread / All Threads (ignored for Pause)

So please don't waste your time on the Test Action sampler

A: I suggest you follow the suggestion made by Oliver E. on user mailing list:

*

*http://mail-archives.apache.org/mod_mbox/jmeter-user/201607.mbox/%3cCAK4Z_0AJ2c0_L==ByfgZ16FGgkyT5S9UnzboOaj3qc9PU94LSQ@mail.gmail.com%3e
Regarding your questions:

*

*1/ follow 1 + 3 as per Dmitri Answers

*2/ not possible yet :)

*3/ Follow mailing list answer

*4/ Not possible


text:
Q: The type arguments for method System.Linq.Enumerable.OrderBy cannot be inferred from the usage I'm trying to follow the demo from this link to add a jqGrid to an MVC app.
I have a table named Companies that I'm trying to display in a grid. A Company simply contains an ID and a Name.
I'm running into an error in my controller function:
public JsonResult DynamicGridData(string sortIndex, string sortOrder, int page, int rows)
{
    int pageIndex = Convert.ToInt32(page) - 1;
    int pageSize = rows;

    var companies = companiesRepository.Companies.OrderBy(sortIndex + " " + sortOrder).Skip(pageIndex * pageSize).Take(pageSize);
    //Error here

    ...
}

I'm getting an error on the line that is calling OrderBy():

The type arguments for method 'System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I really have no idea what the error means, and I haven't been able to find an explanation. I'm not sure what is causing this error on a simple OrderBy function.

A: If you consulted the documentation for the method you are calling (Enumerable.OrderBy), you would know that the parameter is a Func<TSource, TKey> and not a string.

The type arguments for method 'System.Linq.Enumerable.OrderBy(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

The compiler attempted to figure out how the string parameter was actually a Func and then decided that it couldn't determine what TSource is and what TKey is.  It's asking you to help out by specifying those types in the call, like this:
companiesRepository.Companies.OrderBy<Company, int>(sortIndex + " " + sortOrder)

If you do that, then the compiler will instead tell you that string isn't a correct parameter, because now it has enough information to know that.

A: The specific answer to this question is you need to add
using System.Linq.Dynamic;

and you need to add a reference to Dynamic.DLL in your project.

A: If you are referencing System.Linq.Dynamic, don't forget to add using System.Linq.Dynamic;
If you are referencing System.Linq.Dynamic.Core, don't forget to add using System.Linq.Dynamic.Core;

A: You cannot OrderBy a string; you need to pass a lambda expression or delegate.
You need to use Dynamic LINQ, as mentioned in the tutorial.

A: *

*Add the reference System.Linq.Dynamic.dll to your project.

*Then, add the namespace: using System.Linq.Dynamic;

A: I know this is a school-boy error from my part, but I got this same error "CS0411   The type arguments for method 'Enumerable.OrderBy(IEnumerable, Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.".
It turns out the "property" I was sorting on, was actually a function, and I had omitted the "()". It took me AGES to find!
In my code exerpt:
return _numbers.Values.OrderBy(x => x.TotalScore);

should have been
return _numbers.Values.OrderBy(x => x.TotalScore());

Just thought I would mention it......

A: For .Net Core project, need to add a reference of System.Linq.Dynamic.Core;


text:
Q: AlpineJs - iterate only not null values I'm using Laravel8 with AlpineJs2. I want to make a conditional dropdown using Alpine.
I have 2 issues:

*

*I want to render a customClass for each children select eg. :class="selectChild{parent.id}"

*I want to render the select only if parent.children.length > 0

Thank you for your answers
$data = [
    [
        'id' => 1,
        'name' => 'Parent1 Name',
        'children' => [],
    ],
    [
        'id' => 2,
        'name' => 'Parent2 Name',
        'children' => [
            [
                'id' => 1,
                'name' => 'Parent2Child1 Name',
            ],
            [
                'id' => 2,
                'name' => 'Parent2Child2 Name',
            ],
            [
                'id' => 3,
                'name' => 'Parent2Child3 Name',
            ],
        ],
    ],
    [
        'id' => 3,
        'name' => 'Parent3 Name',
        'children' => [
            [
                'id' => 1,
                'name' => 'Parent3Child1 Name',
            ],
            [
                'id' => 2,
                'name' => 'Parent3Child1 Name',
            ],
        ],
    ],
];

and the template:

            <select class="form-select selectParent">
            <template x-for="parent in data" :key="parent.id">
                <option :value="parent.id" x-text="parent.name"></option>
            </template>
            </select>

            <template x-for="parent in data" :key="parent.id">
                <select x-if="parent.children.length"  :class="selectChild{parent.id}"  class="form-select">
                    <template x-for="child in parent.children" :key="child.id">
                        <option :value="child.id" x-text="child.name"></option>
                    </template>
                </select>
            </template>

A: Best solution I found so far:
<select x-show="parent.children.length" :class="`form-select selectChild${parent.id}`">
   <template x-for="child in parent.children" :key="child.id">
      <option :value="child.id" x-text="child.name"></option>
   </template>
</select>

I'm happy with the className, but I don't like that fact that I have to render an element and hide it...


text:
Q: What methods are quadrature and which not According to differential equations terms, one equation can be solved using quadrature if integration can be performed to obtain the desired solution, this applies well to separation of variables and certain substitution techniques, but integration is used also in finding integrating factors, and in Laplace transforms. i notice it's not used in solving the characteristic equation in linear ODES, also isn't numerical solutions aproximations to integrals?
A question rose, for what is a method of finding solutions of a differential equation that is not quadrature or that doesn rely on integration to yield a solution? what am i missing?


text:
Q: Idiomatic way in Postgres to record when an event happened Consider an event with two states.

*

*Event did not occur, therefore there is no date of event occurrence.

*Event did occur, date exists when an event occurred.

Postgres has a type timestamp, is there a way to record the two states above with just the timestamp field where the timestamp = not-set, where not set is 0 or something, or do I also need a boolean field to differentiate between the two?


text:
Q: Redirecting users signing in with social accounts I am using Django allauth for sign up and social authentication. For users signing up with there email, they are redirected normally to their profile based on their username as the slug. For example, something like this:
views.py
class RegisterView(SignupView):
    form_class = RegisterForm
    template_name = 'oauth/auth_form.html'

    def form_valid(self, form):
        return redirect('profiles:Index', slug=form.cleaned_data['username'])

The user is redirected to the profiles app which contains an Index view that displays their profile based on the slug (their username inputted). This works correctly, however, when I try to do social sign in with Facebook or Google for example, it redirects me to /accounts/profile/# which is the default Django profiles page. I want them to be redirected to the profiles app, which is /profiles/{their username} How can I make this happen?

A: I think this usecase/situation is described on their (django-allauth) documentation. You can check it here.
Basically you need to create a custom adapter class (that inherits from allauth.account.adapter.DefaultAccountAdapter or allauth.socialaccount.adapter.DefaultSocialAccountAdapter, depending on the case) with that functionality and them point to it using the ACCOUNT_ADAPTER variable in the settings.

A: For errors like

AttributeError: 'SocialAccountAdapter' object has no attribute
  'is_safe_url'

If you create custom adapter inheriting allauth.account.adapter.DefaultAccountAdapter, set ACCOUNT_ADAPTER in settings.py.
If it's allauth.socialaccount.adapter.DefaultSocialAccountAdapter, set SOCIALACCOUNT_ADAPTER in settings.py


text:
Q: How can the roots of $x^4 - 16 = 0$ be $2$, $-2$, $-2i$ and $2i$? How can the roots of the equation $x^4 - 16 = 0$ be $2$, $-2$, $-2i$ and $2i$? Wouldn't it just be $2$ and $-2$? I don't know where $-2i$ and $2i$ came from. Please explain in the simplest way. Thank you!

A: This is simply repeated application of the difference of squares formula $$a^2-b^2=(a+b)(a-b),$$ together with the fact that $i^2=-1.$ In particular, $$\begin{align}x^4-16 &= (x^2)^2-4^2\\ &= (x^2+4)(x^2-4)\\ &=  (x^2+2^2)(x^2-2^2)\\ &= \bigl(x^2-2^2\cdot(-1)\bigr)(x+2)(x-2)\\ &= (x^2-2^2i^2)(x+2)(x-2)\\ &= \bigl(x^2-(2i)^2\bigr)(x+2)(x-2)\\ &= (x+2i)(x-2i)(x+2)(x-2).\end{align}$$ Hence, our roots are $\pm 2i,$ as well as $\pm 2.$

A: Simply because: $2^4=16$ , $(-2)^4=16$ , $(-2i)^4=-2^4\times(i)^4=16\times1$  , $2i^4=2^4\times i^4=16$

A: $(x^4 - 16) = (x^2 - 4) (x^2 + 4) = (x - 2) (x + 2) (x^2 + 4)$. Then, you have the real roots at $x=2$ and $x=-2$ but you also have the values which cancel $x^2 + 4$; that means that $x^2 = - 4 = 4 i^2$, then the two imaginary roots $x = 2 i$ and $x = - 2 i$.

A: $$x^4-16 = 0 \implies  (x^2-4)(x^2+4) = 0 \implies x^2-4=0\text{ or } x^2+4=0$$
$x=\pm 2$ are solutions to $x^2-4=0$, whereas $x=\pm 2i$ are solutions to $x^2+4=0$ if you allow for complex solutions.

A: $2i$ and $-2i$ are the complex roots of the equation, and $2$ and $-2$ are the real roots of the equation.
$(x^4-16)=(x^2-4)(x^2+4)=0$
or, equivalently $x^2+4=0$ which gives us roots $\pm2i(\text{here i is known as complex square root of unity or } i=\sqrt{-1})$ and $x^2-4=0$ which gives us roots $\pm2.$

A: Well you know obviously that the fourth root of 1 is nothing other than $1,-1,i,-i$ and fortunately we have $(16)^{\frac 14}=2.(1)^{\frac 14}$ so...!


text:
Q: Proof Check - Basic real analysis Prove that if $s_n$, $t_n$ are sequences such that $\lim\limits_{n \to \infty}s_n=+\infty$ and $t_n \ge 0$ for all n, then $\lim\limits_{n \to \infty}(s_n+t_n) = +\infty$.
My proof:
Since $\lim s_n=+\infty$, then for $M\,\gt0$, there exists $N$ such that $n\gt N\implies s_n\gt M$.
Now consider adding $t_n$ to each $s_n$ such that $s_n+t_n\gt M+t_n$ and since $t_n\ge 0$ for all $n$. For $t_n\gt 0$ this is true and for $t_n=0$ this is still true.
So for $\lim\,(s_n+t_n)$, let $A=M+t_n$ then for each $A$ there exists $N$ such that $n\gt N\implies s_n+t_n\gt A$ therefore $\lim\,(s_n+t_n)=+\infty$.
If this is wrong any hints or corrections would be very helpful.

A: There is a little issue with the fact that $A$ depends on $n$.
This is a more direct approach for the second half of your proof: for each $M>0$, let $N$ be as you defined ($n>N \implies s_n > M$). Then $n> N$ implies $s_n+t_n \ge s_n > M$.


text:
Q: How can I have Miniprofiler just call may log method for the profile messages I am building a windows service.
I am trying to have miniprofiler,  intercept ado.net calls and hand the messages to my application's logging system.
All miniprofiler needs to do is to call a static method Log(string text).
I went through the following post and learned how to intercept ado.net calls:
Using MiniProfiler for direct ADO.net calls
It seems that the only unsolved puzzle is to have miniprofile call my log method. How can I do that?
I went through the site  http://miniprofiler.com/, but the documentation is minimal.

A: In short: this isn't something MiniProfiler is designed to do, because that's not profiling.
However, you lucked out in how MiniProfiler is implemented here. You can implement IDbProfiler yourself that just calls the logger. There are only a handful of methods. Here's MiniProfiler's implementation.
If your implementation just calls your logging method(s), you can re-use all of the ADO.NET bits built for MiniProfiler like this:
IDbProfiler logger = new YourLogger();
var conn = new SqlServerConnection(myConnectionString);
var profiledConn = new ProfiledDbConnection(cnn, logger);
// ...do stuff with profiledConn


text:
Q: doing a data analysis project in R, keep getting error "Error: Must request at least one colour from a hue palette" looked all over the internet, couldn't find anything comparable to what exactly I am trying to do. any help would be appreciated thank you!!
I am making grouped histograms and density plots for variables pertaining to heart rate and age. this is what I have to make a grouped histogram and density plot:
heart_disease$Age_cat[heart_disease$Age>= 18 & heart_disease$Age<= 35]= "young adult"
heart_disease$Age_cat[heart_disease$Age>= 36 & heart_disease$Age<= 55]= "middle adult"
heart_disease$Age_cat[heart_disease$Age>= 56 & heart_disease$Age<= 65]= "older adult"
heart_disease$Age_cat[heart_disease$Age>= 66 & heart_disease$Age<= 110]= "elderly adult"

ggplot(heart_disease, aes(x = HeartDisease, fill = Age_cat)) + geom_histogram(colour = "black", binwidth = .1, lwd = .75, linetype= 1,position = "identity", alpha = 4,) + labs(x = "HeartDisease", y = "Frequency", title = "Distribution of Heart Disease by Age")

Densityplot <- ggplot(data = heart_disease,aes(x=HeartDisease,fill= Age_cat ))+ geom_density(alpha = 0.7,cex=1)+ggtitle(labs(title = "Distribution of Heart Disease by Age"))+theme(text = element_text(size=10))
Densityplot

error message reads: Error: Must request at least one colour from a hue palette.
originally I hadn't listed my variables as "Age_cat", just "age" and it worked fine. My partner told me we have to list with _cat and now nothing I've done works. this is what I originally had for example and that ran and created a plot, although quite funky looking of a plot.
heart_disease$Age[heart_disease$Age>= 18 & heart_disease$Age<= 35]= "young adult"

*I'm still learning to read these plots plz be nice I'm trying:)


text:
Q: Node.js post request returns 404 i'm trying to use postman with "post" method , but when i use it i'm getting a 404 not found error.
i will attach my code and a picture of the error
thanks in advance
using React Native
const express = require('express');

const router = express.Router();

router.post('/signup', (req, res) => {
    res.send('You made a post request');
});

module.exports = router;

Picture from Postman app with the error

A: Things to consider are
 1. Make sure you have imported the routes in app.js and used them.
 2. Your app is running on 3000 port.
const UserRouter = require('./routes/v1');
app.use('/api',UserRouter);
 const port = process.env.PORT || 3000;
app.listen(port, function() {
console.log("listening at port",port)
});


text:
Q: What's the Error? I'm unable to detect the cause of error.
Please help point me out and it's corrective action. I'm a beginner and so this will be a great help to me.
mapping.txt:
test1 hello
test2 world

My Sh file:
parameter 1 = hello
a= cat mapping.txt | grep $1 | awk '{print$1}'
echo $a

## Extracting Dump name
b=$(ls -ltr  /home/oracle/$a/$1*.dmp | awk '{print $9}' | tail -1)

I'm getting test1 as echo, but i'm unable to substitute in /home/oracle/$a/$1*.dmp
script
output: ls: /home/oracle//hello*.dmp: No such file or directory
What change should i do to let it substitute as: /home/oracle/test1/hello*.dmp

A: From the error, you can see the variable a is not set:
Change your first line from:
a= cat mapping.txt | grep $1 | awk '{print$1}'

to:
a=$(cat mapping.txt | grep $1 | awk '{print$1}')