问:
ptxas complains about (types in) my sad device function
Consider the following PTX code:

```<code>//
// Generated by NVIDIA NVVM Compiler... sort of
//
// Compiler Build ID: CL-25769353
// Cuda compilation tools, release 10.1, V10.1.105
// Based on LLVM 3.4svn
//

.version 6.4
.target sm_30
.address_size 64

.func  (.param .b32 func_retval0) foo(
        .param .b32 foo_param_0,
        .param .b32 foo_param_1,
        .param .b32 foo_param_2
)
{
        .reg .b16       %rs<3>;
        .reg .b32       %r<3>;

        ld.param.u16    %rs1, [foo_param_0];
        ld.param.u16    %rs2, [foo_param_1];
        ld.param.u32    %r2, [foo_param_2];
        // inline asm
        sad.s16 %r1, %rs1, %rs2, %r2;
        // inline asm
        st.param.b32    [func_retval0+0], %r1;
        ret;
}
</code>```

When trying to compile this with ptxas (CUDA 10.1), I get:

```<code>ptxas /tmp/a.ptx, line 27; error   : Arguments mismatch for instruction 'sad'
ptxas fatal   : Ptx assembly aborted due to errors
</code>```

why is that? What's wrong with this combination of types?

The PTX reference says:

```<code>sad.type  d, a, b, c;

.type = { .u16, .u32, .u64,
          .s16, .s32, .s64 };
</code>```

and it seems d and c are u32 always and type applies to a and b. That's what the __sad() functions in device_functions.h have anyway.

答:
Actually, the type of d and a needs to be "the unsigned version of the type of b and c". So, this should work:

```<code>.func  (.param .b32 func_retval0) foo(
        .param .b32 foo_param_0,
        .param .b32 foo_param_1,
        .param .b32 foo_param_2
)
{
        .reg .b32       %r<5>;

        ld.param.u32    %r4, [foo_param_2];
        ld.param.s16    %r2, [foo_param_0];
        ld.param.s16    %r3, [foo_param_1];
        // inline asm
        sad.s32 %r1, %r2, %r3, %r4;
        // inline asm
        st.param.b32    [func_retval0+0], %r1;
        ret;
}
</code>```

Body:
Consider the following PTX code:

//
// Generated by NVIDIA NVVM Compiler... sort of
//
// Compiler Build ID: CL-25769353
// Cuda compilation tools, release 10.1, V10.1.105
// Based on LLVM 3.4svn
//

.version 6.4
.target sm_30
.address_size 64

.func  (.param .b32 func_retval0) foo(
        .param .b32 foo_param_0,
        .param .b32 foo_param_1,
        .param .b32 foo_param_2
)
{
        .reg .b16       %rs<3>;
        .reg .b32       %r<3>;

        ld.param.u16    %rs1, [foo_param_0];
        ld.param.u16    %rs2, [foo_param_1];
        ld.param.u32    %r2, [foo_param_2];
        // inline asm
        sad.s16 %r1, %rs1, %rs2, %r2;
        // inline asm
        st.param.b32    [func_retval0+0], %r1;
        ret;
}

When trying to compile this with ptxas (CUDA 10.1), I get:

ptxas /tmp/a.ptx, line 27; error   : Arguments mismatch for instruction 'sad'
ptxas fatal   : Ptx assembly aborted due to errors

why is that? What's wrong with this combination of types?

The PTX reference says:

sad.type  d, a, b, c;

.type = { .u16, .u32, .u64,
          .s16, .s32, .s64 };

and it seems d and c are u32 always and type applies to a and b. That's what the __sad() functions in device_functions.h have anyway.

Body:
Actually, the type of d and a needs to be "the unsigned version of the type of b and c". So, this should work:

.func  (.param .b32 func_retval0) foo(
        .param .b32 foo_param_0,
        .param .b32 foo_param_1,
        .param .b32 foo_param_2
)
{
        .reg .b32       %r<5>;

        ld.param.u32    %r4, [foo_param_2];
        ld.param.s16    %r2, [foo_param_0];
        ld.param.s16    %r3, [foo_param_1];
        // inline asm
        sad.s32 %r1, %r2, %r3, %r4;
        // inline asm
        st.param.b32    [func_retval0+0], %r1;
        ret;
}


来源: stackexchange

问:
Find out if QCursor::setPos has an effect
QCursor::setPos() does not work on some platforms under some conditions. E.g. on MacOS, there are accessibility settings, allowing an application to allow or forbid controlling the cursor. Is there a way to find out whether QCursor::setPos() currently has an effect?

The most trivial solution, changing the cursor slightly using QCursor::setPos and check whether it changed (using QCursor::pos) did not work, at least not on MacOS.

Note: A generic solution for at least Linux, Windows, Mac, is required.

答:
A cross-platform solution is not known to me, which does not mean there is none. But for macOS you can use platform-specific code.

macOS solution

There is the AXIsProcessTrusted function in the ApplicationServices framework of macOS, it

Returns whether the current process is a trusted accessibility client.

see https://developer.apple.com/documentation/applicationservices/1460720-axisprocesstrusted?language=objc

In addition to calling the above function, you need to:

use the Q_OS_MAC preprocessor conditional to include macOS specific code

link against the ApplicationServices framework

use the include #include <ApplicationServices/ApplicationServices.h>

Example

A complete self-contained example could look like this:

```<code>#include <iostream>
#include <QApplication>
#include <QMainWindow>
#ifdef Q_OS_MAC
#include <ApplicationServices/ApplicationServices.h>
#endif

class MainWindow : public QMainWindow {

public:
    explicit MainWindow(QWidget *parent = nullptr) : QMainWindow(parent) {
        this->setWindowTitle("Qt Cursor Test");
        this->resize(320, 240);
    }
};

int main(int argc, char *argv[]) {
    QApplication appl(argc, argv);
    MainWindow mainw_window;
    mainw_window.show();

    QCursor cursor;

#ifdef Q_OS_MAC
    if(AXIsProcessTrusted()) {
        std::cout << "trusted accessibility client" << std::endl;
        cursor.setPos(10,10);
    } else {
        std::cout << "not a trusted trusted accessibility client, so give the user a hint or do whatever is appropriate" << std::endl;
    }
#else
    cursor.setPos(10,10);
#endif

    return QApplication::exec();
}
</code>```

Building

You need to link against the ApplicationServices framework. In case you are using CMake for building it could look like this:

```<code> cmake_minimum_required(VERSION 3.15)
 project(CursorTest)

 set(CMAKE_CXX_STANDARD 14)
 set(Qt5_DIR "/usr/local/Cellar/qt/5.14.1/lib/cmake/Qt5/")

 find_package(Qt5 COMPONENTS Widgets REQUIRED)

 add_executable(CursorTest main.cpp)

 target_link_libraries(CursorTest PRIVATE Qt5::Widgets  "-framework ApplicationServices")
</code>```

System Dialog

Perhaps you want to show the system dialog for MacOS users, that explains that the application wants to have accessibility  trust in and offers to open the system defaults, which would look like this:

Then you would use Boolean AXIsProcessTrustedWithOptions(CFDictionaryRef options), which

Returns whether the current process is a trusted accessibility client.

options

A dictionary of options, or NULL to specify no options. The following options are available:
  KEY: kAXTrustedCheckOptionPrompt VALUE: ACFBooleanRef indicating whether the user will be informed if the current process is untrusted. This could be used, for example, on application startup to always warn a user if accessibility is not enabled for the current process. Prompting occurs asynchronously and does not affect the return value.

see https://developer.apple.com/documentation/applicationservices/1459186-axisprocesstrustedwithoptions?language=objc

Just slightly modify the above example:

```<code>...
#ifdef Q_OS_MAC
    CFStringRef keys[] = { kAXTrustedCheckOptionPrompt };
    CFTypeRef values[] = { kCFBooleanTrue };
    CFDictionaryRef options = CFDictionaryCreate(NULL,
                                                 (const void **)&keys,
                                                 (const void **)&values,
                                                 sizeof(keys) / sizeof(keys[0]),
                                                 &kCFTypeDictionaryKeyCallBacks,
                                                 &kCFTypeDictionaryValueCallBacks);
    if(AXIsProcessTrustedWithOptions(options)) {
        std::cout << "trusted accessibility client" << std::endl;
        cursor.setPos(10,10);
    } else {
        std::cout << "not a trusted trusted accessibility client, so give the user a hint or do whatever is appropriate" << std::endl;
    }
    CFRelease(options);
#else
...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
A cross-platform solution is not known to me, which does not mean there is none. But for macOS you can use platform-specific code.

macOS solution

There is the AXIsProcessTrusted function in the ApplicationServices framework of macOS, it

Returns whether the current process is a trusted accessibility client.

see https://developer.apple.com/documentation/applicationservices/1460720-axisprocesstrusted?language=objc

In addition to calling the above function, you need to:

use the Q_OS_MAC preprocessor conditional to include macOS specific code

link against the ApplicationServices framework

use the include #include <ApplicationServices/ApplicationServices.h>

Example

A complete self-contained example could look like this:

#include <iostream>
#include <QApplication>
#include <QMainWindow>
#ifdef Q_OS_MAC
#include <ApplicationServices/ApplicationServices.h>
#endif

class MainWindow : public QMainWindow {

public:
    explicit MainWindow(QWidget *parent = nullptr) : QMainWindow(parent) {
        this->setWindowTitle("Qt Cursor Test");
        this->resize(320, 240);
    }
};

int main(int argc, char *argv[]) {
    QApplication appl(argc, argv);
    MainWindow mainw_window;
    mainw_window.show();

    QCursor cursor;

#ifdef Q_OS_MAC
    if(AXIsProcessTrusted()) {
        std::cout << "trusted accessibility client" << std::endl;
        cursor.setPos(10,10);
    } else {
        std::cout << "not a trusted trusted accessibility client, so give the user a hint or do whatever is appropriate" << std::endl;
    }
#else
    cursor.setPos(10,10);
#endif

    return QApplication::exec();
}

Building

You need to link against the ApplicationServices framework. In case you are using CMake for building it could look like this:

 cmake_minimum_required(VERSION 3.15)
 project(CursorTest)

 set(CMAKE_CXX_STANDARD 14)
 set(Qt5_DIR "/usr/local/Cellar/qt/5.14.1/lib/cmake/Qt5/")

 find_package(Qt5 COMPONENTS Widgets REQUIRED)

 add_executable(CursorTest main.cpp)

 target_link_libraries(CursorTest PRIVATE Qt5::Widgets  "-framework ApplicationServices")

System Dialog

Perhaps you want to show the system dialog for MacOS users, that explains that the application wants to have accessibility  trust in and offers to open the system defaults, which would look like this:

Then you would use Boolean AXIsProcessTrustedWithOptions(CFDictionaryRef options), which

Returns whether the current process is a trusted accessibility client.

options

A dictionary of options, or NULL to specify no options. The following options are available:
  KEY: kAXTrustedCheckOptionPrompt VALUE: ACFBooleanRef indicating whether the user will be informed if the current process is untrusted. This could be used, for example, on application startup to always warn a user if accessibility is not enabled for the current process. Prompting occurs asynchronously and does not affect the return value.

see https://developer.apple.com/documentation/applicationservices/1459186-axisprocesstrustedwithoptions?language=objc

Just slightly modify the above example:

...
#ifdef Q_OS_MAC
    CFStringRef keys[] = { kAXTrustedCheckOptionPrompt };
    CFTypeRef values[] = { kCFBooleanTrue };
    CFDictionaryRef options = CFDictionaryCreate(NULL,
                                                 (const void **)&keys,
                                                 (const void **)&values,
                                                 sizeof(keys) / sizeof(keys[0]),
                                                 &kCFTypeDictionaryKeyCallBacks,
                                                 &kCFTypeDictionaryValueCallBacks);
    if(AXIsProcessTrustedWithOptions(options)) {
        std::cout << "trusted accessibility client" << std::endl;
        cursor.setPos(10,10);
    } else {
        std::cout << "not a trusted trusted accessibility client, so give the user a hint or do whatever is appropriate" << std::endl;
    }
    CFRelease(options);
#else
...


问:
Array of Strings to an Array of Objects
Maybe there is a method that does this that I don't know about - I doubt it though - but I'm trying to convert an array of strings to an array of Objects. Here is the problem: I'm reading a file in from the command line. The file represents several classes of the following types each with their own data fields. Vehicle is the parent class of all who follow: Vehicle,Car,American Car, Foreign car, Truck, Bicycle.

I have no problem reading the file into a string array. However I need to create objects of all these types and store them in an array of type Vehicle[]. For example a portion of the file looks like this:

Vehicle

Kim Stanley Robinson

2344 court drive

(221)885-7777

stackoverflow@overflow.com

American Car

John Bunyon

1010 binary lane

(221)885-55643

bgt.com

convertable

made in detroit

 union plant

Where Class type is the first line followed by, Owner's Name, address, phone number, email address...Each type has fields particular to it. So a foreign car is not made in Detroit. Each of these fields appear on a separate line in the file. So what I've done is read the  entire file into a string array. However, I need to find my types in the array of strings,create objects of those types, and store them in a Vehicle array. My main problem is that each data field is on a separate line. How should I approach this problem?
This is java code by the way.

答:
It seems to me you need a factory pattern to build your set of vehicle types from the inputs. The factory can look after determining where one car specification starts and another one ends. It'll then determine the set of fields for a car, and determine the car type. It can then call the appropriate constructor, passing in all the related fields.

This means that a constructor of (say) an American car specifies all the fields that it's interested in. A European car constructor would do the same. Each constructor can assert on what it's been given so you don't create any cars incorrectly.

The factory will look after parsing and separating the inputs, and determining what is to be built. Each type of car's constructor looks after info for that car only, and performs the appropriate asserts.

The factory will maintain the list of cars created, and return that list (of America/European/Japanese) upon completion.

In pseudo-code:

```<code>whilst(!done) {
   fields.add(fieldFromFile);

   if (carSpecificationCompleted) {
       type = getType(fields);
       if (type == 'American') {
          car = new AmericanCar(fields);
       }
       else if (type == 'European') {
          car = new EuropeanCar(fields);
       }
       cars.add(car);
       clearStoredFields();
   }
}
</code>```

OwnerDisplayName: BloodParrot

ContentLicense: CC BY-SA 2.5

Title: Array of Strings to an Array of Objects

Body:
It seems to me you need a factory pattern to build your set of vehicle types from the inputs. The factory can look after determining where one car specification starts and another one ends. It'll then determine the set of fields for a car, and determine the car type. It can then call the appropriate constructor, passing in all the related fields.

This means that a constructor of (say) an American car specifies all the fields that it's interested in. A European car constructor would do the same. Each constructor can assert on what it's been given so you don't create any cars incorrectly.

The factory will look after parsing and separating the inputs, and determining what is to be built. Each type of car's constructor looks after info for that car only, and performs the appropriate asserts.

The factory will maintain the list of cars created, and return that list (of America/European/Japanese) upon completion.

In pseudo-code:

whilst(!done) {
   fields.add(fieldFromFile);

   if (carSpecificationCompleted) {
       type = getType(fields);
       if (type == 'American') {
          car = new AmericanCar(fields);
       }
       else if (type == 'European') {
          car = new EuropeanCar(fields);
       }
       cars.add(car);
       clearStoredFields();
   }
}

OwnerDisplayName: Brian Agnew


问:
Enable/Disable specific buttons in a ngFor
I want to enable the save button in a specific row and disable two buttons (add Selector and add Section) in a loop above through the edit button. But i am not able to disable/enable just a specific button that got generated.
Also i would like to manage it in my component to Enable/Disable.
I hope anyone can help me.

My Form Looks like this -> https://gyazo.com/329e442becd93222d33c15b1232cc9d2

```<code><div formArrayName="sectionList">
    <div *ngFor="let section of myForm.get('sectionList').controls; let i=index" [formGroupName]="i">
      <div formGroupName="section">
        <button mat-button color="primary" (click)="enableSection(i)">Edit</button>
        <mat-form-field>
          <input matInput placeholder="name" formControlName="name">
          <mat-error *ngIf="">
              todo
          </mat-error>
        </mat-form-field>
        <button mat-raised-button color="warn" (click)="deleteSection(i)" >Delete</button>
        <button mat-raised-button color="primary" [disabled]="true" (click)="saveSection(i)">Save</button>
      </div>

      <div formArrayName="selectorList">
        <div *ngFor="let selector of section.controls.selectorList.controls; let j=index" [formGroupName]="j">
          <button mat-button color="primary" (click)="enableSelector(i, j)">Edit</button>
          <mat-form-field>
            <input matInput placeholder="locator" formControlName="locator" >
          </mat-form-field>
          <mat-form-field>
            <input matInput placeholder="language" formControlName="language" >
          </mat-form-field>
          <mat-form-field>
            <input matInput placeholder="value" formControlName="value" >
          </mat-form-field>
          <button mat-raised-button color="warn" (click)="deleteSelector(i,j)">Delete</button>
          <button mat-raised-button color="primary" [disabled]="isDisabled" (click)="saveSelector(i,j)">Save</button>
        </div>
        <button mat-raised-button color="primary" (click)="addSelector(i)">Add Selector</button>
      </div>
    </div>
    <button mat-raised-button color="primary" (click)="addSection()">Add Section</button>
  </div>
</code>```

```<code> enableSection(i){
    this.sectionForms.controls[i].get('section').enable();
  }

  enableSelector(i, j){
    this.isDisabled = false;
    this.myForm.get('sectionList.' + i + '.selectorList.' + j).enable();
  }
</code>```

答: Just add to the button you wanna disable [disabled]="rowIWannaDisable === i" where i is the index of the *ngFor like in ngFor="let section of myForm.get('sectionList').controls; let i=index" and rowIWannaDisable is the row number where you want the button disabled. You could also use a function instead of rowIWannaDisable to select the disabled row dynamically.

Body:
I want to enable the save button in a specific row and disable two buttons (add Selector and add Section) in a loop above through the edit button. But i am not able to disable/enable just a specific button that got generated.
Also i would like to manage it in my component to Enable/Disable.
I hope anyone can help me.

My Form Looks like this -> https://gyazo.com/329e442becd93222d33c15b1232cc9d2

        <button mat-button color="primary" (click)="enableSection(i)">Edit</button>
        <mat-form-field>
          <input matInput placeholder="name" formControlName="name">
          <mat-error *ngIf="">
              todo
          </mat-error>
        </mat-form-field>
        <button mat-raised-button color="warn" (click)="deleteSection(i)" >Delete</button>
        <button mat-raised-button color="primary" [disabled]="true" (click)="saveSection(i)">Save</button>

          <button mat-button color="primary" (click)="enableSelector(i, j)">Edit</button>
          <mat-form-field>
            <input matInput placeholder="locator" formControlName="locator" >
          </mat-form-field>
          <mat-form-field>
            <input matInput placeholder="language" formControlName="language" >
          </mat-form-field>
          <mat-form-field>
            <input matInput placeholder="value" formControlName="value" >
          </mat-form-field>
          <button mat-raised-button color="warn" (click)="deleteSelector(i,j)">Delete</button>
          <button mat-raised-button color="primary" [disabled]="isDisabled" (click)="saveSelector(i,j)">Save</button>

        <button mat-raised-button color="primary" (click)="addSelector(i)">Add Selector</button>

    <button mat-raised-button color="primary" (click)="addSection()">Add Section</button>

 enableSection(i){
    this.sectionForms.controls[i].get('section').enable();
  }

  enableSelector(i, j){
    this.isDisabled = false;
    this.myForm.get('sectionList.' + i + '.selectorList.' + j).enable();
  }


答:
In MySQL 8.0? you can do this with row_number() and aggregation:

```<code>select
    max(case when rn % 3 = 0 then name end) group1,
    max(case when rn % 3 = 1 then name end) group2,
    max(case when rn % 3 = 2 then name end) group3
