问:
Understanding a Structure / Linked List
I came across this structures and I am having a hard time "dissecting" them, both because I write them differently and because I'm dumb.

Here's the structures:

```<code>typedef struct no_disciplina * ListDisciplinas;

typedef struct no_disciplina
{
     char * nome;
     struct no_apont_aluno * alunos;
     ListDisciplinas next;
} NoDisciplina;

typedef struct no_aluno * ListAlunos;

typedef struct no_aluno
{
     char * nome;
     int numero;
     struct no_apont_disciplina * disciplinas;
     ListAlunos next;
 } NoAluno;

 typedef struct no_apont_disciplina * ListApontDisciplinas;

 typedef struct no_apont_disciplina
 {    ListDisciplinas disciplina;
      ListApontDisciplinas next;
 } NoApontDisciplina;

typedef struct no_apont_aluno * ListApontAlunos;

typedef struct no_apont_aluno
{
     ListAlunos aluno;
     ListApontAlunos next;
} NoApontAluno;
</code>```

Also it is said that these linked lists don't have a header (a node solely composed of a pointer to the first "real" node of the list) so how do i define it?

Thanks in advance :D!

答:
So you would define your linked list like so,

```<code>typedef struct node {
    char val;
    struct node * next;
} node_t;
</code>```

Then to use the linked list with a head you would do something like this,

```<code>node_t * head = NULL;
head = malloc(sizeof(node_t));
if (head == NULL) {
    return 1;
}

head->val = 'a';
head->next = NULL;
</code>```

So now 'head' will be your header and any subsequent nodes you define will be attached to the 'head' with the last element being the tail.

Title: Understanding a Structure / Linked List

Body:
I came across this structures and I am having a hard time "dissecting" them, both because I write them differently and because I'm dumb.

Here's the structures:

typedef struct no_disciplina * ListDisciplinas;

typedef struct no_disciplina
{
     char * nome;
     struct no_apont_aluno * alunos;
     ListDisciplinas next;
} NoDisciplina;

typedef struct no_aluno * ListAlunos;

typedef struct no_aluno
{
     char * nome;
     int numero;
     struct no_apont_disciplina * disciplinas;
     ListAlunos next;
 } NoAluno;

 typedef struct no_apont_disciplina * ListApontDisciplinas;

 typedef struct no_apont_disciplina
 {    ListDisciplinas disciplina;
      ListApontDisciplinas next;
 } NoApontDisciplina;

typedef struct no_apont_aluno * ListApontAlunos;

typedef struct no_apont_aluno
{
     ListAlunos aluno;
     ListApontAlunos next;
} NoApontAluno;

Also it is said that these linked lists don't have a header (a node solely composed of a pointer to the first "real" node of the list) so how do i define it?

Thanks in advance :D!

Body:
So you would define your linked list like so,

typedef struct node {
    char val;
    struct node * next;
} node_t;

Then to use the linked list with a head you would do something like this,

node_t * head = NULL;
head = malloc(sizeof(node_t));
if (head == NULL) {
    return 1;
}

head->val = 'a';
head->next = NULL;

So now 'head' will be your header and any subsequent nodes you define will be attached to the 'head' with the last element being the tail.


来源: stackexchange

问:
readyState vs status==200
```<code>xmlhttp.onreadystatechange = function()
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
    }
}
</code>```

Above code is from:http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp.

Question:

According to this tutorial:

```<code>readyState: 4: request finished and response is ready

status: 200: "OK"

When readyState is 4 and status is 200, the response is ready:
</code>```

since when xmlhttp.readyState == 4,  response is ready, why do we still need xmlhttp.status == 200? what is the difference between xmlhttp.readyState == 4 and xmlhttp.status == 200?

答:
onreadystatechange=function() executes only when we get the response from the server.
If we get response from the server means our request is finished which is indicated by 4.And 200 tells us its status that is correct.
"4: request finished and response is ready status 200"
We get status 404 if the page is not found.</p>

ContentLicense: CC BY-SA 3.0

Title: readyState vs status==200

Body:
xmlhttp.onreadystatechange = function()
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
    }
}

Above code is from:http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp.

Question:

According to this tutorial:

readyState: 4: request finished and response is ready

status: 200: "OK"

When readyState is 4 and status is 200, the response is ready:

since when xmlhttp.readyState == 4,  response is ready, why do we still need xmlhttp.status == 200? what is the difference between xmlhttp.readyState == 4 and xmlhttp.status == 200?


问:
Inherit acessor in typescript
I have a class A which possesses an accessor for an object which contains several string.
The whole thing offers an easy way to get url to call a Vertx API.

My problem is that I would like to overload this API in a subclass B which inherit the class A.

Something like that :

```<code>class A {
    get api () {
        return {
            GET_LESSON : '/lesson/',
        };
    }
}

class B extends A{
    get api () {
        return _.extend(super.api, {
            GET_CALL : '/lesson/call/',
       });
   }
}
</code>```

But it doesn't work, I get the error :

```TS2340:Only public and protected methods of the base class are accessible via the 'super' keyword.```

Why do I have this error ? Is it an intended behaviour for Typescript Accessors ?

答:
Is it an intended behaviour for Typescript Accessors

Yes. This is being tracked here : https://github.com/Microsoft/TypeScript/issues/338

Reason why its not supported yet: The current super lookup is really simple. Changing that has performance impacts covered in the issue as mentioned.

Title: Inherit acessor in typescript

Body:
I have a class A which possesses an accessor for an object which contains several string.
The whole thing offers an easy way to get url to call a Vertx API.

My problem is that I would like to overload this API in a subclass B which inherit the class A.

Something like that :

class A {
    get api () {
        return {
            GET_LESSON : '/lesson/',
        };
    }
}

class B extends A{
    get api () {
        return _.extend(super.api, {
            GET_CALL : '/lesson/call/',
       });
   }
}

But it doesn't work, I get the error :

TS2340:Only public and protected methods of the base class are accessible via the 'super' keyword.

Why do I have this error ? Is it an intended behaviour for Typescript Accessors ?


问:
SASS not compiling in symfony
I'm trying to use SASS with the Assetic bundle with symfony. I followed the main tutorial here. However, it is not generating any css files. I've tried using different outputs, checking file permissions and messing with filters, but I'm not very sure where to go from here.

The relevant config.yml code:

```<code># Assetic Configuration
assetic:
    debug:          '%kernel.debug%'
    use_controller: '%kernel.debug%'
    filters:
        cssrewrite: ~
        scssphp:
          bin: /usr/local/lib/ruby/gems/2.3.0/gems/sass-3.4.24
          apply_to: .scss$
</code>```

And this is my stylesheet.html.twig which I include in my base.html.twig

```<code>{% stylesheets
    'sass/style.scss'
    filter = "scssphp" output='css/sass.css' %}
    <link rel="stylesheet" href="{{ asset_url }}"/>
{% endstylesheets %}
</code>```

I tried using the following command line:

```<code>php bin/console assetic:dump --env=prod --no-debug
</code>```

And got the following error:

```<code>[Assetic\Exception\FilterException]
  An error occurred while running:
  '/usr/local/lib/ruby' '/usr/local/lib/ruby/gems/2.3.0/gems/sass-3.4.24' '--
  load-path' '/Applications/XAMPP/xamppfiles/htdocs/my_website/app/../web/sas
  s' '--scss' '--load-path' '/Applications/XAMPP/xamppfiles/htdocs/my_website
  /app/../web' '--cache-location' '/Applications/XAMPP/xamppfiles/htdocs/my_w
  ebsite/var/cache/prod' '/private/var/folders/_2/xkw80vl13zj0xw0nm7j8c4bc000
  0gn/T/assetic_sassqn8iBF'
  Error Output:
  sh: /usr/local/lib/ruby: is a directory
  sh: line 0: exec: /usr/local/lib/ruby: cannot execute: Undefined error: 0
  Input:
  [...]
</code>```

The remainder of the error was just my scss file. I'm not quite sure what the error is telling me.

Thanks :)

答:
I think you need to find the correct path to ruby (that error means /usr/local/lib/ruby is not your ruby interpreter, but just a folder) and sass.

Execute which ruby. It will print the path to ruby. For me it's /usr/bin/ruby.

Setup the correct path in your configuration:

```
    assetic:
        debug:          '%kernel.debug%'
        use_controller: '%kernel.debug%'
        ruby: /usr/bin/ruby
        filters:
            cssrewrite: ~
            scssphp:
            bin: /usr/local/lib/ruby/gems/2.3.0/gems/sass-3.4.24
            apply_to: .scss$
```

If it still doesn't work, probably you need to find the correct path of sass too. I'm looking for it in this folders:

find /usr/local/bin/ | grep sass
find /usr/bin/ | grep sass
find /usr/lib/ | grep sass

The first command gave to me this output:

```<code>/usr/local/bin/sass-convert
/usr/local/bin/node-sass
/usr/local/bin/sass
</code>```

The last line reveals the path. Try to change it in your configuration, like this:

```<code>assetic:
    debug:          '%kernel.debug%'
    use_controller: '%kernel.debug%'
    ruby: /usr/bin/ruby
    filters:
        cssrewrite: ~
        scssphp:
          bin: /usr/local/bin/sass
          apply_to: .scss$
</code>```

Let me know if it works.

Title: SASS not compiling in symfony

Body:
I'm trying to use SASS with the Assetic bundle with symfony. I followed the main tutorial here. However, it is not generating any css files. I've tried using different outputs, checking file permissions and messing with filters, but I'm not very sure where to go from here.

The relevant config.yml code:

# Assetic Configuration
assetic:
    debug:          '%kernel.debug%'
    use_controller: '%kernel.debug%'
    filters:
        cssrewrite: ~
        scssphp:
          bin: /usr/local/lib/ruby/gems/2.3.0/gems/sass-3.4.24
          apply_to: .scss$

And this is my stylesheet.html.twig which I include in my base.html.twig

{% stylesheets
    'sass/style.scss'
    filter = "scssphp" output='css/sass.css' %}
    <link rel="stylesheet" href="{{ asset_url }}"/>
{% endstylesheets %}

I tried using the following command line:

php bin/console assetic:dump --env=prod --no-debug

And got the following error:

[Assetic\Exception\FilterException]
  An error occurred while running:
  '/usr/local/lib/ruby' '/usr/local/lib/ruby/gems/2.3.0/gems/sass-3.4.24' '--
  load-path' '/Applications/XAMPP/xamppfiles/htdocs/my_website/app/../web/sas
  s' '--scss' '--load-path' '/Applications/XAMPP/xamppfiles/htdocs/my_website
  /app/../web' '--cache-location' '/Applications/XAMPP/xamppfiles/htdocs/my_w
  ebsite/var/cache/prod' '/private/var/folders/_2/xkw80vl13zj0xw0nm7j8c4bc000
  0gn/T/assetic_sassqn8iBF'
  Error Output:
  sh: /usr/local/lib/ruby: is a directory
  sh: line 0: exec: /usr/local/lib/ruby: cannot execute: Undefined error: 0
  Input:
  [...]

The remainder of the error was just my scss file. I'm not quite sure what the error is telling me.

Thanks :)

Body:
I think you need to find the correct path to ruby (that error means /usr/local/lib/ruby is not your ruby interpreter, but just a folder) and sass.

Execute which ruby. It will print the path to ruby. For me it's /usr/bin/ruby.

Setup the correct path in your configuration:

    assetic:
        debug:          '%kernel.debug%'
        use_controller: '%kernel.debug%'
        ruby: /usr/bin/ruby
        filters:
            cssrewrite: ~
            scssphp:
            bin: /usr/local/lib/ruby/gems/2.3.0/gems/sass-3.4.24
            apply_to: .scss$

If it still doesn't work, probably you need to find the correct path of sass too. I'm looking for it in this folders:

find /usr/local/bin/ | grep sass
find /usr/bin/ | grep sass
find /usr/lib/ | grep sass

The first command gave to me this output:

/usr/local/bin/sass-convert
/usr/local/bin/node-sass
/usr/local/bin/sass

The last line reveals the path. Try to change it in your configuration, like this:

assetic:
    debug:          '%kernel.debug%'
    use_controller: '%kernel.debug%'
    ruby: /usr/bin/ruby
    filters:
        cssrewrite: ~
        scssphp:
          bin: /usr/local/bin/sass
          apply_to: .scss$

Let me know if it works.


问:
SQL Find Values Between *
I have a strange request, I thikn.
I have a system which I need to retrieve data from - its SQL based. The field in question has a multitude of data in it, but I specifically only need 1 or 2 values.

In the example below, the field contains values contained in "*". I need to retrieve the value for AQISPremIdProcessType_Hidden which is "N2725/D". Is this possible through a SQL script?

```<code>AQISEntityIds_Hidden=CN0001MB*AQISPremIdProcessType_Hidden=N2725/D*CPQuestionGenDate_Hidden=20/01/2017
</code>```

答:
You can use charindex(<what>, <where>) function. First, to find index of AQISPremIdProcessType_Hidden= string. Second, to find index of first * after it.
Here an example:

```<code>declare
    @testString nvarchar(max) = N'AQISEntityIds_Hidden=CN0001MB*AQISPremIdProcessType_Hidden=N2725/D*CPQuestionGenDate_Hidden=20/01/2017',
    @field nvarchar(max) = N'AQISPremIdProcessType_Hidden=';

;with _rawInfo as(
    select @testString as [Str]
)
, _trimmedStart as (
    select
        [Str] as [Origin],
        -- check here the math: 2nd arg = length of the tail, so we take
        -- whole length [StrLen] and subtract index of @field and its length
        right([Str], [StrLen] - FieldInd - FieldLen + 1) as Tail
    from _rawInfo
    cross apply (
        select
            len([Str]) as [StrLen],
            charindex(@field, [Str]) as FieldInd,
            len(@field) as FieldLen
    ) x
), _result as (
    select
        [Origin],
        Tail,
        -- 2nd arg = length of the left cut, so we just take index of '*'
        left(Tail, charindex(N'*', Tail) - 1) as [Value]
    from _trimmedStart
)
select
    *
from _result
</code>```

UPD. And query adapted for your data:

```<code>;with _trimmedStart as (
    select
        jd.*,
        right(AddInfo, AddInfoLen - FieldInd - FieldLen + 1) as AddInfoTail
    from JobDeclaration jd
    cross apply (
        select
            len(AddInfo) as AddInfoLen,
            charindex(@field, AddInfo) as FieldInd,
            len(@field) as FieldLen
    ) x
), _result as (
    select
        t.*,
        left(AddInfoTail, charindex(N'*', AddInfoTail) - 1) as [AQISPremIdProcessType_Hidden]
    from _trimmedStart t
)
select
    *
from _result
</code>```

Title: SQL Find Values Between *

Body:
I have a strange request, I thikn.
I have a system which I need to retrieve data from - its SQL based. The field in question has a multitude of data in it, but I specifically only need 1 or 2 values.

In the example below, the field contains values contained in "*". I need to retrieve the value for AQISPremIdProcessType_Hidden which is "N2725/D". Is this possible through a SQL script?

AQISEntityIds_Hidden=CN0001MB*AQISPremIdProcessType_Hidden=N2725/D*CPQuestionGenDate_Hidden=20/01/2017

Body:
You can use charindex(<what>, <where>) function. First, to find index of AQISPremIdProcessType_Hidden= string. Second, to find index of first * after it.
Here an example:

declare
    @testString nvarchar(max) = N'AQISEntityIds_Hidden=CN0001MB*AQISPremIdProcessType_Hidden=N2725/D*CPQuestionGenDate_Hidden=20/01/2017',
    @field nvarchar(max) = N'AQISPremIdProcessType_Hidden=';

;with _rawInfo as(
    select @testString as [Str]
)
, _trimmedStart as (
    select
        [Str] as [Origin],
        -- check here the math: 2nd arg = length of the tail, so we take
        -- whole length [StrLen] and subtract index of @field and its length
        right([Str], [StrLen] - FieldInd - FieldLen + 1) as Tail
    from _rawInfo
    cross apply (
        select
            len([Str]) as [StrLen],
            charindex(@field, [Str]) as FieldInd,
            len(@field) as FieldLen
    ) x
), _result as (
    select
        [Origin],
        Tail,
        -- 2nd arg = length of the left cut, so we just take index of '*'
        left(Tail, charindex(N'*', Tail) - 1) as [Value]
    from _trimmedStart
)
select
    *
from _result

UPD. And query adapted for your data:

;with _trimmedStart as (
    select
        jd.*,
        right(AddInfo, AddInfoLen - FieldInd - FieldLen + 1) as AddInfoTail
    from JobDeclaration jd
    cross apply (
        select
            len(AddInfo) as AddInfoLen,
            charindex(@field, AddInfo) as FieldInd,
            len(@field) as FieldLen
    ) x
), _result as (
    select
        t.*,
        left(AddInfoTail, charindex(N'*', AddInfoTail) - 1) as [AQISPremIdProcessType_Hidden]
    from _trimmedStart t
)
select
    *
from _result


问:
Wordpress plug in php issues
I'd like to preface that I am not too fluent in php so i'm trying to understand and build php as i go.

I am attempting to add a custom Slidedeck slider to my website, http://cfsb.org/ . I currently have one in the header, but would like to change it on a per page basis.

```<code>I currently have:

    function slidedecktwo_header_home() {
if (is_home()) {
    echo do_shortcode('[SlideDeck2 id=xxx]');
   }
}

add_action('genesis_header', 'slidedecktwo_header_home');
</code>```

But when i try to add something like

```<code>else if (is_page(PAGE_ID = x)) {
         echo do_shortcode('[SlideDeck2 id=xxx');

}
</code>```

My webpage crashes and I have to delete the code before my website returns. Anyone see some obvious problems?

Thanks in advance.

答:
Not sure if what you posted is the actual PHP you tried, but there are definite syntax errors.

Your code should look more like this (I added a random ID passed as an integer to the is_page() function):

```<code>function slidedecktwo_header_home() {
    if ( is_home() ) {
             echo do_shortcode('[SlideDeck2 id=xxx]');
    } elseif ( is_page(42) ) {
            echo do_shortcode('[SlideDeck2 id=xxx]');
    }
}

add_action('genesis_header', 'slidedecktwo_header_home');
</code>```

In your snippet, you had is_page( PAGE_ID = x ) and your shortcode snippet wasn't closed with a closing bracket ]

Title: Wordpress plug in php issues

Body:
I'd like to preface that I am not too fluent in php so i'm trying to understand and build php as i go.

I am attempting to add a custom Slidedeck slider to my website, http://cfsb.org/ . I currently have one in the header, but would like to change it on a per page basis.

I currently have:

    function slidedecktwo_header_home() {
if (is_home()) {
    echo do_shortcode('[SlideDeck2 id=xxx]');
   }
}

add_action('genesis_header', 'slidedecktwo_header_home');

But when i try to add something like

else if (is_page(PAGE_ID = x)) {
         echo do_shortcode('[SlideDeck2 id=xxx');

}

My webpage crashes and I have to delete the code before my website returns. Anyone see some obvious problems?

Thanks in advance.

Body:
Not sure if what you posted is the actual PHP you tried, but there are definite syntax errors.

Your code should look more like this (I added a random ID passed as an integer to the is_page() function):

function slidedecktwo_header_home() {
    if ( is_home() ) {
             echo do_shortcode('[SlideDeck2 id=xxx]');
    } elseif ( is_page(42) ) {
            echo do_shortcode('[SlideDeck2 id=xxx]');
    }
}

add_action('genesis_header', 'slidedecktwo_header_home');

In your snippet, you had is_page( PAGE_ID = x ) and your shortcode snippet wasn't closed with a closing bracket ]


问:
Is my S3 bucket publicly writable?
I am trying to work out whether my S3 bucket is publicly writable.

Here is the ACL:

Here is the bucket policy:

```<code>{
"Version": "2008-10-17",
"Statement": [
    {
        "Sid": "AllowPublicRead",
        "Effect": "Allow",
        "Principal": {
            "AWS": "*"
        },
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::bucket.name/*"
    }
]
}
</code>```

I am trying to use S3 CLI: echo "hello" | aws s3 cp - s3://bucket.name/file.csv --region eu-west-1 --no-sign-request

However I get the: upload failed: - to s3://bucket.name/file.csv An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

Is my bucket safe from public write?

Background:

Got the application and trying to find weak points / auditing. Probably the easiest would be to not give the "write" access to anyone in ACLs. However the point is to not make any changes to the system / code, just find the weak points.

答:
Your bucket policy, as shown, only grants Read permissions. It does not grant Write permissions.

However, your bucket ACL is:

This is currently permitting anyone in the world to read from AND write to your bucket.

Since access is granted if ANY of these methods grant access, then Yes, your bucket is publicly writable.

Test of Scenario

Here's what I did:

Account A: Created Bucket A, assigned "public permissions" of READ and WRITE for Object access (no Permissions access -- not necessary)

Account B: Used the AWS CLI with a User from a different account (Account B) and successfully did aws s3 ls on the bucket and aws s3 cp to copy an object to the bucket

The fact that the call was made from an IAM User from a different AWS Account shows that the Object access permissions were granting read and write access.

Title: Is my S3 bucket publicly writable?

Body:
I am trying to work out whether my S3 bucket is publicly writable.

Here is the ACL:

Here is the bucket policy:

{
"Version": "2008-10-17",
"Statement": [
    {
        "Sid": "AllowPublicRead",
        "Effect": "Allow",
        "Principal": {
            "AWS": "*"
        },
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::bucket.name/*"
    }
]
}

I am trying to use S3 CLI: echo "hello" | aws s3 cp - s3://bucket.name/file.csv --region eu-west-1 --no-sign-request

However I get the: upload failed: - to s3://bucket.name/file.csv An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

Is my bucket safe from public write?

Background:

Got the application and trying to find weak points / auditing. Probably the easiest would be to not give the "write" access to anyone in ACLs. However the point is to not make any changes to the system / code, just find the weak points.


问:
Sequence number bug in CouchDB 2 or is there another way to compare sequence numbers?
I’m digging deeper into CouchDB 2 and I’m finding some unexpected ordering with sequence numbers. In one case, I found that an early change in a _changes feed has the sequence number

```<code>99-g1AAAAI-eJyd0EsOgjAQBuAGiI-dN9C9LmrBwqzkJtrSNkgQV6z1JnoTvYneBEvbhA0aMU1mkj6-_NMSITTJfYFm2anOcsFT10mpTzyG-LxpmiL32eqoN8aEAcWE9dz_jPCFrnzrHGQchiFM4kSgaV0JqQ6VFF-AtAV2DggMgCEGxrNhQfatc3bOyDiKUalg2EBVoCu66KapazcUh41e69-GssjNIvcWWRokk2oNofwj0MNazy4QFURhGQ0J9LKI-SHPIBHEgiak51nxBhxnrRk
</code>```

The last sequence number in my _changes feed, for the same DB, is

```<code>228-g1AAAAJFeJyd0EkOgjAUBuAGTJCdN9AjlIKFruQm2jFAEFes9SZ6E72J3gQ7JW7QCGnyXtLhy-vfAgCWVSjAip96XglW-o5afRJQwNbDMDRVSOuj3ogQJRgiOnL_O8I2urKdd4B1KCRpkRcCxH0npKo7KX4ApQH2HogsAElOKOPTBjkY5-yd2DqKYqnItA91C13BRTdNXY0VWouRrV7JDOvmrLuxlLW4VAlJ5Qzr4aznJ2wskIIy-y9sh7wcYoMKLJKRXOACjTxr3uHcsBE
</code>```

In a browser console, the following is false

```<code>'228-g1AAAAJFeJyd0EkOgjAUBuAGTJCdN9AjlIKFruQm2jFAEFes9SZ6E72J3gQ7JW7QCGnyXtLhy-vfAgCWVSjAip96XglW-o5afRJQwNbDMDRVSOuj3ogQJRgiOnL_O8I2urKdd4B1KCRpkRcCxH0npKo7KX4ApQH2HogsAElOKOPTBjkY5-yd2DqKYqnItA91C13BRTdNXY0VWouRrV7JDOvmrLuxlLW4VAlJ5Qzr4aznJ2wskIIy-y9sh7wcYoMKLJKRXOACjTxr3uHcsBE' > '99-g1AAAAI-eJyd0EsOgjAQBuAGiI-dN9C9LmrBwqzkJtrSNkgQV6z1JnoTvYneBEvbhA0aMU1mkj6-_NMSITTJfYFm2anOcsFT10mpTzyG-LxpmiL32eqoN8aEAcWE9dz_jPCFrnzrHGQchiFM4kSgaV0JqQ6VFF-AtAV2DggMgCEGxrNhQfatc3bOyDiKUalg2EBVoCu66KapazcUh41e69-GssjNIvcWWRokk2oNofwj0MNazy4QFURhGQ0J9LKI-SHPIBHEgiak51nxBhxnrRk'
</code>```

Is this a bug or do I need to use some other method to compare sequence numbers?

In looking at the other sequence numbers in my _changes feed, it looks like they are generally ordered as I would expect, but in this case it appears that when the first number, e.g. 99, jumps from 2 digits to 3 digits, the ordering breaks. If you boil this down to a simple string comparison example, you can see that '228' > '99' => false

答:
The following answer contains excerpts from an email thread with @rnewson. I hope it helps someone else to understand sequence numbers in CouchDB 2. Thanks, Robert!

The background:

There's no easy way to compare them in 2.0 and no requirement for them
  to be in order. They are not, in short, designed to be examined or
  compared outside of couchdb; treat them opaquely.

The number on the front is the sum of the individual update sequences
  encoded in the second part and exists only to trick older versions of
  the couchdb replicator into making checkpoints.

The latter half of the sequence string is an encoded list of {node,
  range, seq} tuples (where seq is the integer value you know from
  pre-2.0 releases). When a sequence string is passed back in, as the
  since= parameter, couchdb decodes this string and passes the
  appropriate integer seq value to the individual shard.

All that said, in general the front number should increase. The full
  strings themselves are not comparable, since there's no defined order
  to the encoded list (so two strings could be generated that are
  encoded differently but decode to the same list of tuples, just in a
  different order).

Another aspect to this is that the changes feed is not totally
  ordered. For a given shard it is totally ordered (a shard being
  identical to a pre 2.0 database with an integer sequence), couchdb
  doesn't shuffle that output (though correctness of replication would
  be retained if it did). A clustered database is comprised of several
  shards, though (the 'q' value, defaulting to 4 iirc). The clustered
  changes feed combines those separate changes feed into a single one,
  but makes no effort to impose a total order over that. We don't do it
  because it would be expensive and unnecessary.

The solution if you need to listen on a _changes feed and then restart
from where you left off later:

The algorithm for correctly consuming the changes feed is:

read /dbname/_changes

process each row idempotently

periodically (every X seconds or every X rows) store the "seq" value of the last row you processed

If you ever crash, or if you weren't using continuous=true, you can do
  this same procedure again but modified in step 1;

revised 1. read /dbname/_changes?since=X

where X is the value you saved in step 3. If you're not using
  continuous mode then you could just record the "last_seq" value at the
  end of consuming the non-continuous response. You run the risk of
  reprocessing a lot more items, though.

With this scheme (which the replicator and all indexers follow), you
  don't care if the results come out of order, you don't need to compare
  any two seq values.

You do need to ensure you can correctly process the same change
  multiple times. For an example of that, consider the replicator, when
  it sees a row from a changes feed it asks the target database if it
  contains the _id and _rev values from that row. If it does, the
  replicator moves on to the next row. If it doesn't, it tries to write
  the document in that row to the target database. In the event of a
  crash, and therefore a call to _changes with a seq value from before
  processing that row, it will ask the target database if it has the
  _id/_rev again, only this time the target will say yes.

Body:
I’m digging deeper into CouchDB 2 and I’m finding some unexpected ordering with sequence numbers. In one case, I found that an early change in a _changes feed has the sequence number

99-g1AAAAI-eJyd0EsOgjAQBuAGiI-dN9C9LmrBwqzkJtrSNkgQV6z1JnoTvYneBEvbhA0aMU1mkj6-_NMSITTJfYFm2anOcsFT10mpTzyG-LxpmiL32eqoN8aEAcWE9dz_jPCFrnzrHGQchiFM4kSgaV0JqQ6VFF-AtAV2DggMgCEGxrNhQfatc3bOyDiKUalg2EBVoCu66KapazcUh41e69-GssjNIvcWWRokk2oNofwj0MNazy4QFURhGQ0J9LKI-SHPIBHEgiak51nxBhxnrRk

The last sequence number in my _changes feed, for the same DB, is

228-g1AAAAJFeJyd0EkOgjAUBuAGTJCdN9AjlIKFruQm2jFAEFes9SZ6E72J3gQ7JW7QCGnyXtLhy-vfAgCWVSjAip96XglW-o5afRJQwNbDMDRVSOuj3ogQJRgiOnL_O8I2urKdd4B1KCRpkRcCxH0npKo7KX4ApQH2HogsAElOKOPTBjkY5-yd2DqKYqnItA91C13BRTdNXY0VWouRrV7JDOvmrLuxlLW4VAlJ5Qzr4aznJ2wskIIy-y9sh7wcYoMKLJKRXOACjTxr3uHcsBE

In a browser console, the following is false

'228-g1AAAAJFeJyd0EkOgjAUBuAGTJCdN9AjlIKFruQm2jFAEFes9SZ6E72J3gQ7JW7QCGnyXtLhy-vfAgCWVSjAip96XglW-o5afRJQwNbDMDRVSOuj3ogQJRgiOnL_O8I2urKdd4B1KCRpkRcCxH0npKo7KX4ApQH2HogsAElOKOPTBjkY5-yd2DqKYqnItA91C13BRTdNXY0VWouRrV7JDOvmrLuxlLW4VAlJ5Qzr4aznJ2wskIIy-y9sh7wcYoMKLJKRXOACjTxr3uHcsBE' > '99-g1AAAAI-eJyd0EsOgjAQBuAGiI-dN9C9LmrBwqzkJtrSNkgQV6z1JnoTvYneBEvbhA0aMU1mkj6-_NMSITTJfYFm2anOcsFT10mpTzyG-LxpmiL32eqoN8aEAcWE9dz_jPCFrnzrHGQchiFM4kSgaV0JqQ6VFF-AtAV2DggMgCEGxrNhQfatc3bOyDiKUalg2EBVoCu66KapazcUh41e69-GssjNIvcWWRokk2oNofwj0MNazy4QFURhGQ0J9LKI-SHPIBHEgiak51nxBhxnrRk'

Is this a bug or do I need to use some other method to compare sequence numbers?

In looking at the other sequence numbers in my _changes feed, it looks like they are generally ordered as I would expect, but in this case it appears that when the first number, e.g. 99, jumps from 2 digits to 3 digits, the ordering breaks. If you boil this down to a simple string comparison example, you can see that '228' > '99' => false


问:
how to send events to multiple trackers in google analytics without two send calls (analytics.js)
According to google's documentation for the new analytics.js - you can set up multiple trackers, and send events to them by explicitly mentioning the trackers by name in separate send calls:

https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#multipletrackers

```<code>ga('create', 'UA-XXXX-Y');
ga('create', 'UA-12345-6', {'name': 'newTracker'});  // New tracker.
ga('send', 'pageview');
ga('newTracker.send', 'pageview'); // Send page view for new tracker.'
</code>```

I'm wondering if there's a way to send one event to both trackers without having to write two separate send calls for every event, or even if there is a way to send using one send call and a comma delineated list of trackers or something. Anybody know?

答:
Based on Mike's answer and it works with GA Universal.</p>

```<code>function multiSend() {
  var trackers = ga.getAll();
  for (var i = 0; i < trackers.length; i++) {
    tracker=trackers[i].get('name')+'.send';
    argum = Array.prototype.slice.call(arguments);
    argum.unshift(tracker);
    ga.apply(window, argum);
  }
}
</code>```

Body:
According to google's documentation for the new analytics.js - you can set up multiple trackers, and send events to them by explicitly mentioning the trackers by name in separate send calls:

https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#multipletrackers

ga('create', 'UA-XXXX-Y');
ga('create', 'UA-12345-6', {'name': 'newTracker'});  // New tracker.
ga('send', 'pageview');
ga('newTracker.send', 'pageview'); // Send page view for new tracker.'

I'm wondering if there's a way to send one event to both trackers without having to write two separate send calls for every event, or even if there is a way to send using one send call and a comma delineated list of trackers or something. Anybody know?

Body:
Based on Mike's answer and it works with GA Universal.

function multiSend() {
  var trackers = ga.getAll();
  for (var i = 0; i < trackers.length; i++) {
    tracker=trackers[i].get('name')+'.send';
    argum = Array.prototype.slice.call(arguments);
    argum.unshift(tracker);
    ga.apply(window, argum);
  }
}


问:
GNU make many output files from single dependency which might match others
I tried looking for answers to this question, so I apologize in advance if this is a duplicate of a question I didn't find. Also sorry that I cannot directly provide the code that I am working with (it would require a lot of environmental dependencies, anyway).

I have a sequence of actions, which all depend on the success of the previous actions, and also don't need to be repeated unless they are out of date. A make solution seemed like the proper one. I've come up with a solution that does almost all of it. Here is the sequence of steps I am trying to replicate, with the output of each step listed below its input:

ZIP file

extract to package/

package/directory/*.comp

execute uncomp.py to create a .uncomp file from a .comp file

Everything works fine up to this point

package/directory/*.uncomp

For *.uncomp files, execute script1 to produce a .html file

For *_ext.uncomp files, execute script2 to produce numbered *_ext.##.png file(s)

Multiple numbered files (_ext.0.png, _ext.1.png, _ext.2.png) are possible, and may not be present at the time make is run. However, make should know that they are the output of the previous step, and only run this recipe if these files (a) don't exist or (b) any are older than the *_ext.uncomp file.

I have put together a Makefile which does almost what I'm looking for, except that it delegates all of the last portion (numbered files) to a shell script which I could program to look at file times, but that defeats the purpose of using make in the first place, in my opinion.

Environment

Debian 8.8 (x86)

```<code>GNU Make 4.0
Built for x86_64-pc-linux-gnu
</code>```

My Question

What rules and recipes can I use to inform GNU make of the relationship between the *_ext.uncomp files and the _ext.##.png files so that those recipes only get executed as necessary (and say 'Target is up-to-date' if all .png files are at least as new as the _ext.uncomp file), that won't also apply to the *.uncomp files, and that will still work of there are no .png files in the output?

I will also need to indicate the relationship between non-_ext files and their corresponding HTML counterparts. So that script1 only gets executed when the HTML file is out of date or doesn't exist. This recipe/rule should not pay attention to _ext.uncomp files.

Any other advice on my Makefile would also be appreciated, because I am not overly familiar with it.

Generalized contents of my current Makefile

```<code>.PHONY : all
all : package package/directory/*.uncomp
    ./process $^

%.comp.uncomp : %.comp package
    python uncomp.py $<

package : *.zip
    rm -rf package/
    unzip *.zip -d package/
</code>```

Contents of the process script

This script should no longer exist if all the goals of the question are met (make will handle everything). It works great, but it always processes .uncomp files no matter what, even if the output from them already exists and is newer than the source.

```<code>#!/bin/bash

if [ $# -lt 2 ]; then
    echo "$0 expects at least 2 arguments"
    exit 1
fi

# Discard the first agrument, it's always 'package'
shift

# Iterate over each of the remaining arguments
while [ $# -gt 0 ]; do
    if [[ $1 == *_ext.uncomp ]] ; then
        python script2 $1
    elif [[ $1 == *.uncomp ]] ; then
        python script1 $1
    else
        echo "Warning: Unknown file type: $1"
    fi
    shift
done
</code>```

答:
I learned a lot about GNU make trying to get this to work. I discovered that the solution to my problem was in not overthinking it.

The most important realization was that I didn't need make to track all of the numbered output files, but just the first one (if the first one is out of date or missing, they all will be, and they all get re-extracted by the script, so a 1:1 relationship was all I needed to indicate there).

I found out that GNU make 3.82 and later uses "shortest stem first" order instead of definition order when matching pattern rules. To make my file compatible with both versions, I made sure to define the most specific stems first.

After that it was a matter of setting up some implicit rules, and just telling make what to expect to be able to find—the concept is a little backwards to my way of thinking which is why I had some trouble at first (look for this file that doesn't exist yet; now, here's a way to make it from a file that does exist). The end result, fully functional:

```<code>PACKAGE      := package
COMP         := .comp
UNCOMP       := .comp.uncomp
PNG0         := .comp.0.png
TXT          := .comp.txt
SUFFIX       := _ext

COMPFILES     = $(wildcard $(PACKAGE)/subdir/*$(COMP))
UNCOMPFILES   = $(COMPFILES:$(COMP)=$(UNCOMP))
SUFFIXFILES   = $(filter %$(SUFFIX)$(UNCOMP),$(UNCOMPFILES))
PNGFILES      = $(SUFFIXFILES:$(UNCOMP)=$(PNG0))
NOSUFFIXFILES = $(filter-out %$(SUFFIX)$(UNCOMP),$(UNCOMPFILES))
TXTFILES      = $(NOSUFFIXFILES:$(UNCOMP)=$(TXT))

.PHONY : all
all : pngs txts htaccess

.PHONY : txts
txts : $(TXTFILES)

.PHONY : pngs
pngs : $(PNGFILES)

.PHONY : uncomp
uncomp : $(UNCOMPFILES)
    make pngs
    make txts

.PHONY : htaccess
htaccess : $(PACKAGE)/.htaccess

%$(SUFFIX)$(PNG0) : %$(SUFFIX)$(UNCOMP)
    @# Ignore failures when extracting PNG files
    -python script1.py $<

%$(TXT) : %$(UNCOMP)
    @# Ignore failures when dumping TXT files
    -python script2.py $< > $@

%$(UNCOMP) : %$(COMP)
    @# Ignore decompression failure
    -python uncomp.py $<

$(PACKAGE)/.htaccess : .htaccess | $(PACKAGE)
    cp .htaccess $(PACKAGE)/

$(PACKAGE) : *.zip
    rm -rf $(PACKAGE)/
    unzip *.zip -d $(PACKAGE)/
    make uncomp

.PHONY : clean
clean :
    rm -rf $(PACKAGE)/
</code>```

Body:
I tried looking for answers to this question, so I apologize in advance if this is a duplicate of a question I didn't find. Also sorry that I cannot directly provide the code that I am working with (it would require a lot of environmental dependencies, anyway).

I have a sequence of actions, which all depend on the success of the previous actions, and also don't need to be repeated unless they are out of date. A make solution seemed like the proper one. I've come up with a solution that does almost all of it. Here is the sequence of steps I am trying to replicate, with the output of each step listed below its input:

ZIP file

extract to package/

package/directory/*.comp

execute uncomp.py to create a .uncomp file from a .comp file

Everything works fine up to this point

package/directory/*.uncomp

For *.uncomp files, execute script1 to produce a .html file

For *_ext.uncomp files, execute script2 to produce numbered *_ext.##.png file(s)

Multiple numbered files (_ext.0.png, _ext.1.png, _ext.2.png) are possible, and may not be present at the time make is run. However, make should know that they are the output of the previous step, and only run this recipe if these files (a) don't exist or (b) any are older than the *_ext.uncomp file.

I have put together a Makefile which does almost what I'm looking for, except that it delegates all of the last portion (numbered files) to a shell script which I could program to look at file times, but that defeats the purpose of using make in the first place, in my opinion.

Environment

Debian 8.8 (x86)

GNU Make 4.0
Built for x86_64-pc-linux-gnu

My Question

What rules and recipes can I use to inform GNU make of the relationship between the *_ext.uncomp files and the _ext.##.png files so that those recipes only get executed as necessary (and say 'Target is up-to-date' if all .png files are at least as new as the _ext.uncomp file), that won't also apply to the *.uncomp files, and that will still work of there are no .png files in the output?

I will also need to indicate the relationship between non-_ext files and their corresponding HTML counterparts. So that script1 only gets executed when the HTML file is out of date or doesn't exist. This recipe/rule should not pay attention to _ext.uncomp files.

Any other advice on my Makefile would also be appreciated, because I am not overly familiar with it.

Generalized contents of my current Makefile

.PHONY : all
all : package package/directory/*.uncomp
    ./process $^

%.comp.uncomp : %.comp package
    python uncomp.py $<

package : *.zip
    rm -rf package/
    unzip *.zip -d package/

Contents of the process script

This script should no longer exist if all the goals of the question are met (make will handle everything). It works great, but it always processes .uncomp files no matter what, even if the output from them already exists and is newer than the source.

#!/bin/bash

if [ $# -lt 2 ]; then
    echo "$0 expects at least 2 arguments"
    exit 1
fi

# Discard the first agrument, it's always 'package'
shift

# Iterate over each of the remaining arguments
while [ $# -gt 0 ]; do
    if [[ $1 == *_ext.uncomp ]] ; then
        python script2 $1
    elif [[ $1 == *.uncomp ]] ; then
        python script1 $1
    else
        echo "Warning: Unknown file type: $1"
    fi
    shift
done

Body:
I learned a lot about GNU make trying to get this to work. I discovered that the solution to my problem was in not overthinking it.

The most important realization was that I didn't need make to track all of the numbered output files, but just the first one (if the first one is out of date or missing, they all will be, and they all get re-extracted by the script, so a 1:1 relationship was all I needed to indicate there).

I found out that GNU make 3.82 and later uses "shortest stem first" order instead of definition order when matching pattern rules. To make my file compatible with both versions, I made sure to define the most specific stems first.

After that it was a matter of setting up some implicit rules, and just telling make what to expect to be able to find—the concept is a little backwards to my way of thinking which is why I had some trouble at first (look for this file that doesn't exist yet; now, here's a way to make it from a file that does exist). The end result, fully functional:

PACKAGE      := package
COMP         := .comp
UNCOMP       := .comp.uncomp
PNG0         := .comp.0.png
TXT          := .comp.txt
SUFFIX       := _ext

COMPFILES     = $(wildcard $(PACKAGE)/subdir/*$(COMP))
UNCOMPFILES   = $(COMPFILES:$(COMP)=$(UNCOMP))
SUFFIXFILES   = $(filter %$(SUFFIX)$(UNCOMP),$(UNCOMPFILES))
PNGFILES      = $(SUFFIXFILES:$(UNCOMP)=$(PNG0))
NOSUFFIXFILES = $(filter-out %$(SUFFIX)$(UNCOMP),$(UNCOMPFILES))
TXTFILES      = $(NOSUFFIXFILES:$(UNCOMP)=$(TXT))

.PHONY : all
all : pngs txts htaccess

.PHONY : txts
txts : $(TXTFILES)

.PHONY : pngs
pngs : $(PNGFILES)

.PHONY : uncomp
uncomp : $(UNCOMPFILES)
    make pngs
    make txts

.PHONY : htaccess
htaccess : $(PACKAGE)/.htaccess

%$(SUFFIX)$(PNG0) : %$(SUFFIX)$(UNCOMP)
    @# Ignore failures when extracting PNG files
    -python script1.py $<

%$(TXT) : %$(UNCOMP)
    @# Ignore failures when dumping TXT files
    -python script2.py $< > $@

%$(UNCOMP) : %$(COMP)
    @# Ignore decompression failure
    -python uncomp.py $<

$(PACKAGE)/.htaccess : .htaccess | $(PACKAGE)
    cp .htaccess $(PACKAGE)/

$(PACKAGE) : *.zip
    rm -rf $(PACKAGE)/
    unzip *.zip -d $(PACKAGE)/
    make uncomp

.PHONY : clean
clean :
    rm -rf $(PACKAGE)/


问:
C# Inheritance: How to invoke the base class constructor when i call the derived class constructor
I am trying to figure out how to invoke a base class constructor when I call the derived class constructor.

I have a class called "AdditionalAttachment" which is inherited from System.Net.Mail.Attachment.I have added 2 more properties to my new class so that i can have all the properties of existing Attachment class with my new properties

```<code>public class AdditionalAttachment: Attachment
{
   [DataMember]
   public string AttachmentURL
   {
       set;
       get;
   }
   [DataMember]
   public string DisplayName
   {
       set;
       get;
   }
}
</code>```

Earlier i used to create constructor like

//objMs is a MemoryStream object

```<code>Attachment objAttachment = new Attachment(objMs, "somename.pdf")
</code>```

I am wondering how can I create the same kind of constructor to my class which will do the same thing as of the above constructor of the base class

答:
You can write a constructor that calls the class base constructor:</p>

```<code>public AdditionalAttachment(MemoryStream objMs, string filename)
    : base(objMs, filename)
{
}
</code>```

Body:
I am trying to figure out how to invoke a base class constructor when I call the derived class constructor.

I have a class called "AdditionalAttachment" which is inherited from System.Net.Mail.Attachment.I have added 2 more properties to my new class so that i can have all the properties of existing Attachment class with my new properties

public class AdditionalAttachment: Attachment
{
   [DataMember]
   public string AttachmentURL
   {
       set;
       get;
   }
   [DataMember]
   public string DisplayName
   {
       set;
       get;
   }
}

Earlier i used to create constructor like

//objMs is a MemoryStream object

Attachment objAttachment = new Attachment(objMs, "somename.pdf")

I am wondering how can I create the same kind of constructor to my class which will do the same thing as of the above constructor of the base class

Body:
You can write a constructor that calls the class base constructor:

public AdditionalAttachment(MemoryStream objMs, string filename)
    : base(objMs, filename)
{
}

ContentLicense: CC BY-SA 2.5


问:
Will if / else if / else become an expressions in typescript / javascript at some point?
I really like this feature in Kotlin:

In Kotlin, if is an expression, i.e. it returns a value.

```<code>// As expression
val max = if (a > b) a else b
</code>```

(from https://kotlinlang.org/docs/reference/control-flow.html)

Is this also planned for typescript / javascript?

Update:

In reply to the ternary operator suggestions, of course I also mean cases with else if:

```<code>val bla = if ( 5 == 6) {
    7
} else if (5 == 7) {
    8
} else {
    9
}

println(bla) // prints 9
</code>```

答:
Is this also planned for typescript / javascript?

No. Statements vs. Only Expressions is a pretty hard fork in language design and will not change without breaking existing code so will not happen.

Simple example:

```<code>var foo = 123;
function inc(){
  foo = foo + 1;
}
</code>```

Going down the expression route would change the return of this function from undefined to foo which can drastically break existing code for more complex functions.

Body:
I really like this feature in Kotlin:

In Kotlin, if is an expression, i.e. it returns a value.

// As expression
val max = if (a > b) a else b

(from https://kotlinlang.org/docs/reference/control-flow.html)

Is this also planned for typescript / javascript?

Update:

In reply to the ternary operator suggestions, of course I also mean cases with else if:

val bla = if ( 5 == 6) {
    7
} else if (5 == 7) {
    8
} else {
    9
}

println(bla) // prints 9

Body:
Is this also planned for typescript / javascript?

No. Statements vs. Only Expressions is a pretty hard fork in language design and will not change without breaking existing code so will not happen.

Simple example:

var foo = 123;
function inc(){
  foo = foo + 1;
}

Going down the expression route would change the return of this function from undefined to foo which can drastically break existing code for more complex functions.


问:
How do I only copy the files changed
```<code>gulp.task('scripts:source', function () {
        gulp.src('./src/admin/assets/scripts/**/*.js').pipe(gulp.dest(adminPath + '/assets/scripts'));
    });
</code>```

and then I have a watch setup on it

```<code>gulp.watch('./src/admin/assets/scripts/**/*.js', ['scripts:source']);
</code>```

This works and does it copy but it copies all of the files which is an issue since I have 100s of them and the development experience becomes a bit slow. Is there a way to only copy the files which have changed or do I have to live with this?

答:
Have you looked at gulp-newer?

A Gulp plugin for passing through only those source files that are newer than corresponding destination files.

Title: How do I only copy the files changed

Body:
gulp.task('scripts:source', function () {
        gulp.src('./src/admin/assets/scripts/**/*.js').pipe(gulp.dest(adminPath + '/assets/scripts'));
    });

and then I have a watch setup on it

gulp.watch('./src/admin/assets/scripts/**/*.js', ['scripts:source']);

This works and does it copy but it copies all of the files which is an issue since I have 100s of them and the development experience becomes a bit slow. Is there a way to only copy the files which have changed or do I have to live with this?


问:
galleria javascript crops topand bootom of images when viewing in Firefox Chrome and IE
galleria javascript crops top and base of images when viewing in Firefox Chrome and IE

However in Safari this issue does not exist.

Please see the issue here
http://galleria.aino.se/media/galleria/src/themes/fullscreen/fullscreen-demo.html

no compare the squirrel image with its original
right click on any image and you will see how the script is not displaying the the full image.

We are using galleria. js full screen for a wordpress theme and all our images are the same size so there is no height issue the images we will use are 1600x900

If any one can help please advise. We need to display the entire image.

Thanks all.

答:
I believe that's how galleria is supposed to behave. In full screen mode it fills the screen, so it will crop the top or sides, whichever extends beyond the aspect ratio of the browser window.

In full-screen mode, if you have a wide browser window, it'll crop the top/bottom. If you resize the browser window to portrait orientation, it'll crop the left/right.


问:
would like to restrict oracle spatial shapes to simple polygons
I'm rather new to oracle spatial. I'd like to restrict shapes to simple polygons. multiple polygons are ok. donuts are not. crossed edges are not. and all shapes must be separated by a tolerance.

SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT seems like a good place to start... but would appreciate any further insight on how to determine that I do not have donuts.

any insight appreciated.

答:
found what I needed here:
https://spatialdbadvisor.com/oracle_spatial_tips_tricks/89/sdo_utilgetnumrings-an-alternative

with additional information from the documentation:
https://docs.oracle.com/cd/B28359_01/appdev.111/b28400/sdo_objrelschema.htm#SPATL020


问:
How to insert an empty row in every three rows displayed in a table (ui:repeat)
I have a bootstrap table with more than 50 rows, what i want to achieve is to have
an empty row that will act as a divider in every three rows being displayed.

this is my xhtml code.

```<code><tbody>
    <ui:repeat var="person" value="#{myBean.listOfPersons}">
        <tr>
            <td><h:outputText value="#{person.firstName}"/> </td>
            <td><h:outputText value="#{person.lastName}"/> </td>
            <td><h:outputText value="#{person.age}"/> </td>
        </tr>
    </ui:repeat>
</tbody>
</code>```

Thanks!

答:
Try the code below:

```<code><tbody>
    <ui:repeat var="person" value="#{myBean.listOfPersons}" varStatus="status">
        <tr>
            <td><h:outputText value="#{person.firstName}"/> </td>
            <td><h:outputText value="#{person.lastName}"/> </td>
            <td><h:outputText value="#{person.age}"/> </td>
        </tr>

        <ui:fragment rendered="#{(status.index + 1) % 3 eq 0}">
            <tr style="height:30px;">
                <td colspan="3"></td>
            </tr>
        </ui:fragment>

    </ui:repeat>
</tbody>
</code>```

Use the varStatus attribute to get the index of the iteration #{status.index}.

The rendered attribute determine whether the component will be rendered or not.

Body:
I have a bootstrap table with more than 50 rows, what i want to achieve is to have
an empty row that will act as a divider in every three rows being displayed.

this is my xhtml code.

    <ui:repeat var="person" value="#{myBean.listOfPersons}">

            <h:outputText value="#{person.firstName}"/>
            <h:outputText value="#{person.lastName}"/>
            <h:outputText value="#{person.age}"/>

    </ui:repeat>

Thanks!

Body:
Try the code below:

<tbody>
    <ui:repeat var="person" value="#{myBean.listOfPersons}" varStatus="status">
        <tr>
            <td><h:outputText value="#{person.firstName}"/> </td>
            <td><h:outputText value="#{person.lastName}"/> </td>
            <td><h:outputText value="#{person.age}"/> </td>
        </tr>

        <ui:fragment rendered="#{(status.index + 1) % 3 eq 0}">
            <tr style="height:30px;">
                <td colspan="3"></td>
            </tr>
        </ui:fragment>

    </ui:repeat>
</tbody>

Use the varStatus attribute to get the index of the iteration #{status.index}.

The rendered attribute determine whether the component will be rendered or not.


问:
Qt Quick controls 2.0 for embedded device
My long term goal is to make HCI development for embedded devices, and by embedded I really mean it, not phone devices.

I've been working on Qt Widgets for a month now, avoiding Qt Quick for some reasons (I feared that QML code wasn't optimize), but yesterday I have watched this video :Youtube

The speaker says at the end : "If you're making an embedded product these days, use Qt Quick, especially now in 5.8. There's no excuse not to use Qt Quick"

But on the contrary, he explains that for embedded devices we should use c++ code, not JavaScript.

I don't really get it, does it means that I have to create all my objects in c++ code and make my architecture using Qt Quick ?

I don't really get what Qt want us to do. Is it just communication, since they don't want to optimize the old and stable Qt widgets, or is Qt Quick really the solution for embedded devices ?

I personally think that Qt is not the solution for embedded devices, as they keep evolving, changing strategy, and seems not to know where they are going.

I apologize for this non-algorithmic question, and thank you for all your answers.

答:
I can't speak to the developer's intent, nor can I speak for other developers. I can only speak to what I understand, as a developer that has been designing embedded devices for 40 years (sorry for being a number dropper).

C++ or JavaScript? I don't feel that question has too much to do with whether you use QtQuick or not. Sure, you can embed some JaveScript in QML code (with limitations), but you can also use C++ in the same code base (just not embedded in the QML). Then there's Python. Both Qt and QtQuick are programming frameworks, and are somewhat language agnostic.

My perspective is that QtQuick is a good, portable way to create your user-interface code. In my current project (a multi-axis industrial servo-control system) I use QML for the user-interface (with a little JavaScript where needed), C++ for the bulk of the higher level processing (like network control and data-streaming), C and assembly language for the lower levels (those routines executed in uC's and DSP's). QML and C++ interface together nicely, in my opinion.


问:
The translator API changes content of some tags in text/html mode
Using method “TranslateArray” of Microsoft Translator Text API with option “ContentType” mode “text/html”, changes content of some tags extracting part of “important” text out of the tag.
This “changes” seems not justified by syntactic adjustments of the translation.
An example translating from “EN” to “RU”
Fragment of original text:

Download Program Name and discover the comfort of managing advertising campaigns or sending messages to mobiles from your computer.

Fragment of translated text:

Скачать Program Name и откройте для себя удобство управления рекламных кампанийили отправка сообщений на мобильные телефоны с вашего компьютера.

The text “или отправка сообщений на мобильные телефоны с вашего компьютера.” Equivalent of “or sending messages to mobiles from your computer” now is out strong tag.
There is any way to force the api to respect the tags?

答:
there is only one way to influence the handling of tags, which is using contentType text/html vs. text/plain.
The words of the translation may be in very different order than the original, and the tags move around with the words they are attached to. The word the tag is attached to may appear a bit random occasionally. </p>

<p>In this particular case you get a better tag placement when using Microsoft Translator's neural decoder, invoked by &category=generalnn.
But at this time you will not want to switch to neural for heavily tagged content. As of right now, the tag placement is worse in neural, in most cases other than yours. </p>

Body:
there is only one way to influence the handling of tags, which is using contentType text/html vs. text/plain.
The words of the translation may be in very different order than the original, and the tags move around with the words they are attached to. The word the tag is attached to may appear a bit random occasionally.

In this particular case you get a better tag placement when using Microsoft Translator's neural decoder, invoked by &category=generalnn.
But at this time you will not want to switch to neural for heavily tagged content. As of right now, the tag placement is worse in neural, in most cases other than yours.


问:
Export variable from within while loop
I want to export a variable from within a loop. I was not able to do it. I am not sure what is missing here.

Any suggestion would be great help

```<code>var="ahs tcs amq tos"

for i in ${var}
do
   ${i}_log="/var/tmp/pmp_${i}_log"
   #export ${i}_log
done
</code>```

答:
This can be done in one line without a loop

```<code>printf '%s\n' {ahs,tcs,amq,tos} | xargs -I {} bash -c 'export {}_log="/var/tmp/pmp_{}_log"; echo {}_log=${{}_log}'
</code>```

or with a loop

```<code>#!/bin/bash
for i in {ahs,tcs,amq,tos}; do
    #export
    export "${i}_log=/var/tmp/pmp_${i}_log";

    #test
    bash -c 'echo '"${i}_log"'='"\$${i}_log"; done
done
</code>```

The reason  ${i}_log="/var/tmp/pmp_${i}_log" failed is because ${i}_log is unquoted and the syntax for exporting is export somevar=somedefintion. In order to dynamically generate the variable name, surround the statement in quotes so that it gets interpolated. ie. export "${dynamic}_var=${dynamic}_definition"

see http://wiki.bash-hackers.org/syntax/quoting

Title: Export variable from within while loop

Body:
I want to export a variable from within a loop. I was not able to do it. I am not sure what is missing here.

Any suggestion would be great help

var="ahs tcs amq tos"

for i in ${var}
do
   ${i}_log="/var/tmp/pmp_${i}_log"
   #export ${i}_log
done

Body:
This can be done in one line without a loop

printf '%s\n' {ahs,tcs,amq,tos} | xargs -I {} bash -c 'export {}_log="/var/tmp/pmp_{}_log"; echo {}_log=${{}_log}'

or with a loop

#!/bin/bash
for i in {ahs,tcs,amq,tos}; do
    #export
    export "${i}_log=/var/tmp/pmp_${i}_log";

    #test
    bash -c 'echo '"${i}_log"'='"\$${i}_log"; done
done

The reason  ${i}_log="/var/tmp/pmp_${i}_log" failed is because ${i}_log is unquoted and the syntax for exporting is export somevar=somedefintion. In order to dynamically generate the variable name, surround the statement in quotes so that it gets interpolated. ie. export "${dynamic}_var=${dynamic}_definition"

see http://wiki.bash-hackers.org/syntax/quoting


问:
Why are my instances changing?
I'm making a class of polynomial objects, represented by dictionaries:

3*x^2+x+2 == {2:3, 1:1, 0:2}

This is the part of my code that's relevant for the question:

```<code>class Sparse_polynomial():
    def __init__(self, coeffs_dict):
        self.coeffs_dict = coeffs_dict

    def __repr__(self):
        terms = [" + ("+str(self.coeffs_dict[k])+"*x^" + str(k)+")" \
                 for k in sorted(self.coeffs_dict.keys(), reverse=True)]
        terms = "".join(terms)
        return terms[3:]

    def __neg__(self):
        neg_pol= self.coeffs_dict
        for key in self.coeffs_dict:
            neg_pol[key]= -self.coeffs_dict[key]
        return Sparse_polynomial(neg_pol)
</code>```

Whenever I try to use the __neg__ method, the original object changes.  For example:

```<code>>>> p1= Sparse_polynomial({1:3,5:1})
>>> p1
(1*x^5) + (3*x^1)
>>> -p1
(-1*x^5) + (-3*x^1)
>>> p1
(-1*x^5) + (-3*x^1)
>>>
</code>```

I really can't understand why the original p1 changes. I made no direct changes to it, only accessed its fields.

Can anyone clarify so I can fix this?

答:
This is not a copy, just a reference to the original dictionary:

```<code>neg_pol = self.coeffs_dict
</code>```

You want a copy, so you can mutate it without messing with the original:

```<code>neg_pol = self.coeffs_dict.copy()
</code>```

You may want to check "How can I assign by value in python" for clues on how to copy other mutable objects - Python is not very consistent on how to copy builtins, for example the list type has no copy method and most people use slicing notation in order to copy a list:

```<code>new_list = old_list[:]
</code>```

As MSeifert suggested, dict comprehensions are a good way to generate a mutated copy:

```<code>>>> original_dict = {'a': 2, 'b': 3}
>>> square_dict = {k + "²": v * 2 for k, v in original_dict.items()}
>>> double_dict
{'a²': 4, 'b²': 9}
>>> original_dict
{'a': 1, 'b': 2}
</code>```

Title: Why are my instances changing?

Body:
I'm making a class of polynomial objects, represented by dictionaries:

3*x^2+x+2 == {2:3, 1:1, 0:2}

This is the part of my code that's relevant for the question:

class Sparse_polynomial():
    def __init__(self, coeffs_dict):
        self.coeffs_dict = coeffs_dict

    def __repr__(self):
        terms = [" + ("+str(self.coeffs_dict[k])+"*x^" + str(k)+")" \
                 for k in sorted(self.coeffs_dict.keys(), reverse=True)]
        terms = "".join(terms)
        return terms[3:]

    def __neg__(self):
        neg_pol= self.coeffs_dict
        for key in self.coeffs_dict:
            neg_pol[key]= -self.coeffs_dict[key]
        return Sparse_polynomial(neg_pol)

Whenever I try to use the __neg__ method, the original object changes.  For example:

>>> p1= Sparse_polynomial({1:3,5:1})
>>> p1
(1*x^5) + (3*x^1)
>>> -p1
(-1*x^5) + (-3*x^1)
>>> p1
(-1*x^5) + (-3*x^1)
>>>

I really can't understand why the original p1 changes. I made no direct changes to it, only accessed its fields.

Can anyone clarify so I can fix this?

Body:
This is not a copy, just a reference to the original dictionary:

neg_pol = self.coeffs_dict

You want a copy, so you can mutate it without messing with the original:

neg_pol = self.coeffs_dict.copy()

You may want to check "How can I assign by value in python" for clues on how to copy other mutable objects - Python is not very consistent on how to copy builtins, for example the list type has no copy method and most people use slicing notation in order to copy a list:

new_list = old_list[:]

As MSeifert suggested, dict comprehensions are a good way to generate a mutated copy:

>>> original_dict = {'a': 2, 'b': 3}
>>> square_dict = {k + "²": v * 2 for k, v in original_dict.items()}
>>> double_dict
{'a²': 4, 'b²': 9}
>>> original_dict
{'a': 1, 'b': 2}


答:
I made no direct changes to it, only accessed it's field.

That's not true: look at your code ...

```<code>def __neg__(self):
    neg_pol= self.coeffs_dict
    for key in self.coeffs_dict:
        neg_pol[key]= -self.coeffs_dict[key]
</code>```

You grabbed a reference to the coefficients dictionary and negated every member.  This is not a copy; it's a reference to the original.

If you're trying to return a separate dictionary, then use one of the several copy methods available.  A popular one is copy from the class itself:

```<code>neg_pol = self.coeffs_dict.copy()
</code>```

To check the "handle" of an item, use the id method.  For instance:

```<code>print id(self.coeffs_dict), id(neg_pol)
</code>```

This shows readily that the two variable names refer to the same object.

Title: Why are my instances changing?

Body:
I made no direct changes to it, only accessed it's field.

That's not true: look at your code ...

def __neg__(self):
    neg_pol= self.coeffs_dict
    for key in self.coeffs_dict:
        neg_pol[key]= -self.coeffs_dict[key]

You grabbed a reference to the coefficients dictionary and negated every member.  This is not a copy; it's a reference to the original.

If you're trying to return a separate dictionary, then use one of the several copy methods available.  A popular one is copy from the class itself:

neg_pol = self.coeffs_dict.copy()

To check the "handle" of an item, use the id method.  For instance:

print id(self.coeffs_dict), id(neg_pol)

This shows readily that the two variable names refer to the same object.


问:
Attaching a disconnected object to an NHibernate session; best practice?
My repository works in a UnitOfWork model; all operations, whether retrieval or persistence, must be performed within the scope of an IDisposable UnitOfWork token object, which behind the scenes is associated with a Session that performs the work requested. So, the basic pattern is:

```<code>using (var uow = repo.BeginUnitOfWork())
{
   try
   {
      //DB operations here; all repo methods require passing in uow.
      ...
      repo.CommitUnitOfWork(uow);
   }
   catch(Exception)
   {
      repo.RollbackUnitOfWork(uow);
      throw;
   }
}
</code>```

I've also implemented some wrapper methods that allow you to specify a lambda or delegate that will be executed in this framework, relieving the need to implement all this scaffolding every time.

The problem I'm having is that using this model, code must "know" what the user needs, and eager-load it using NHUtil.Initialize() within the UnitOfWork. Once the UOW is disposed at the end of the using block, the Session associated with any PersistentBags is closed, and so they cannot be evaluated. As eager-loading everything up front is not always feasible and kind of defeats the purpose of a lazy-loading ORM, I am implementing an Attach() method.

Here's the question; In the absence of a built-in ISession.Attach() method, there are three methods I've seen recommended to associate an object with a new Session. Which of them is the best practice to get the job done?

A:

```<code>if(!Session.Contains(domainObject))
    Session.Update(domainObject);
</code>```

B:

```<code>Session.Merge(domainObject);
</code>```

C:

```<code>Session.Lock(domainObject, LockMode.None);
</code>```

答:
D: None of the above. Effectively disabling lazy-loading by keeping your UOW too short and defeats the purpose of a lazy-loading ORM. The fact that you have to re-associate disconnected objects as normal operations means that your unit of work boundaries are wrong.

Merge, Update, and Lock all have different purposes. If you're stuck with your current architecture then Lock is probably what you want.

Update - associates a changed object

Lock - associates an unchanged object

Merge - if the object exists in the
current session then it is updated
with changes from the merged object,
otherwise it's the same as Lock

Body:
My repository works in a UnitOfWork model; all operations, whether retrieval or persistence, must be performed within the scope of an IDisposable UnitOfWork token object, which behind the scenes is associated with a Session that performs the work requested. So, the basic pattern is:

using (var uow = repo.BeginUnitOfWork())
{
   try
   {
      //DB operations here; all repo methods require passing in uow.
      ...
      repo.CommitUnitOfWork(uow);
   }
   catch(Exception)
   {
      repo.RollbackUnitOfWork(uow);
      throw;
   }
}

I've also implemented some wrapper methods that allow you to specify a lambda or delegate that will be executed in this framework, relieving the need to implement all this scaffolding every time.

The problem I'm having is that using this model, code must "know" what the user needs, and eager-load it using NHUtil.Initialize() within the UnitOfWork. Once the UOW is disposed at the end of the using block, the Session associated with any PersistentBags is closed, and so they cannot be evaluated. As eager-loading everything up front is not always feasible and kind of defeats the purpose of a lazy-loading ORM, I am implementing an Attach() method.

Here's the question; In the absence of a built-in ISession.Attach() method, there are three methods I've seen recommended to associate an object with a new Session. Which of them is the best practice to get the job done?

A:

if(!Session.Contains(domainObject))
    Session.Update(domainObject);

B:

Session.Merge(domainObject);

C:

Session.Lock(domainObject, LockMode.None);


问:
log4j2 configuration logging to file but not to console
My log4j2 version is 2.8

I have the following log4j2.xml in src/main/resources:

```<code><?xml version="1.0" encoding="UTF-8"?>

<Configuration status="WARN" monitorInterval="120">
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout>
                <Pattern>%d{yyyy-MM-dd HH.mm.ss} %5p %c{1}:%L - %m%n</Pattern>
            </PatternLayout>
        </Console>
        <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="${env:CATALINA_HOME:-.}/logs/applicationlogs.log"
                                 filePattern="${env:CATALINA_HOME:-.}/logs/$${date:yyyy-MM}/applicationlogs-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout>
                <Pattern>%d{yyyy-MM-dd HH.mm.ss} %5p %c{1}:%L - %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <OnStartupTriggeringPolicy />
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="50 MB"/>
            </Policies>
        </RollingRandomAccessFile>
    </Appenders>
    <Loggers>
        <AsyncLogger name="com.mypackage" level="trace" includeLocation="true" additivity="false">
            <AppenderRef ref="RollingRandomAccessFile"/>
        </AsyncLogger>
        <AsyncLogger name="org.springframework.jdbc" level="debug" includeLocation="true" additivity="false">
            <AppenderRef ref="RollingRandomAccessFile"/>
        </AsyncLogger>
        <Root level="info" includeLocation="true">
            <AppenderRef ref="STDOUT"/>
            <AppenderRef ref="RollingRandomAccessFile"/>
        </Root>
    </Loggers>
</Configuration>
</code>```

This logs correctly to the file, but nothing appears on Console.

What's wrong here ?

答:
As per answer above, I did this:

```<code><AsyncLogger name="com.mypackage" level="trace" includeLocation="true" additivity="false">
            <AppenderRef ref="RollingRandomAccessFile"/>
        </AsyncLogger>
        <AsyncLogger name="org.springframework.jdbc" level="debug" includeLocation="true" additivity="false">
            <AppenderRef ref="RollingRandomAccessFile"/>
        </AsyncLogger>
        <AsyncLogger name="com.mypackage" level="info" includeLocation="true" additivity="false">
            <AppenderRef ref="STDOUT"/>
        </AsyncLogger>
        <AsyncLogger name="org.springframework.jdbc" level="info" includeLocation="true" additivity="false">
            <AppenderRef ref="STDOUT"/>
        </AsyncLogger>
</code>```

But now, the logs were coming only to console. Log file remained empty.

So, my final solution was:

```<code>           <AsyncLogger name="com.mypackage" level="trace" includeLocation="true" additivity="false">
                <AppenderRef ref="RollingRandomAccessFile"/>
            </AsyncLogger>
            <AsyncLogger name="org.springframework.jdbc" level="debug" includeLocation="true" additivity="false">
                <AppenderRef ref="RollingRandomAccessFile"/>
            </AsyncLogger>
            <AsyncLogger name="com.mypackage" level="info" includeLocation="true" additivity="false">
                <AppenderRef ref="STDOUT"/>
                <AppenderRef ref="RollingRandomAccessFile"/>
            </AsyncLogger>
            <AsyncLogger name="org.springframework.jdbc" level="info" includeLocation="true" additivity="false">
                <AppenderRef ref="STDOUT"/>
                <AppenderRef ref="RollingRandomAccessFile"/>
            </AsyncLogger>
</code>```

This worked as expected.

Body:
My log4j2 version is 2.8

I have the following log4j2.xml in src/main/resources:

<?xml version="1.0" encoding="UTF-8"?>

<Configuration status="WARN" monitorInterval="120">
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout>
                <Pattern>%d{yyyy-MM-dd HH.mm.ss} %5p %c{1}:%L - %m%n</Pattern>
            </PatternLayout>
        </Console>
        <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="${env:CATALINA_HOME:-.}/logs/applicationlogs.log"
                                 filePattern="${env:CATALINA_HOME:-.}/logs/$${date:yyyy-MM}/applicationlogs-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout>
                <Pattern>%d{yyyy-MM-dd HH.mm.ss} %5p %c{1}:%L - %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <OnStartupTriggeringPolicy />
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="50 MB"/>
            </Policies>
        </RollingRandomAccessFile>
    </Appenders>
    <Loggers>
        <AsyncLogger name="com.mypackage" level="trace" includeLocation="true" additivity="false">
            <AppenderRef ref="RollingRandomAccessFile"/>
        </AsyncLogger>
        <AsyncLogger name="org.springframework.jdbc" level="debug" includeLocation="true" additivity="false">
            <AppenderRef ref="RollingRandomAccessFile"/>
        </AsyncLogger>
        <Root level="info" includeLocation="true">
            <AppenderRef ref="STDOUT"/>
            <AppenderRef ref="RollingRandomAccessFile"/>
        </Root>
    </Loggers>
</Configuration>

This logs correctly to the file, but nothing appears on Console.

What's wrong here ?

Body:
As per answer above, I did this:

<AsyncLogger name="com.mypackage" level="trace" includeLocation="true" additivity="false">
            <AppenderRef ref="RollingRandomAccessFile"/>
        </AsyncLogger>
        <AsyncLogger name="org.springframework.jdbc" level="debug" includeLocation="true" additivity="false">
            <AppenderRef ref="RollingRandomAccessFile"/>
        </AsyncLogger>
        <AsyncLogger name="com.mypackage" level="info" includeLocation="true" additivity="false">
            <AppenderRef ref="STDOUT"/>
        </AsyncLogger>
        <AsyncLogger name="org.springframework.jdbc" level="info" includeLocation="true" additivity="false">
            <AppenderRef ref="STDOUT"/>
        </AsyncLogger>

But now, the logs were coming only to console. Log file remained empty.

So, my final solution was:

           <AsyncLogger name="com.mypackage" level="trace" includeLocation="true" additivity="false">
                <AppenderRef ref="RollingRandomAccessFile"/>
            </AsyncLogger>
            <AsyncLogger name="org.springframework.jdbc" level="debug" includeLocation="true" additivity="false">
                <AppenderRef ref="RollingRandomAccessFile"/>
            </AsyncLogger>
            <AsyncLogger name="com.mypackage" level="info" includeLocation="true" additivity="false">
                <AppenderRef ref="STDOUT"/>
                <AppenderRef ref="RollingRandomAccessFile"/>
            </AsyncLogger>
            <AsyncLogger name="org.springframework.jdbc" level="info" includeLocation="true" additivity="false">
                <AppenderRef ref="STDOUT"/>
                <AppenderRef ref="RollingRandomAccessFile"/>
            </AsyncLogger>

This worked as expected.


问:
Is there a way to get multiple Image Extensions, in a link?
```<code><img src="uploads/<?php echo $_SESSION['username']; ?>.jpg" class="img-circle" width="60" <b class="hidden-xs">
</code>```

I am getting a User Image the Link is uploads/admin.jpg or also uploads/?php echo $_SESSION['username'];?>.jpg.

If they upload a .png how do I get it where it will choose the right extension for the Image so If it was a png instead of a JPG it would load the png image instead of the JPG? is there a way?

答:
You have options.

1) You can pre-process images uploaded to you (perhaps using ImageMagick) to force them to the one format you want before saving the file to your server.  This is probably the best solution.

2) You can accept the name of the uploaded file and store it in your database.  Thus, instead of:

"uploads/<?php echo $_SESSION['username']; ?>.jpg"

you would use something like:

"uploads/<?php echo $_SESSION['userimagefilename']; ?>"

The problem with this solution is trust.  Users might not send you a filename that honestly represents the file contents.

3) Another solution is to use exif_imagetype().  This accepts an image, looks at the file contents, and tells you what the image type is (or isn't, in the case of nefarious users).  Combined with image_type_to_mime_type() you have the ability to stream the image as an inline HTML image and forget about what the suffix is.  This is especially handy if you store images in your DB rather than as files on disk, which is a problem when you try to store a lot of images.

4) A final solution is to if-then through a bunch of file_exists() statements.  However, you need to check at least three and should test a dozen file formats.  That's 1-12 disk hits per image.  It's an expensive solution and still doesn't protect you from someone uploading a file that isn't what it's pretending to be or uploading a file that isn't renderable as an image (e.g., .PDF, .DOC, .RTF, etc.).  It's my least favorite solution.

Body:
<img src="uploads/<?php echo $_SESSION['username']; ?>.jpg" class="img-circle" width="60"

I am getting a User Image the Link is uploads/admin.jpg or also uploads/?php echo $_SESSION['username'];?>.jpg.

If they upload a .png how do I get it where it will choose the right extension for the Image so If it was a png instead of a JPG it would load the png image instead of the JPG? is there a way?


问:
Dynamic source code shows in browser on Windows
I'm running Windows 7, and using Google Chrome as my web browser.

This is my code:

```<code>#!/usr/bin/env python
print 'content-type: text/html\n'

print """
<!DOCTYPE html>
  <html>
    <head>
      <title> sample </title>
    </head>

    <body>
"""

print 2 + 3

print """
    </body>
  </html>
"""
</code>```

In Command Prompt, where python results in C:\Python27\python.exe, but according to this post  I should use #!/usr/bin/env python instead.

When I try to run this .py code in my browser, the source code appears instead of just 5.

If someone would provide detailed instructions as to how to properly work this, I would be most grateful.

Thanks!

答:
Okay. So of course it is not possible to run python directly in the browser but you can configure a local server to be able to run CGI scripts. Since you are on windows you could use something like a WAMP.
Try following this tutorial
https://wiki.python.org/moin/CgiScripts</p>

Body:
I'm running Windows 7, and using Google Chrome as my web browser.

This is my code:

#!/usr/bin/env python
print 'content-type: text/html\n'

print """
<!DOCTYPE html>

      <title> sample </title>

"""

print 2 + 3

print """

"""

In Command Prompt, where python results in C:\Python27\python.exe, but according to this post  I should use #!/usr/bin/env python instead.

When I try to run this .py code in my browser, the source code appears instead of just 5.

If someone would provide detailed instructions as to how to properly work this, I would be most grateful.

Thanks!


问:
Call a function in java from C outside of a JNI function (Android)?
I'm trying to call a Java function from my C code using the JNI in Android, but I'm in a somewhat awkward situation.

My C code is being executed outside of a JNI function in a callback that is passed to a library.

Here is an example of the java code

```<code>package com.my.java.package;

class MyClass {
    public function handleData(byte[] data) {
        doSomethingWithThisData(data);
    }
}
</code>```

Here is an example of the C code

```<code>void handleData(uint8_t *data, size_t len) {
    // I need to call handleData in my java
    // class instance from here, but i have
    // no access to a JNIEnv here.

    // I don't think I can create one, since
    // it has to be the same object that's
    // sending JNI calls elsewhere.
}

. . .

myCLibInstance.callback = handleData;
</code>```

Now whenever the C Lib does what it needs to do, it will trigger the callback. But I have no way to send it back to the java class to handle the data.

答:
On some version of the Android NDK, JNI_GetCreatedJavaVMs could be used to get the current VM.. however, the better option is to override JNI_OnLoad and save the VM there. Using either method, once you have the VM, you can attach to the current thread and get call the function..

```<code>extern jint JNI_GetCreatedJavaVMs(JavaVM **vm, jsize size, jsize *size2);

static JavaVM *jvm = NULL;

static jint JNI_OnLoad(JavaVM* vm, void* reserved) {
    jvm = vm;
    JNIEnv *env = NULL;

    if (jvm && (*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_6) == JNI_OK)
    {
        return JNI_VERSION_1_6;
    }
    return -1;
}

JavaVM* getJavaVM() {
    if (jvm)
    {
        return jvm;
    }

    jint num_vms = 0;
    const jint max_vms = 5;
    JavaVM* vms[max_vms] = {0};
    if (JNI_GetCreatedJavaVMs(vms, max_vms, &num_vms) == JNI_OK)
    {
        for (int i = 0; i < num_vms; ++i)
        {
            if (vms[i] != NULL)
            {
                return vms[i];
            }
        }
    }
    return NULL;
}

 void handleData(uint8_t *data, size_t len) {
    JavaVM *jvm = getJavaVM();

    if (jvm)
    {
        JNIEnv *env = NULL;
        if ((*jvm)->AttachCurrentThread(jvm, (void **)&env, NULL)  == JNI_OK)
        {
            if (env)
            {
                //Call function with JNI..
            }

            (*jvm)->DetachCurrentThread(jvm);
        }
    }
}
</code>```

Body:
I'm trying to call a Java function from my C code using the JNI in Android, but I'm in a somewhat awkward situation.

My C code is being executed outside of a JNI function in a callback that is passed to a library.

Here is an example of the java code

package com.my.java.package;

class MyClass {
    public function handleData(byte[] data) {
        doSomethingWithThisData(data);
    }
}

Here is an example of the C code

void handleData(uint8_t *data, size_t len) {
    // I need to call handleData in my java
    // class instance from here, but i have
    // no access to a JNIEnv here.

    // I don't think I can create one, since
    // it has to be the same object that's
    // sending JNI calls elsewhere.
}

. . .

myCLibInstance.callback = handleData;

Now whenever the C Lib does what it needs to do, it will trigger the callback. But I have no way to send it back to the java class to handle the data.

Body:
On some version of the Android NDK, JNI_GetCreatedJavaVMs could be used to get the current VM.. however, the better option is to override JNI_OnLoad and save the VM there. Using either method, once you have the VM, you can attach to the current thread and get call the function..

extern jint JNI_GetCreatedJavaVMs(JavaVM **vm, jsize size, jsize *size2);

static JavaVM *jvm = NULL;

static jint JNI_OnLoad(JavaVM* vm, void* reserved) {
    jvm = vm;
    JNIEnv *env = NULL;

    if (jvm && (*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_6) == JNI_OK)
    {
        return JNI_VERSION_1_6;
    }
    return -1;
}

JavaVM* getJavaVM() {
    if (jvm)
    {
        return jvm;
    }

    jint num_vms = 0;
    const jint max_vms = 5;
    JavaVM* vms[max_vms] = {0};
    if (JNI_GetCreatedJavaVMs(vms, max_vms, &num_vms) == JNI_OK)
    {
        for (int i = 0; i < num_vms; ++i)
        {
            if (vms[i] != NULL)
            {
                return vms[i];
            }
        }
    }
    return NULL;
}

 void handleData(uint8_t *data, size_t len) {
    JavaVM *jvm = getJavaVM();

    if (jvm)
    {
        JNIEnv *env = NULL;
        if ((*jvm)->AttachCurrentThread(jvm, (void **)&env, NULL)  == JNI_OK)
        {
            if (env)
            {
                //Call function with JNI..
            }

            (*jvm)->DetachCurrentThread(jvm);
        }
    }
}


问:
C++ unordered_map< pair<uint, uint>, UserClass > insertion
I am attempting to use the unordered_map to with keys as a pair of uint and values of the class Tile.

```<code>#include <iostream>
#include <unordered_map>
#include <boost/functional/hash.hpp>

class Tile {
public:
  std::pair<uint, uint> coordinate;

  bool operator==(const Tile &t) {
    return this->coordinate.first == t.coordinate.first
      && this->coordinate.second == t.coordinate.second;
  }

  Tile (uint x, uint y) {
    this->coordinate.first = x;
    this->coordinate.second = y;
  }

  std::pair<uint, uint> GetCoor() const
  {return this->coordinate;}

  uint GetX() const
  {return coordinate.first;}

  uint GetY() const
  {return coordinate.second;}
};

struct TileHash {
  std::size_t operator()(const Tile &t) const
  {
    size_t seed = 0;
    boost::hash_combine (seed, t.GetX());
    boost::hash_combine (seed, t.GetY());
    return seed;
  }
};

int main ()
{
  std::unordered_map<std::pair<uint, uint>, Tile, TileHash> board;
  Tile t1 = Tile (0, 0);

  board.insert (std::make_pair (t1.GetCoor(), t1));
  //board[t1.GetCoor()] = t1; // This causes a different error at compile time...
}
</code>```

I get following error followed by some notes that I did not paste here

```<code>/usr/include/c++/v1/unordered_map:400:17: error: no matching function for call to object of type 'const TileHash'
        {return static_cast<const _Hash&>(*this)(__x.__cc.first);}
                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/v1/__hash_table:1712:21: note: in instantiation of member function 'std::__1::__unordered_map_hasher<std::__1::pair<unsigned int, unsigned int>, std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>,
      Tile>, TileHash, true>::operator()' requested here
    size_t __hash = hash_function()(__x);
                    ^
/usr/include/c++/v1/__hash_table:1692:12: note: in instantiation of member function 'std::__1::__hash_table<std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>, Tile>,
      std::__1::__unordered_map_hasher<std::__1::pair<unsigned int, unsigned int>, std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>, Tile>, TileHash, true>, std::__1::__unordered_map_equal<std::__1::pair<unsigned
      int, unsigned int>, std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>, Tile>, std::__1::equal_to<std::__1::pair<unsigned int, unsigned int> >, true>,
      std::__1::allocator<std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>, Tile> > >::__insert_unique_value' requested here
    return __insert_unique_value(__x);
</code>```

I know that my instantiation of the unordered_map is ok, when I compile without a call to insert all is well.

答:
Via TileHash, you're providing a hasher function that takes a const Tile&.

The implementation is looking for a hasher function that takes a const std::pair<uint, uint>&.

That's because it's the key that gets hashed, not the mapped-value.

So, you're hashing the wrong thing.

The standard doesn't give us a hasher for pairs, but Boost does:

```<code>std::unordered_map<
   std::pair<uint, uint>,
   Tile,
   boost::hash<std::pair<uint, uint>>
> board;
</code>```

Body:
I am attempting to use the unordered_map to with keys as a pair of uint and values of the class Tile.

#include <iostream>
#include <unordered_map>
#include <boost/functional/hash.hpp>

class Tile {
public:
  std::pair<uint, uint> coordinate;

  bool operator==(const Tile &t) {
    return this->coordinate.first == t.coordinate.first
      && this->coordinate.second == t.coordinate.second;
  }

  Tile (uint x, uint y) {
    this->coordinate.first = x;
    this->coordinate.second = y;
  }

  std::pair<uint, uint> GetCoor() const
  {return this->coordinate;}

  uint GetX() const
  {return coordinate.first;}

  uint GetY() const
  {return coordinate.second;}
};

struct TileHash {
  std::size_t operator()(const Tile &t) const
  {
    size_t seed = 0;
    boost::hash_combine (seed, t.GetX());
    boost::hash_combine (seed, t.GetY());
    return seed;
  }
};

int main ()
{
  std::unordered_map<std::pair<uint, uint>, Tile, TileHash> board;
  Tile t1 = Tile (0, 0);

  board.insert (std::make_pair (t1.GetCoor(), t1));
  //board[t1.GetCoor()] = t1; // This causes a different error at compile time...
}

I get following error followed by some notes that I did not paste here

/usr/include/c++/v1/unordered_map:400:17: error: no matching function for call to object of type 'const TileHash'
        {return static_cast<const _Hash&>(*this)(__x.__cc.first);}
                ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/v1/__hash_table:1712:21: note: in instantiation of member function 'std::__1::__unordered_map_hasher<std::__1::pair<unsigned int, unsigned int>, std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>,
      Tile>, TileHash, true>::operator()' requested here
    size_t __hash = hash_function()(__x);
                    ^
/usr/include/c++/v1/__hash_table:1692:12: note: in instantiation of member function 'std::__1::__hash_table<std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>, Tile>,
      std::__1::__unordered_map_hasher<std::__1::pair<unsigned int, unsigned int>, std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>, Tile>, TileHash, true>, std::__1::__unordered_map_equal<std::__1::pair<unsigned
      int, unsigned int>, std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>, Tile>, std::__1::equal_to<std::__1::pair<unsigned int, unsigned int> >, true>,
      std::__1::allocator<std::__1::__hash_value_type<std::__1::pair<unsigned int, unsigned int>, Tile> > >::__insert_unique_value' requested here
    return __insert_unique_value(__x);

I know that my instantiation of the unordered_map is ok, when I compile without a call to insert all is well.

Body:
Via TileHash, you're providing a hasher function that takes a const Tile&.

The implementation is looking for a hasher function that takes a const std::pair<uint, uint>&.

That's because it's the key that gets hashed, not the mapped-value.

So, you're hashing the wrong thing.

The standard doesn't give us a hasher for pairs, but Boost does:

std::unordered_map<
   std::pair<uint, uint>,
   Tile,
   boost::hash<std::pair<uint, uint>>
> board;


问:
When should I return by value, as opposed to returning a unique pointer
What I'm wondering is, how does returning by value a Cat actually differ from returning an std::unique_ptr<Cat> in terms of passing them around, memory management and using them in practice.

Memory management wise, aren't they the same? As both a returned by value object and an object wrapped in a unique_ptr will have their destructors triggered once they go out of scope?

So, how would you compare both pieces of code:

```<code>Cat catFactory(string catName) {
    return Cat(catName);
}

std::unique_ptr<Cat> catFactory(string catName) {
    return std::unique_ptr(new Cat(catName));
}
</code>```

答:
By default, return by value.

Exceptions to this rule:

The Cat needs to exist on the heap, so as to outlast the code triggering its creation... but in this case perhaps it shouldn't really be a unique_ptr that's returned, but rather a shared_ptr.

You're not actually constructing the Cat but rather getting access to something which can be interpreted as a Cat; in this case, again, you probably don't want a unique pointer but a regular one (or a unique pointer with a custom deleter).

Polymorphism - if it's a factory and Cat is one of its products, you can probably also make a Dog and a Horse, all being Animals, so you'll return a pointer to an Animal. That's definitely a case where you would use a unique pointer.

Dark voodoo in your copy, assignment and/or move constructors which makes it important to always make sure you only poke your Cat from afar.

I disagree with @Brian's answer regarding two of the exceptions he suggests:

I would suggest not to use a pointer return type so as to be able to indicate failure by returning nullptr. Failing to return a valid value is what exceptions are for, and even if you want to avoid them - I'd suggest returning an std::expected (with C++23) or std::optional (earlier C++ versions). Or just throwing an exception on failure if you're allowed to do that.

You usually don't need a move constructor for return value optimization to kick in - so the lack of a move constructor should not be a reason to return a pointer.

ContentLicense: CC BY-SA 4.0

Body:
What I'm wondering is, how does returning by value a Cat actually differ from returning an std::unique_ptr<Cat> in terms of passing them around, memory management and using them in practice.

Memory management wise, aren't they the same? As both a returned by value object and an object wrapped in a unique_ptr will have their destructors triggered once they go out of scope?

So, how would you compare both pieces of code:

Cat catFactory(string catName) {
    return Cat(catName);
}

std::unique_ptr<Cat> catFactory(string catName) {
    return std::unique_ptr(new Cat(catName));
}