from (select name, row_number() over(order by name) - 1 rn from mytable where active = 1) t
group by floor(rn / 3)
</code>```

Note that this does not produces exactly the result that you showed: names are spread from left to right, then top to bottom (while your result is top to bottom, then left to right).

Demo on DB Fiddle:

```
group1 | group2 | group3
:----- | :----- | :-----
Name1  | Name2  | Name3
Name4  | Name5  | Name6
Name7  | Name8  | Name9
```

In earlier versions of MySQL, you can emulate row_number() with variable, like so:

```<code>set @rn = -1;
select
    max(case when rn % 3 = 0 then name end) group1,
    max(case when rn % 3 = 1 then name end) group2,
    max(case when rn % 3 = 2 then name end) group3
from (
    select name, @rn := @rn + 1 rn from mytable where active = 1 order by name) t
group by floor(rn / 3)
</code>```

Demo on MySQL 5.6 DB Fiddle

Title: Create grouping rows by foreach and mysql in PHP

Body:
This is my table structure :

----------------------
 # |  name  | active |
---|--------|--------|
 1 |  Name1 |   1    |
---|--------|--------|
 2 |  Name2 |   1    |
---|--------|--------|
 3 |  Name3 |   1    |
---|--------|--------|
 4 |  Name4 |   1    |
---|--------|--------|
 5 |  Name5 |   1    |
---|--------|--------|
 6 |  Name6 |   1    |
---|--------|--------|
 7 |  Name7 |   1    |
---|--------|--------|
 8 |  Name8 |   1    |
---|--------|--------|
 9 |  Name9 |   1    |
---|--------|--------|

I want to grouping (groups of three) rows by foreach and mysql, like the following:

--------------------------------
 Group 1 |  Group 2  | Group 3 |
---------|-----------|---------|
  Name1  |   Name4   |  Name7  |
---------|-----------|---------|
  Name2  |   Name5   |  Name8  |
---------|-----------|---------|
  Name3  |   Name6   |  Name9  |
---------|-----------|---------|

How do I do this?

Body:
In MySQL 8.0? you can do this with row_number() and aggregation:

select
    max(case when rn % 3 = 0 then name end) group1,
    max(case when rn % 3 = 1 then name end) group2,
    max(case when rn % 3 = 2 then name end) group3
from (select name, row_number() over(order by name) - 1 rn from mytable where active = 1) t
group by floor(rn / 3)

Note that this does not produces exactly the result that you showed: names are spread from left to right, then top to bottom (while your result is top to bottom, then left to right).

Demo on DB Fiddle:

group1 | group2 | group3
:----- | :----- | :-----
Name1  | Name2  | Name3
Name4  | Name5  | Name6
Name7  | Name8  | Name9

In earlier versions of MySQL, you can emulate row_number() with variable, like so:

set @rn = -1;
select
    max(case when rn % 3 = 0 then name end) group1,
    max(case when rn % 3 = 1 then name end) group2,
    max(case when rn % 3 = 2 then name end) group3
from (
    select name, @rn := @rn + 1 rn from mytable where active = 1 order by name) t
group by floor(rn / 3)

Demo on MySQL 5.6 DB Fiddle


问:
Idempotence Key in Node.js API
I have a REST API endpoint in node.js that handles monetary transactions. I want to implement something similar to stripe's idempotence key to ensure that the same transaction isn't carried out twice in the event of a network failure.
How can I implement something like that in Node.js?</p>

答:
In your case, as the call is non idempotent, you can call it only once. In case of failure, best is to be contacted directly as a human to check the transaction status and manually fix it.

For identification, use uuid for each call. You can generate it on the client side or on the server side. On the server side is recommended, but the response may never reach the client, so they will not have the id. Other option is to generate it on the client side and accept it as a parameter on the server side. This implies lower trust in those ids, but still useful for easier identification.

Title: Idempotence Key in Node.js API


问:
how to use custom regular expression for more than one call?
edit: This part was solved, but I have one last problem with my code, see last answer.

I have a textfile structured as follow:

```<code>Name1 (Middlename1) LastName
Birthyear
Name2 (Middlename2) LastName
Birthyear
...
NameN (MiddlenameM) LastName
Birthyear
</code>```

I'm trying to use RE to find the name and the year automatically but I don't know how to combine the two REs since both information are not on the same line:

```<code>import re
regexp = re.compile(  r'(( )*)(?P<name>([a-zA-Z]*)( [a-zA-Z]+)? ROCHE)\n'
                      r'(( )*)(?P<year>18\d\d)\n'
                   )
</code>```

The two REs are working independently but not together. How am I supposed to do it?

答:
You should use re.MULTILINE

```<code>r = re.compile(r'(( )*)(?P<name>([a-zA-Z]*)( [a-zA-Z]+)?)(( )+)(?P<surname>([a-zA-Z]+))\n(?P<year>18\d\d)', re.MULTILINE)

m = r.match("""Jan Sebastian  Bach
1892""")
</code>```

Update #1
More complete example with reading two lines from file and then another two lines.

```<code>import re

r = re.compile(r'(( )*)(?P<name>([a-zA-Z]*)( [a-zA-Z]+)?)(( )+)(?P<surname>([a-zA-Z]+))\n(?P<year>18\d\d)', re.MULTILINE)

with open('people.txt') as f:
    while True:
        line1 = f.readline()
        line2 = f.readline()
        if not line2: break
        m = r.match(line1+line2)
        print("name:%s, surname:%s, year:%s" % (m.group('name'), m.group('surname'), m.group('year')))
</code>```

Body:
edit: This part was solved, but I have one last problem with my code, see last answer.

I have a textfile structured as follow:

Name1 (Middlename1) LastName
Birthyear
Name2 (Middlename2) LastName
Birthyear
...
NameN (MiddlenameM) LastName
Birthyear

I'm trying to use RE to find the name and the year automatically but I don't know how to combine the two REs since both information are not on the same line:

import re
regexp = re.compile(  r'(( )*)(?P<name>([a-zA-Z]*)( [a-zA-Z]+)? ROCHE)\n'
                      r'(( )*)(?P<year>18\d\d)\n'
                   )

The two REs are working independently but not together. How am I supposed to do it?

Body:
You should use re.MULTILINE

r = re.compile(r'(( )*)(?P<name>([a-zA-Z]*)( [a-zA-Z]+)?)(( )+)(?P<surname>([a-zA-Z]+))\n(?P<year>18\d\d)', re.MULTILINE)

m = r.match("""Jan Sebastian  Bach
1892""")

Update #1
More complete example with reading two lines from file and then another two lines.

import re

r = re.compile(r'(( )*)(?P<name>([a-zA-Z]*)( [a-zA-Z]+)?)(( )+)(?P<surname>([a-zA-Z]+))\n(?P<year>18\d\d)', re.MULTILINE)

with open('people.txt') as f:
    while True:
        line1 = f.readline()
        line2 = f.readline()
        if not line2: break
        m = r.match(line1+line2)
        print("name:%s, surname:%s, year:%s" % (m.group('name'), m.group('surname'), m.group('year')))


问:
combine (join) objects in array javascript
In d3.csv("file.csv", function(error, data) instruction

d3.csv is a helper that uses d3.csv.parse internally to parse CSV
data loaded from a file into an array of objects, and then it passes this
to a callback.

So data is a callback variable that holds an array of objects

In the picture the structure of data

You can see that the headers of the original CSV have been used as the property names for the data objects.Using d3.csv in this manner requires that your CSV file has a header row.

data is array of objects

```<code>data (in orange) is a combination of :
- columns array (in red) holding csv headers that means **property names**
  for the **data objects**
- an array of 6131 elements (in green) holding the values associated with
  these propertie
</code>```

Now that we have finished describing the desired structure:

Imagine I have an array of 6131 elements (the same as described in the
 picture in green)

```<code>var dataArray =[];
 for(var i=0;i<6131;i++){
        ddd[i]={x:..,y:...etc};
        dataArray.push(ddd[i]);
 }
</code>```

My question is how to construct in reverse the same identical structure described before and result with the same data like the one got from d3.csv.

```<code>var columnsArray=["NOM","PRENOM","SPECIALITE","Full_Address","VILLE","lat","lon"];
</code>```

Thank you very much for help.

答:
You can attach a columns property to your dataArray object:

```<code>dataArray.columns = columnsArray;
</code>```

Body:
In d3.csv("file.csv", function(error, data) instruction

d3.csv is a helper that uses d3.csv.parse internally to parse CSV
data loaded from a file into an array of objects, and then it passes this
to a callback.

So data is a callback variable that holds an array of objects

In the picture the structure of data

You can see that the headers of the original CSV have been used as the property names for the data objects.Using d3.csv in this manner requires that your CSV file has a header row.

data is array of objects

data (in orange) is a combination of :
- columns array (in red) holding csv headers that means **property names**
  for the **data objects**
- an array of 6131 elements (in green) holding the values associated with
  these propertie

Now that we have finished describing the desired structure:

Imagine I have an array of 6131 elements (the same as described in the
 picture in green)

var dataArray =[];
 for(var i=0;i<6131;i++){
        ddd[i]={x:..,y:...etc};
        dataArray.push(ddd[i]);
 }

My question is how to construct in reverse the same identical structure described before and result with the same data like the one got from d3.csv.

var columnsArray=["NOM","PRENOM","SPECIALITE","Full_Address","VILLE","lat","lon"];

Thank you very much for help.

Body:
You can attach a columns property to your dataArray object:

dataArray.columns = columnsArray;


问:
Update binary files in Node.js
I'm trying to work with binary files using Node.js.

I'm trying to receive a binary file from the client, open the binary file, convert to hexadecimal, replace data and return the new binary file to the client.

```<code>app.use('/read-binary-file',(req,res) => {
    try {
        let content = fs.readFileSync(file_path);
        console.log('content', content)
        res.status(200).send({content})
    }
    catch(err) {
        console.error(err);
    }
})
</code>```

I wrote code that takes an existing file and try to read it. When I print it, I get this in the buffer:

```<code>content <Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ... >
</code>```

I'm not sure how to convert it to hexadecimal and then try to change it...
When I read the file via online hex editor, I get them in 16 bit each line and this way is very comfortable.

I have some questions:

How can convert from binary to hexadecimal?

How can I replace data in a hexadecimal file and then return to the client?

How can I display them in code as 16 bit?

What is the best way to store them in a database? To store the file and then
in the database store only the path?

Is there any documentation that can help?

答:
Convert from binary to hexadecimal:

const file = fs.readFileSync("./test");
const str = file.toString("hex");
```
</li>
<li><p>Replace data and return to the client:</p>
<pre class="lang-js prettyprint-override"><code>let newStr = str.replace( "00", "FF" );
let buffer = Buffer.from( newStr, "hex" );
</code>```

Display in 16 bits:

for ( let i = 0; i < newStr.length; i+=16 ){
  console.log( newStr.slice( i, i+16 ) + "\n" );
}
```
</li>
<li><p>Store the file in a writable upload folder, and store the URL path to the uploaded in the database. That's my suggestion, from my experience. You can read more about whether you want to choose to store the images in the database (in BLOB format) in this Quora post: <em>Is it a bad design to store images as blobs in a database?</em></p>
</li>
</ol>
<hr />
<p>Here's a basic setup that might help you:</p>
<p><em>/test</em></p>
```ABC
```
<p><em>/app.js</em></p>
<pre class="lang-js prettyprint-override"><code>const express = require('express');
const app = express();
const fs = require('fs');

app.use("/test", (req, res) => {

    const file = fs.readFileSync("./test");     // Read file as binary
    const str = file.toString("hex");           // Convert to hexadecimal
    let newStr = str.replace(/41|43/g, "42");   // Replace hexadecimal characters
    let buffer = Buffer.from(newStr, "hex");    // Create buffer from hexadecimal

    // Send to the user as download
    res.setHeader('Content-disposition', 'attachment; filename=test-edited.txt');
    res.setHeader('Content-type', 'text/plain');
    res.charset = 'UTF-8';
    res.write(buffer);
    res.end();
});

app.listen(3000, () => console.log('Server Running...'));
</code>```

The test file contains the characters ABC. They are transformed to BBB and then downloaded.

You can choose to output a different file type, by setting the appropriate filename and MIME type (Content-Type), e.g. for downloading a PNG image:

    res.setHeader('Content-disposition', 'attachment; filename=output.png');
    res.setHeader('Content-type', 'image/png');
```

Note: for direct binary manipulation, without an intermediary hexadecimal conversion, see Christos Lytras' answer.

Title: Update binary files in Node.js

Body:
I'm trying to work with binary files using Node.js.

I'm trying to receive a binary file from the client, open the binary file, convert to hexadecimal, replace data and return the new binary file to the client.

app.use('/read-binary-file',(req,res) => {
    try {
        let content = fs.readFileSync(file_path);
        console.log('content', content)
        res.status(200).send({content})
    }
    catch(err) {
        console.error(err);
    }
})

I wrote code that takes an existing file and try to read it. When I print it, I get this in the buffer:

content <Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ... >

I'm not sure how to convert it to hexadecimal and then try to change it...
When I read the file via online hex editor, I get them in 16 bit each line and this way is very comfortable.

I have some questions:

How can convert from binary to hexadecimal?

How can I replace data in a hexadecimal file and then return to the client?

How can I display them in code as 16 bit?

What is the best way to store them in a database? To store the file and then
in the database store only the path?

Is there any documentation that can help?

Body:
Convert from binary to hexadecimal:

const file = fs.readFileSync("./test");
const str = file.toString("hex");

Replace data and return to the client:

let newStr = str.replace( "00", "FF" );
let buffer = Buffer.from( newStr, "hex" );

Display in 16 bits:

for ( let i = 0; i < newStr.length; i+=16 ){
  console.log( newStr.slice( i, i+16 ) + "\n" );
}

Store the file in a writable upload folder, and store the URL path to the uploaded in the database. That's my suggestion, from my experience. You can read more about whether you want to choose to store the images in the database (in BLOB format) in this Quora post: Is it a bad design to store images as blobs in a database?

Here's a basic setup that might help you:

/test

ABC

/app.js

const express = require('express');
const app = express();
const fs = require('fs');

app.use("/test", (req, res) => {

    const file = fs.readFileSync("./test");     // Read file as binary
    const str = file.toString("hex");           // Convert to hexadecimal
    let newStr = str.replace(/41|43/g, "42");   // Replace hexadecimal characters
    let buffer = Buffer.from(newStr, "hex");    // Create buffer from hexadecimal

    // Send to the user as download
    res.setHeader('Content-disposition', 'attachment; filename=test-edited.txt');
    res.setHeader('Content-type', 'text/plain');
    res.charset = 'UTF-8';
    res.write(buffer);
    res.end();
});

app.listen(3000, () => console.log('Server Running...'));

The test file contains the characters ABC. They are transformed to BBB and then downloaded.

You can choose to output a different file type, by setting the appropriate filename and MIME type (Content-Type), e.g. for downloading a PNG image:

    res.setHeader('Content-disposition', 'attachment; filename=output.png');
    res.setHeader('Content-type', 'image/png');

Note: for direct binary manipulation, without an intermediary hexadecimal conversion, see Christos Lytras' answer.


问:
JavaScript version of onclick, onmouseover, onmouseout for an image
I'd like to be able to call functions for onmouseover, onmouseout, and onclick of an image, purely using javascript, not HTML. I have code that creates a dynamic list of paragraph tags on the page using purely javascript. It looks like a list but is not a list. I've also added an x image to the left of each line of the list. I'd like when that image is clicked, to call a function to remove that line. Remember the image was added via JavaScript not HTML. How do I do this?

Here is my code:

```<code>updateAllDataDisplay(false);
function updateAllDataDisplay(addOne) {

    // Updating the entire display
    if (!addOne) {
        for (var i = 0; i < allData.length; i++) {
            let a = document.createElement("p");
            let c = document.createElement("img");
            c.src = "delete_button_smallest_still.png";
            c.addEventListener('click', removeLine(`${allData[i].month}/${allData[i].day}/${allData[i].year} (${allData[i].hours}:${allData[i].mins}:${allData[i].secs}): ${allData[i].exerciseHours}. ${allData[i].food}. ${allData[i].weight}. ${allData[i].mood}.`), false);
            a.appendChild(c);
            let d = document.createTextNode(" ");
            a.appendChild(d);
            let b = document.createTextNode(`${allData[i].month}/${allData[i].day}/${allData[i].year} (${allData[i].hours}:${allData[i].mins}:${allData[i].secs}): ${allData[i].exerciseHours}. ${allData[i].food}. ${allData[i].weight}. ${allData[i].mood}.`);
            a.appendChild(b);
            document.body.appendChild(a);
        }

    // Updating the last item of the display
    } else if (addOne) {
        let a = document.createElement("p");
        if (allData.length > 0) {
        let b = document.createTextNode(`${allData[allData.length - 1].month}/${allData[allData.length - 1].day}/${allData[allData.length - 1].year} (${allData[allData.length - 1].hours}:${allData[allData.length - 1].mins}:${allData[allData.length - 1].secs}): ${allData[allData.length - 1].exerciseHours}. ${allData[allData.length - 1].food}. ${allData[allData.length - 1].weight}. ${allData[allData.length - 1].mood}.`);
        a.appendChild(b);
        document.body.appendChild(a);
        }
    }
}
</code>```

答:
Use addEventListener

Look at the docs here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Body:
I'd like to be able to call functions for onmouseover, onmouseout, and onclick of an image, purely using javascript, not HTML. I have code that creates a dynamic list of paragraph tags on the page using purely javascript. It looks like a list but is not a list. I've also added an x image to the left of each line of the list. I'd like when that image is clicked, to call a function to remove that line. Remember the image was added via JavaScript not HTML. How do I do this?

Here is my code:

updateAllDataDisplay(false);
function updateAllDataDisplay(addOne) {

    // Updating the entire display
    if (!addOne) {
        for (var i = 0; i < allData.length; i++) {
            let a = document.createElement("p");
            let c = document.createElement("img");
            c.src = "delete_button_smallest_still.png";
            c.addEventListener('click', removeLine(`${allData[i].month}/${allData[i].day}/${allData[i].year} (${allData[i].hours}:${allData[i].mins}:${allData[i].secs}): ${allData[i].exerciseHours}. ${allData[i].food}. ${allData[i].weight}. ${allData[i].mood}.`), false);
            a.appendChild(c);
            let d = document.createTextNode(" ");
            a.appendChild(d);
            let b = document.createTextNode(`${allData[i].month}/${allData[i].day}/${allData[i].year} (${allData[i].hours}:${allData[i].mins}:${allData[i].secs}): ${allData[i].exerciseHours}. ${allData[i].food}. ${allData[i].weight}. ${allData[i].mood}.`);
            a.appendChild(b);
            document.body.appendChild(a);
        }

    // Updating the last item of the display
    } else if (addOne) {
        let a = document.createElement("p");
        if (allData.length > 0) {
        let b = document.createTextNode(`${allData[allData.length - 1].month}/${allData[allData.length - 1].day}/${allData[allData.length - 1].year} (${allData[allData.length - 1].hours}:${allData[allData.length - 1].mins}:${allData[allData.length - 1].secs}): ${allData[allData.length - 1].exerciseHours}. ${allData[allData.length - 1].food}. ${allData[allData.length - 1].weight}. ${allData[allData.length - 1].mood}.`);
        a.appendChild(b);
        document.body.appendChild(a);
        }
    }
}


问:
Error referring static variable inside static function in a class in PHP 7.4.2
I am learning PHP and using PHP 7.4.2 (using XAMPP) version to try out examples. I am trying to access the static variable from a static function using self::$vaiablename

But getting the following error:

```<code>Parse error: syntax error, unexpected 'self' (T_STRING) in C:\xampp\htdocs\php-getting-started\classes\CountryRepository.php on line 18

<?php

require 'Country.php';
require 'State.php';

class CountryRepository {
    private static $countries = array();

    protected static function init() {
        $countries = array();
        array_push($countries,
        new Country('Austria','at',array(new State('Styria'), new State('Burgandy'))));
        array_push($countries,
        new Country('United States','usa',array(new State('California'), new State('Maryland'))));
        array_push($countries,
        new Country('Luxembourg','lu'))

        self::$countries = $countries;
    }

    public static function getCountries() {
        if(count(self::$countries) === 0) {
            self::init();
        }
        return self::$countries;
    }
}

?>
</code>```

Can anyone please help me with this?

答:
In your case there is a missing semicolon after the last array_push. PHP interprets this as array_push()self which leads to the above error.

```<code>new Country('Luxembourg', 'lu'))
                                ^^^
</code>```

vs

```<code>new Country('Luxembourg', 'lu'));
                                ^^^
</code>```

Body:
I am learning PHP and using PHP 7.4.2 (using XAMPP) version to try out examples. I am trying to access the static variable from a static function using self::$vaiablename

But getting the following error:

Parse error: syntax error, unexpected 'self' (T_STRING) in C:\xampp\htdocs\php-getting-started\classes\CountryRepository.php on line 18

<?php

require 'Country.php';
require 'State.php';

class CountryRepository {
    private static $countries = array();

    protected static function init() {
        $countries = array();
        array_push($countries,
        new Country('Austria','at',array(new State('Styria'), new State('Burgandy'))));
        array_push($countries,
        new Country('United States','usa',array(new State('California'), new State('Maryland'))));
        array_push($countries,
        new Country('Luxembourg','lu'))

        self::$countries = $countries;
    }

    public static function getCountries() {
        if(count(self::$countries) === 0) {
            self::init();
        }
        return self::$countries;
    }
}

?>

Can anyone please help me with this?

Body:
In your case there is a missing semicolon after the last array_push. PHP interprets this as array_push()self which leads to the above error.

new Country('Luxembourg', 'lu'))
                                ^^^

vs

new Country('Luxembourg', 'lu'));
                                ^^^


问:
Is a "const member function" checked at compile time or runtime?
I am wondering when the checking for a const member function happens? I guess it happens at compile time, but cannot be sure.
Does anyone know?

答:
constness of member functions affects the type of the this pointer.  Type safety is checked at compile time (unless bypassed with a cast, most casts bypass safety checks, dynamic_cast adds a runtime check).

However, on most architectures constness is not merely a type check, but enforced by the memory protection unit.  This happens at runtime, and is NOT bypassed by const_cast (or C-style cast).

ContentLicense: CC BY-SA 3.0


问:
What's the best way to avoid many if statements in Angular component to call specific function?
I'm creating a temperature conversion app in Angular 7, in my formGroup I have an input/output value, and 2 multi selects where the user can select a unit of temperature 'From' and 'To' to convert(celsius, Fahrenheit or Kelvin).

When the user submit the form in my component I get the input data

```<code>submitForm(data) {
    this.input = data.input;
    this.unitInput= data.unitInput;
    this.unitTarget= data.unitTarget;
    this.output= data.output;
  }
</code>```

I thought in just adding if statements to call the function that will make the conversion, but now looking at all if statements that i have seems a lot and not a good design.

```<code>if (this.inputUnit === 'Celsius' && this.targetUnit === 'Fahrenheit') {
        this.celsiusToFahrenheitConversion ();
}
if (this.inputUnit === 'Celsius' && this.targetUnit === 'Kelvin') {
      this.celsiusToKelvinConversion ();
}
if (this.inputUnit === 'Celsius' && this.targetUnit === 'Rankine') {
      this.celsiusToRankineConversion ();
}
</code>```

If's for Fahrenheit, If's for Kelvin, If's for Rankine, etc..
and what about if in the feature I want to add a different kind of unit?
What would be a better approach?

Thanks in advance

答:
When I look at this I see compound keys set against a function value.

One way to represent this idea is with an typical object where the keys are the compound and they map to a specific function:

```<code>const conversionFunctions = {
    'celsius-fahrenheit': this.celsiusToFahrenheitConversion,
    'celsius-kelvin': this.celsiusToKelvinConversion,
    'celsius-rankine': this.celsiusToRankineConversion
};

const key = `${this.inputUnit.toLowerCase()}-${this.targetUnit.toLowerCase()}`;
const convert = conversionFunctions[key];

convert();
</code>```

Body:
I'm creating a temperature conversion app in Angular 7, in my formGroup I have an input/output value, and 2 multi selects where the user can select a unit of temperature 'From' and 'To' to convert(celsius, Fahrenheit or Kelvin).

When the user submit the form in my component I get the input data

submitForm(data) {
    this.input = data.input;
    this.unitInput= data.unitInput;
    this.unitTarget= data.unitTarget;
    this.output= data.output;
  }

I thought in just adding if statements to call the function that will make the conversion, but now looking at all if statements that i have seems a lot and not a good design.

if (this.inputUnit === 'Celsius' && this.targetUnit === 'Fahrenheit') {
        this.celsiusToFahrenheitConversion ();
}
if (this.inputUnit === 'Celsius' && this.targetUnit === 'Kelvin') {
      this.celsiusToKelvinConversion ();
}
if (this.inputUnit === 'Celsius' && this.targetUnit === 'Rankine') {
      this.celsiusToRankineConversion ();
}

If's for Fahrenheit, If's for Kelvin, If's for Rankine, etc..
and what about if in the feature I want to add a different kind of unit?
What would be a better approach?

Thanks in advance

Body:
When I look at this I see compound keys set against a function value.

One way to represent this idea is with an typical object where the keys are the compound and they map to a specific function:

const conversionFunctions = {
    'celsius-fahrenheit': this.celsiusToFahrenheitConversion,
    'celsius-kelvin': this.celsiusToKelvinConversion,
    'celsius-rankine': this.celsiusToRankineConversion
};

const key = `${this.inputUnit.toLowerCase()}-${this.targetUnit.toLowerCase()}`;
const convert = conversionFunctions[key];

convert();


问:
How to not redirect Twitterbot when using cloudflare SSL?
Twitter Cards (twitter:image or og:image) won’t allow https from a shared SSL including Cloudflare. The workaround mentioned is to create an .htaccess file and add code to not redirect twitterbot to the shared https. The problem is this is breaking my pages saying there are too many redirects.

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^example.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteCond %{HTTP_USER_AGENT} !Twitterbot [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]
</IfModule>
</code>```

That being said, when I run the page through Twitter Card Validator when I have that .htaccess code, the image does show up fine on the Twitter Card Validator. But as I mentioned, the website breaks because of too many redirects.

I tried removing the .htaccess code and putting the twitter card image in a directory called /social/ and putting this page rule in Cloudflare: example.com/social/ - Disable Security as the first rule (only one rule works per page), and this simply is ignored by twitterbot even though if i manually put the path to the image in that directory it’s correctly not redirecting to https.

```<code><meta property="og:image" content="http://example.com/social/image.jpg">
<meta name="twitter:image" content="http://example.com/social/image.jpg">
</code>```

When validating the page on Twitter Card Validator and using ?utm_source=a-random-number to make sure it's pulling a fresh page, it pulls all the info correctly except for the image. Facebook pulls the image fine, it's just twitterbot's incompatibility with Cloudflare's flexible shared SSL. I'm not on WordPress and this is on Apache. There is currently no .htaccess file. Any ideas?

=============

EDIT

Ok, got it working. The solution of adding:
example.com/social/ - Disable Security
on Cloudflare's SSL page rules was correct, but I also had to include two meta og parameters on the head:

```<code><meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
</code>```

without that the image wouldn't show on Twitter Card Validator, but does when you add it. Hope that helps someone else.

答:
The redirect loop isn't caused by the Twitterbot exception (that would simply prevent the rule being executed), but because you are checking the SERVER_PORT. When using "Cloudflare's flexible shared SSL" your application server is always communicating on port 80 (ie. HTTP). Cloudflare is an SSL proxy. The connection from the client to Cloudflare is secure, but the connection from Cloudflare to your application server is not. Reference: https://support.cloudflare.com/hc/en-us/articles/200170416#h_4e0d1a7c-eb71-4204-9e22-9d3ef9ef7fef

Instead of checking the SERVER_PORT in order to determine whether the client is not yet on an HTTPS connection, you should check the X-Forwarded-Proto HTTP request header instead (set by the Cloudflare proxy). Reference: https://support.cloudflare.com/hc/en-us/articles/200170986-How-does-Cloudflare-handle-HTTP-Request-headers-

For example:

```<code>RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com [NC]
RewriteCond %{HTTP_USER_AGENT} !twitterbot [NC]
RewriteRule (.*) https://www.example.com/$1 [R=301,L]
</code>```

I've combined your two conditions that check the hostname (also avoids the need for the OR flag). Unless you are serving multiple domains/subdomains/hostnames from this account then that condition is not required at all.

You will need to clear your browser cache before testing. (Test with 302 - temporary - redirects to avoid caching issues.)

Body:
Twitter Cards (twitter:image or og:image) won’t allow https from a shared SSL including Cloudflare. The workaround mentioned is to create an .htaccess file and add code to not redirect twitterbot to the shared https. The problem is this is breaking my pages saying there are too many redirects.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTP_HOST} ^example.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteCond %{HTTP_USER_AGENT} !Twitterbot [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]
</IfModule>

That being said, when I run the page through Twitter Card Validator when I have that .htaccess code, the image does show up fine on the Twitter Card Validator. But as I mentioned, the website breaks because of too many redirects.

I tried removing the .htaccess code and putting the twitter card image in a directory called /social/ and putting this page rule in Cloudflare: example.com/social/ - Disable Security as the first rule (only one rule works per page), and this simply is ignored by twitterbot even though if i manually put the path to the image in that directory it’s correctly not redirecting to https.

<meta property="og:image" content="http://example.com/social/image.jpg">
<meta name="twitter:image" content="http://example.com/social/image.jpg">

When validating the page on Twitter Card Validator and using ?utm_source=a-random-number to make sure it's pulling a fresh page, it pulls all the info correctly except for the image. Facebook pulls the image fine, it's just twitterbot's incompatibility with Cloudflare's flexible shared SSL. I'm not on WordPress and this is on Apache. There is currently no .htaccess file. Any ideas?

=============

EDIT

Ok, got it working. The solution of adding:
example.com/social/ - Disable Security
on Cloudflare's SSL page rules was correct, but I also had to include two meta og parameters on the head:

<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />

without that the image wouldn't show on Twitter Card Validator, but does when you add it. Hope that helps someone else.

Body:
The redirect loop isn't caused by the Twitterbot exception (that would simply prevent the rule being executed), but because you are checking the SERVER_PORT. When using "Cloudflare's flexible shared SSL" your application server is always communicating on port 80 (ie. HTTP). Cloudflare is an SSL proxy. The connection from the client to Cloudflare is secure, but the connection from Cloudflare to your application server is not. Reference: https://support.cloudflare.com/hc/en-us/articles/200170416#h_4e0d1a7c-eb71-4204-9e22-9d3ef9ef7fef

Instead of checking the SERVER_PORT in order to determine whether the client is not yet on an HTTPS connection, you should check the X-Forwarded-Proto HTTP request header instead (set by the Cloudflare proxy). Reference: https://support.cloudflare.com/hc/en-us/articles/200170986-How-does-Cloudflare-handle-HTTP-Request-headers-

For example:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com [NC]
RewriteCond %{HTTP_USER_AGENT} !twitterbot [NC]
RewriteRule (.*) https://www.example.com/$1 [R=301,L]

I've combined your two conditions that check the hostname (also avoids the need for the OR flag). Unless you are serving multiple domains/subdomains/hostnames from this account then that condition is not required at all.

You will need to clear your browser cache before testing. (Test with 302 - temporary - redirects to avoid caching issues.)


问:
GitLab CE docker container keeps crashing at startup
I'm trying to run GitLab CE edition as a docker container (gitlab/gitlab-ce) via docker compose, following the instructions at http://doc.gitlab.com/omnibus/docker.

The problem is that every time I start with docker-compose up -d, the container crashes/exits after about a minute. I collected all information that could be useful, there are some chef-related error message that I'm not able to decrypt. The environment runs insides an Ubuntu Vagrant virtual machine.

I tried to use a different tagged version of the image instead of the :latest, but getting similar results.

docker-compose.yml relevant snippet:

```<code>gitlab:
    image: gitlab/gitlab-ce
    container_name: my_gitlab
    volumes:
    - ./runtime/gitlab/config:/etc/gitlab
    - ./runtime/gitlab/data:/var/opt/gitlab
    - ./runtime/gitlab/logs:/var/log/gitlab
    ports:
    - 443:443
    - 22:22
    - 8082:80
</code>```

following is the log file saved in ./runtime/gitlab/logs (volume for /var/log/gitlab)

```<code># Logfile created on 2016-04-28 08:07:43 +0000 by logger.rb/44203
[2016-04-28T08:07:44+00:00] INFO: Started chef-zero at chefzero://localhost:8889 with repository at /opt/gitlab/embedded
  One version per cookbook

[2016-04-28T08:07:44+00:00] INFO: Forking chef instance to converge...
[2016-04-28T08:07:44+00:00] INFO: *** Chef 12.6.0 ***
[2016-04-28T08:07:44+00:00] INFO: Chef-client pid: 36
[2016-04-28T08:07:47+00:00] INFO: HTTP Request Returned 404 Not Found: Object not found: chefzero://localhost:8889/nodes/bcfc5b569532
[2016-04-28T08:07:48+00:00] INFO: Setting the run_list to ["recipe[gitlab]"] from CLI options
[2016-04-28T08:07:48+00:00] INFO: Run List is [recipe[gitlab]]
[2016-04-28T08:07:48+00:00] INFO: Run List expands to [gitlab]
[2016-04-28T08:07:48+00:00] INFO: Starting Chef Run for bcfc5b569532
[2016-04-28T08:07:48+00:00] INFO: Running start handlers
[2016-04-28T08:07:48+00:00] INFO: Start handlers complete.
[2016-04-28T08:07:48+00:00] INFO: HTTP Request Returned 404 Not Found: Object not found:
[2016-04-28T08:07:52+00:00] INFO: Loading cookbooks [gitlab@0.0.1, runit@0.14.2, package@0.0.0]
[2016-04-28T08:07:54+00:00] INFO: directory[/etc/gitlab] owner changed to 0
[2016-04-28T08:07:54+00:00] INFO: directory[/etc/gitlab] group changed to 0
[2016-04-28T08:07:54+00:00] INFO: directory[/etc/gitlab] mode changed to 775
[2016-04-28T08:07:54+00:00] WARN: Cloning resource attributes for directory[/var/opt/gitlab] from prior resource (CHEF-3694)
[2016-04-28T08:07:54+00:00] WARN: Previous directory[/var/opt/gitlab]: /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/default.rb:43:in `from_file'
[2016-04-28T08:07:54+00:00] WARN: Current  directory[/var/opt/gitlab]: /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/users.rb:24:in `from_file'
[2016-04-28T08:07:54+00:00] WARN: Selected upstart because /sbin/init --version is showing upstart.
[2016-04-28T08:07:54+00:00] WARN: Cloning resource attributes for directory[/etc/sysctl.d] from prior resource (CHEF-3694)
[2016-04-28T08:07:54+00:00] WARN: Previous directory[/etc/sysctl.d]: /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/definitions/sysctl.rb:22:in `block in from_file'
[2016-04-28T08:07:54+00:00] WARN: Current  directory[/etc/sysctl.d]: /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/definitions/sysctl.rb:22:in `block in from_file'
[2016-04-28T08:07:54+00:00] WARN: Cloning resource attributes for file[/etc/sysctl.d/90-postgresql.conf] from prior resource (CHEF-3694)
.
. several similar WARN: log entries
.
[2016-04-28T08:07:55+00:00] INFO: directory[/var/opt/gitlab] owner changed to 0
[2016-04-28T08:07:55+00:00] INFO: directory[/var/opt/gitlab] group changed to 0
[2016-04-28T08:07:55+00:00] INFO: directory[/var/opt/gitlab] mode changed to 755

.
.
.
[2016-04-28T08:07:57+00:00] INFO: template[/var/opt/gitlab/gitlab-rails/etc/rack_attack.rb] owner changed to 0
[2016-04-28T08:07:57+00:00] INFO: template[/var/opt/gitlab/gitlab-rails/etc/rack_attack.rb] group changed to 0
[2016-04-28T08:07:57+00:00] INFO: template[/var/opt/gitlab/gitlab-rails/etc/rack_attack.rb] mode changed to 644
[2016-04-28T08:07:58+00:00] INFO: Running queued delayed notifications before re-raising exception
[2016-04-28T08:07:58+00:00] INFO: template[/var/opt/gitlab/gitlab-rails/etc/gitlab.yml] sending run action to execute[clear the gitlab-rails cache] (delayed)
[2016-04-28T08:09:02+00:00] ERROR: Running exception handlers
[2016-04-28T08:09:02+00:00] ERROR: Exception handlers complete
[2016-04-28T08:09:02+00:00] FATAL: Stacktrace dumped to /opt/gitlab/embedded/cookbooks/cache/chef-stacktrace.out
[2016-04-28T08:09:02+00:00] FATAL: Please provide the contents of the stacktrace.out file if you file a bug report
[2016-04-28T08:09:02+00:00] ERROR: Chef::Exceptions::MultipleFailures
[2016-04-28T08:09:02+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)

/opt/gitlab/embedded/bin/chef-client:23:in `<main>'root@bcfc5b569532:/# tail -f /opt/gitlab/embedded/cookbooks/cache/chef-stacktrace.out

/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/lib/chef/local_mode.rb:44:in `with_server_connectivity'
/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/lib/chef/application.rb:203:in `run_chef_client'
/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/lib/chef/application/client.rb:413:in `block in interval_run_chef_client'
/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/lib/chef/application/client.rb:403:in `loop'
/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/lib/chef/application/client.rb:403:in `interval_run_chef_client'
/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/lib/chef/application/client.rb:393:in `run_application'
/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/lib/chef/application.rb:58:in `run'
/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/bin/chef-client:26:in `<top (required)>'
/opt/gitlab/embedded/bin/chef-client:23:in `load'
/opt/gitlab/embedded/bin/chef-client:23:in `<main>'

<...here the container terminates and my exec bash shell returns...>
</code>```

Below the output from docker logs -f for the container. The log is very long (>12K lines), so I tried to look for lines containing useful info but am not sure I found them all:

```<code>Thank you for using GitLab Docker Image!
Current version: gitlab-ce=8.7.0-ce.0

Configure GitLab for your system by editing /etc/gitlab/gitlab.rb file
And restart this container to reload settings.
To do it use docker exec:

  docker exec -it gitlab vim /etc/gitlab/gitlab.rb
  docker restart gitlab

For a comprehensive list of configuration options please see the Omnibus GitLab readme
https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/README.md

If this container fails to start due to permission problems try to fix it by executing:

  docker exec -it gitlab update-permissions
  docker restart gitlab

Preparing services...
Starting services...
Configuring GitLab package...
Configuring GitLab...
[2016-04-28T08:02:39+00:00] INFO: GET /organizations/chef/nodes/bcfc5b569532
[2016-04-28T08:02:39+00:00] INFO: #<ChefZero::RestErrorResponse: 404: Object not found: chefzero://localhost:8889/nodes/bcfc5b569532>

.
.
.
/opt/gitlab/embedded/bin/chef-client:23:in `load'
/opt/gitlab/embedded/bin/chef-client:23:in `<main>'
[2016-04-28T08:02:39+00:00] INFO:
--- RESPONSE (404) ---
{
  "error": [
    "Object not found: chefzero://localhost:8889/nodes/bcfc5b569532"
  ]
}
--- END RESPONSE ---
.
.
.
...a lot of logs (~12K lines), including some errors like the following one:
.
.
.
--- END RESPONSE ---
init (upstart 1.12.1)
[0m
================================================================================[0m
[31mError executing action `create` on resource 'link[/var/log/gitlab/gitlab-rails/sidekiq.log]'[0m
================================================================================[0m

[0mErrno::EPROTO[0m
-------------[0m
Protocol error @ sys_fail2 - (/var/log/gitlab/sidekiq/current, /var/log/gitlab/gitlab-rails/sidekiq.log)[0m
.
.
.
================================================================================
Error executing action `create` on resource 'link[/var/log/gitlab/gitlab-rails/sidekiq.log]'
================================================================================

Errno::EPROTO
-------------
Protocol error @ sys_fail2 - (/var/log/gitlab/sidekiq/current, /var/log/gitlab/gitlab-rails/sidekiq.log)

Resource Declaration:
---------------------
# In /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/gitlab-rails.rb

281: link legacy_sidekiq_log_file do
282:   to File.join(node['gitlab']['sidekiq']['log_directory'], 'current')
283:   not_if { File.exists?(legacy_sidekiq_log_file) }
284: end
285:

Compiled Resource:
------------------
# Declared in /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/gitlab-rails.rb:281:in `from_file'

link("/var/log/gitlab/gitlab-rails/sidekiq.log") do
  action [:create]
  retries 0
  retry_delay 2
  default_guard_interpreter :default
  to "/var/log/gitlab/sidekiq/current"
  link_type :symbolic
  target_file "/var/log/gitlab/gitlab-rails/sidekiq.log"
  declared_type :link
  cookbook_name "gitlab"
  recipe_name "gitlab-rails"
  not_if { #code block }
end

<output ends>
</code>```

答:
```<code>sudo chmod g+s /opt/gitlab/data/git-data/repositories/
</code>```

Where /opt/gitlab/ is the linked docker share

Body:
I'm trying to run GitLab CE edition as a docker container (gitlab/gitlab-ce) via docker compose, following the instructions at http://doc.gitlab.com/omnibus/docker.

The problem is that every time I start with docker-compose up -d, the container crashes/exits after about a minute. I collected all information that could be useful, there are some chef-related error message that I'm not able to decrypt. The environment runs insides an Ubuntu Vagrant virtual machine.

I tried to use a different tagged version of the image instead of the :latest, but getting similar results.

docker-compose.yml relevant snippet:

gitlab:
    image: gitlab/gitlab-ce
    container_name: my_gitlab
    volumes:
    - ./runtime/gitlab/config:/etc/gitlab
    - ./runtime/gitlab/data:/var/opt/gitlab
    - ./runtime/gitlab/logs:/var/log/gitlab
    ports:
    - 443:443
    - 22:22
    - 8082:80

following is the log file saved in ./runtime/gitlab/logs (volume for /var/log/gitlab)

# Logfile created on 2016-04-28 08:07:43 +0000 by logger.rb/44203
[2016-04-28T08:07:44+00:00] INFO: Started chef-zero at chefzero://localhost:8889 with repository at /opt/gitlab/embedded
  One version per cookbook

[2016-04-28T08:07:44+00:00] INFO: Forking chef instance to converge...
[2016-04-28T08:07:44+00:00] INFO: *** Chef 12.6.0 ***
[2016-04-28T08:07:44+00:00] INFO: Chef-client pid: 36
[2016-04-28T08:07:47+00:00] INFO: HTTP Request Returned 404 Not Found: Object not found: chefzero://localhost:8889/nodes/bcfc5b569532
[2016-04-28T08:07:48+00:00] INFO: Setting the run_list to ["recipe[gitlab]"] from CLI options
[2016-04-28T08:07:48+00:00] INFO: Run List is [recipe[gitlab]]
[2016-04-28T08:07:48+00:00] INFO: Run List expands to [gitlab]
[2016-04-28T08:07:48+00:00] INFO: Starting Chef Run for bcfc5b569532
[2016-04-28T08:07:48+00:00] INFO: Running start handlers
[2016-04-28T08:07:48+00:00] INFO: Start handlers complete.
[2016-04-28T08:07:48+00:00] INFO: HTTP Request Returned 404 Not Found: Object not found:
[2016-04-28T08:07:52+00:00] INFO: Loading cookbooks [gitlab@0.0.1, runit@0.14.2, package@0.0.0]
[2016-04-28T08:07:54+00:00] INFO: directory[/etc/gitlab] owner changed to 0
[2016-04-28T08:07:54+00:00] INFO: directory[/etc/gitlab] group changed to 0
[2016-04-28T08:07:54+00:00] INFO: directory[/etc/gitlab] mode changed to 775
[2016-04-28T08:07:54+00:00] WARN: Cloning resource attributes for directory[/var/opt/gitlab] from prior resource (CHEF-3694)
[2016-04-28T08:07:54+00:00] WARN: Previous directory[/var/opt/gitlab]: /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/default.rb:43:in `from_file'
[2016-04-28T08:07:54+00:00] WARN: Current  directory[/var/opt/gitlab]: /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/users.rb:24:in `from_file'
[2016-04-28T08:07:54+00:00] WARN: Selected upstart because /sbin/init --version is showing upstart.
[2016-04-28T08:07:54+00:00] WARN: Cloning resource attributes for directory[/etc/sysctl.d] from prior resource (CHEF-3694)
[2016-04-28T08:07:54+00:00] WARN: Previous directory[/etc/sysctl.d]: /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/definitions/sysctl.rb:22:in `block in from_file'
[2016-04-28T08:07:54+00:00] WARN: Current  directory[/etc/sysctl.d]: /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/definitions/sysctl.rb:22:in `block in from_file'
[2016-04-28T08:07:54+00:00] WARN: Cloning resource attributes for file[/etc/sysctl.d/90-postgresql.conf] from prior resource (CHEF-3694)
.
. several similar WARN: log entries
.
[2016-04-28T08:07:55+00:00] INFO: directory[/var/opt/gitlab] owner changed to 0
[2016-04-28T08:07:55+00:00] INFO: directory[/var/opt/gitlab] group changed to 0
[2016-04-28T08:07:55+00:00] INFO: directory[/var/opt/gitlab] mode changed to 755

.
.
.
[2016-04-28T08:07:57+00:00] INFO: template[/var/opt/gitlab/gitlab-rails/etc/rack_attack.rb] owner changed to 0
[2016-04-28T08:07:57+00:00] INFO: template[/var/opt/gitlab/gitlab-rails/etc/rack_attack.rb] group changed to 0
[2016-04-28T08:07:57+00:00] INFO: template[/var/opt/gitlab/gitlab-rails/etc/rack_attack.rb] mode changed to 644
[2016-04-28T08:07:58+00:00] INFO: Running queued delayed notifications before re-raising exception
[2016-04-28T08:07:58+00:00] INFO: template[/var/opt/gitlab/gitlab-rails/etc/gitlab.yml] sending run action to execute[clear the gitlab-rails cache] (delayed)
[2016-04-28T08:09:02+00:00] ERROR: Running exception handlers
[2016-04-28T08:09:02+00:00] ERROR: Exception handlers complete
[2016-04-28T08:09:02+00:00] FATAL: Stacktrace dumped to /opt/gitlab/embedded/cookbooks/cache/chef-stacktrace.out
[2016-04-28T08:09:02+00:00] FATAL: Please provide the contents of the stacktrace.out file if you file a bug report
[2016-04-28T08:09:02+00:00] ERROR: Chef::Exceptions::MultipleFailures
[2016-04-28T08:09:02+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)

/opt/gitlab/embedded/bin/chef-client:23:in `'root@bcfc5b569532:/# tail -f /opt/gitlab/embedded/cookbooks/cache/chef-stacktrace.out

/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/lib/chef/local_mode.rb:44:in `with_server_connectivity'
/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/lib/chef/application.rb:203:in `run_chef_client'
/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/lib/chef/application/client.rb:413:in `block in interval_run_chef_client'
/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/lib/chef/application/client.rb:403:in `loop'
/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/lib/chef/application/client.rb:403:in `interval_run_chef_client'
/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/lib/chef/application/client.rb:393:in `run_application'
/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/lib/chef/application.rb:58:in `run'
/opt/gitlab/embedded/lib/ruby/gems/2.1.0/gems/chef-12.6.0/bin/chef-client:26:in `<top (required)>'
/opt/gitlab/embedded/bin/chef-client:23:in `load'
/opt/gitlab/embedded/bin/chef-client:23:in `'

<...here the container terminates and my exec bash shell returns...>

Below the output from docker logs -f for the container. The log is very long (>12K lines), so I tried to look for lines containing useful info but am not sure I found them all:

Thank you for using GitLab Docker Image!
Current version: gitlab-ce=8.7.0-ce.0

Configure GitLab for your system by editing /etc/gitlab/gitlab.rb file
And restart this container to reload settings.
To do it use docker exec:

  docker exec -it gitlab vim /etc/gitlab/gitlab.rb
  docker restart gitlab

For a comprehensive list of configuration options please see the Omnibus GitLab readme
https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/README.md

If this container fails to start due to permission problems try to fix it by executing:

  docker exec -it gitlab update-permissions
  docker restart gitlab

Preparing services...
Starting services...
Configuring GitLab package...
Configuring GitLab...
[2016-04-28T08:02:39+00:00] INFO: GET /organizations/chef/nodes/bcfc5b569532
[2016-04-28T08:02:39+00:00] INFO: #<ChefZero::RestErrorResponse: 404: Object not found: chefzero://localhost:8889/nodes/bcfc5b569532>

.
.
.
/opt/gitlab/embedded/bin/chef-client:23:in `load'
/opt/gitlab/embedded/bin/chef-client:23:in `'
[2016-04-28T08:02:39+00:00] INFO:
--- RESPONSE (404) ---
{
  "error": [
    "Object not found: chefzero://localhost:8889/nodes/bcfc5b569532"
  ]
}
--- END RESPONSE ---
.
.
.
...a lot of logs (~12K lines), including some errors like the following one:
.
.
.
--- END RESPONSE ---
init (upstart 1.12.1)
[0m
================================================================================[0m
[31mError executing action `create` on resource 'link[/var/log/gitlab/gitlab-rails/sidekiq.log]'[0m
================================================================================[0m

[0mErrno::EPROTO[0m
-------------[0m
Protocol error @ sys_fail2 - (/var/log/gitlab/sidekiq/current, /var/log/gitlab/gitlab-rails/sidekiq.log)[0m
.
.
.
================================================================================
Error executing action `create` on resource 'link[/var/log/gitlab/gitlab-rails/sidekiq.log]'
================================================================================

Errno::EPROTO
-------------
Protocol error @ sys_fail2 - (/var/log/gitlab/sidekiq/current, /var/log/gitlab/gitlab-rails/sidekiq.log)

Resource Declaration:
---------------------
# In /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/gitlab-rails.rb

281: link legacy_sidekiq_log_file do
282:   to File.join(node['gitlab']['sidekiq']['log_directory'], 'current')
283:   not_if { File.exists?(legacy_sidekiq_log_file) }
284: end
285:

Compiled Resource:
------------------
# Declared in /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/gitlab-rails.rb:281:in `from_file'

link("/var/log/gitlab/gitlab-rails/sidekiq.log") do
  action [:create]
  retries 0
  retry_delay 2
  default_guard_interpreter :default
  to "/var/log/gitlab/sidekiq/current"
  link_type :symbolic
  target_file "/var/log/gitlab/gitlab-rails/sidekiq.log"
  declared_type :link
  cookbook_name "gitlab"
  recipe_name "gitlab-rails"
  not_if { #code block }
end

<output ends>

Body:
sudo chmod g+s /opt/gitlab/data/git-data/repositories/

Where /opt/gitlab/ is the linked docker share


问:
Watson is already running. Second session cannot be started
I have installed IBM watson studio but when i attempt to open it, I am getting an error stating " Watson is already running. Second session cannot be started"</p>

答: It happened to me after I updated to the new version. I had to kill the process from the task manager and now the studio doesn't start up and actually 'show' unless it was Run As Administrator. Try that out, kill the process and re-run it but as admin.</p>


问:
Python Loop for temperature
I am learning python for the first time and my assignment required me to:

Write a loop to print all elements in hourly_temperature. Separate
elements with a -> surrounded by spaces. Sample output for the given
program:

```<code>90 -> 92 -> 94 -> 95
</code>```

Note: 95 is followed by a space, then a newline.

After playing I had difficulty and found the coded answer as:

```<code>hourly_temperature = [90, 92, 94, 95]

Htemp = len(hourly_temperature)

#create list
temps = []

if Htemp >= 0:
    for i in hourly_temperature: #question on i and appends i
        temps.append(i)
        temps.append('->')
        Htemp -= 1
        continue
temps.pop()
for s in temps:    #question here
    print(s,'', end='')
    continue
print('')
</code>```

My question is regarding the for loops that I have notated with the #question.

I am wondering what the purpose is for the i and s to make the code work.

答:
Your example is very messy and can be made very small

For Example:

hourly_temperature = [90, 92, 94, 95]
joined_temps = " -> ".join(map(str, hourly_temperature)) + " " # Add the temperatures together with " -> " as separaters and add the space as you said
print(joined_temps)
```

<p><code>"separater".join(typing.Union[list, tuple])</code> joins a list or tuple together separated by the given separater, then we add the space as you said</p>

<p>Then we print it because print already provides a newline at the end of the string</p>

<p>If you would like it a for loop form</p>

<pre class="lang-py prettyprint-override"><code>hourly_temperature = [90, 92, 94, 95]
ordered_temps = []
for temp in hourly_temperature:
    ordered_temps.append(temp)
    if not temp == hourly_temperature[-1]:
        ordered_temps.append(" -> ")
    else:
        ordered_temps.append(" ")
print("".join(map(str, ordered_temps)))
</code>```

We are once using join again but this has no separater, so it will only join the list.

Title: Python Loop for temperature

Body:
I am learning python for the first time and my assignment required me to:

Write a loop to print all elements in hourly_temperature. Separate
elements with a -> surrounded by spaces. Sample output for the given
program:

90 -> 92 -> 94 -> 95

Note: 95 is followed by a space, then a newline.

After playing I had difficulty and found the coded answer as:

hourly_temperature = [90, 92, 94, 95]

Htemp = len(hourly_temperature)

#create list
temps = []

if Htemp >= 0:
    for i in hourly_temperature: #question on i and appends i
        temps.append(i)
        temps.append('->')
        Htemp -= 1
        continue
temps.pop()
for s in temps:    #question here
    print(s,'', end='')
    continue
print('')

My question is regarding the for loops that I have notated with the #question.

I am wondering what the purpose is for the i and s to make the code work.

Body:
Your example is very messy and can be made very small

For Example:

hourly_temperature = [90, 92, 94, 95]
joined_temps = " -> ".join(map(str, hourly_temperature)) + " " # Add the temperatures together with " -> " as separaters and add the space as you said
print(joined_temps)

"separater".join(typing.Union[list, tuple]) joins a list or tuple together separated by the given separater, then we add the space as you said

Then we print it because print already provides a newline at the end of the string

If you would like it a for loop form

hourly_temperature = [90, 92, 94, 95]
ordered_temps = []
for temp in hourly_temperature:
    ordered_temps.append(temp)
    if not temp == hourly_temperature[-1]:
        ordered_temps.append(" -> ")
    else:
        ordered_temps.append(" ")
print("".join(map(str, ordered_temps)))

We are once using join again but this has no separater, so it will only join the list.