问:
Error restoring databse with transact SQL
I'm trying to restore a database with a .bak file created previously from another server.

The .bak has been created on a server where the SQL path is the E unit, and
in the new server the path is C.

PATH SQL DATABASE SOURCE

```<code>E:\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA
</code>```

PATH DATABASE DESTINATION

```<code>C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA
</code>```

Query restore

```<code>RESTORE DATABASE admin_usuarios
FROM DISK = 'C:\backup\admin_usuarios.bak'
WITH REPLACE;
</code>```

ERROR

Msg 5133, Level 16, State 1, Line 4
  Error searching the file "E: \ Microsoft SQL Server \ MSSQL13.MSSQLSERVER \ MSSQL \ DATA \ admin_usuarios.mdf" in the directories, operating system error: 3 (The system can not find the specified path.).

Query used to create backup

```<code>BACKUP DATABASE admin_usuarios
TO DISK = 'E:\BackupSQL\admin_usuarios.bak'
WITH FORMAT;
</code>```

答:
You need to use RESTORE WITH MOVE syntax:</p>

```<code>RESTORE DATABASE admin_usuarios FROM DISK = 'C:\backup\admin_usuarios.bak'
WITH
MOVE date_file_logical_name TO 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\admin_usuarios_Data.mdf',
MOVE log_file_logical_name TO 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\admin_usuarios_Log.ldf',
REPLACE;
</code>```

Body:
I'm trying to restore a database with a .bak file created previously from another server.

The .bak has been created on a server where the SQL path is the E unit, and
in the new server the path is C.

PATH SQL DATABASE SOURCE

E:\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA

PATH DATABASE DESTINATION

C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA

Query restore

RESTORE DATABASE admin_usuarios
FROM DISK = 'C:\backup\admin_usuarios.bak'
WITH REPLACE;

ERROR

Msg 5133, Level 16, State 1, Line 4
  Error searching the file "E: \ Microsoft SQL Server \ MSSQL13.MSSQLSERVER \ MSSQL \ DATA \ admin_usuarios.mdf" in the directories, operating system error: 3 (The system can not find the specified path.).

Query used to create backup

BACKUP DATABASE admin_usuarios
TO DISK = 'E:\BackupSQL\admin_usuarios.bak'
WITH FORMAT;

Body:
You need to use RESTORE WITH MOVE syntax:

RESTORE DATABASE admin_usuarios FROM DISK = 'C:\backup\admin_usuarios.bak'
WITH
MOVE date_file_logical_name TO 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\admin_usuarios_Data.mdf',
MOVE log_file_logical_name TO 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\admin_usuarios_Log.ldf',
REPLACE;


来源: stackexchange

问:
How do you mock the value of *ec2.DescribeVolumesOutput
I am currently trying to get used to TDD and on a current project I am working on I am trying to leverage AWS's Go SDK. Which is all fine and dandy and I have used it before but I am currently trying to mock the value that *ec2.DescribeVolumesOutput sends.

Diving into the code I see this as what returns for *ec2.DescribeVolumesOutput:

type DescribeVolumesOutput struct {
    _ struct{} `type:"structure"`

    // The NextToken value to include in a future DescribeVolumes request. When
    // the results of a DescribeVolumes request exceed MaxResults, this value can
    // be used to retrieve the next page of results. This value is null when there
    // are no more results to return.
    NextToken *string `locationName:"nextToken" type:"string"`

    // Information about the volumes.
    Volumes []*Volume `locationName:"volumeSet" locationNameList:"item" type:"list"`
}
```

<p>Okay.. That's cool, but what I want to mock the output of must live inside of <code>Volumes []*Volume</code>locationName:"volumeSet" locationNameList:"item" type:"list"` so let's go a little deeper and see what that is...</p>

<pre class="lang-golang prettyprint-override"><code>type Volume struct {
    _ struct{} `type:"structure"`

    // Information about the volume attachments.
    Attachments []*VolumeAttachment `locationName:"attachmentSet" locationNameList:"item" type:"list"`

    // The Availability Zone for the volume.
    AvailabilityZone *string `locationName:"availabilityZone" type:"string"`

    // The time stamp when volume creation was initiated.
    CreateTime *time.Time `locationName:"createTime" type:"timestamp"`

    // Indicates whether the volume will be encrypted.
    Encrypted *bool `locationName:"encrypted" type:"boolean"`

    // The number of I/O operations per second (IOPS) that the volume supports.
    // For Provisioned IOPS SSD volumes, this represents the number of IOPS that
    // are provisioned for the volume. For General Purpose SSD volumes, this represents
    // the baseline performance of the volume and the rate at which the volume accumulates
    // I/O credits for bursting. For more information, see Amazon EBS Volume Types
    // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html)
    // in the Amazon Elastic Compute Cloud User Guide.
    //
    // Constraints: Range is 100-16,000 IOPS for gp2 volumes and 100 to 64,000IOPS
    // for io1 volumes, in most Regions. The maximum IOPS for io1 of 64,000 is guaranteed
    // only on Nitro-based instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances).
    // Other instance families guarantee performance up to 32,000 IOPS.
    //
    // Condition: This parameter is required for requests to create io1 volumes;
    // it is not used in requests to create gp2, st1, sc1, or standard volumes.
    Iops *int64 `locationName:"iops" type:"integer"`

    // The full ARN of the AWS Key Management Service (AWS KMS) customer master
    // key (CMK) that was used to protect the volume encryption key for the volume.
    KmsKeyId *string `locationName:"kmsKeyId" type:"string"`

    // The size of the volume, in GiBs.
    Size *int64 `locationName:"size" type:"integer"`

    // The snapshot from which the volume was created, if applicable.
    SnapshotId *string `locationName:"snapshotId" type:"string"`

    // The volume state.
    State *string `locationName:"status" type:"string" enum:"VolumeState"`

    // Any tags assigned to the volume.
    Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"`

    // The ID of the volume.
    VolumeId *string `locationName:"volumeId" type:"string"`

    // The volume type. This can be gp2 for General Purpose SSD, io1 for Provisioned
    // IOPS SSD, st1 for Throughput Optimized HDD, sc1 for Cold HDD, or standard
    // for Magnetic volumes.
    VolumeType *string `locationName:"volumeType" type:"string" enum:"VolumeType"`
}
</code>```

Nice! this looks like some data that I want to mock the values of!

But over the last couple of days I have had no luck in actually mocking these values. Are they so nested that this type of mocking is not worth the effort? Even trying to use the github.com/aws/aws-sdk-go/service/ec2/ec2iface does not seem to help me wrap my head around how to properly package some mock value returns to test. Am I coming at TDD all wrong? am I missing something super obvious? I do not really have example code to show since I now no longer understand what I am trying to do.

Does anyone possibly have an example of how they have mocked this?

答:
There is no way to mock the type, you are able to mock only implementation of the interface. In your case I assume that you are trying to call DescribeVolumes and in the response get value constructed by you.

To do that you need to create a mock like

type MockEC2API struct {
    ec2iface.EC2API // embedding of the interface is needed to skip implementation of all methods
    DescribeVolumesMethod func(*ec2.DescribeVolumesInput) (*ec2.DescribeVolumesOutput, error)
}

func (m *MockEC2API) DescribeVolumes(in *ec2.DescribeVolumesInput) (*ec2.DescribeVolumesOutput, error) {
    if m.DescribeVolumesMethod != nil {
        return m.DescribeVolumesMethod(in)
    }
    return nil, nil // return any value you think is good for you
}
```

<p>In the test create instance of <code>MockEC2API</code> instead of the real <code>ec2.EC2</code> and provide it with function that will be called and return your's prepared <code>ec2.DescribeVolumesOutput</code> result</p>

<pre class="lang-golang prettyprint-override"><code>...
ec2 := &MockEC2API{
    DescribeVolumesMethod: func(*ec2.DescribeVolumesInput) (*ec2.DescribeVolumesOutput, error) {
        return &ec2.DescribeVolumesOutput{...your initialization...}, nil
    }
}
...
output, err := ec2.DescribeVolumes(in) // this output will be your prepared initialization

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am currently trying to get used to TDD and on a current project I am working on I am trying to leverage AWS's Go SDK. Which is all fine and dandy and I have used it before but I am currently trying to mock the value that *ec2.DescribeVolumesOutput sends.

Diving into the code I see this as what returns for *ec2.DescribeVolumesOutput:

type DescribeVolumesOutput struct {
    _ struct{} `type:"structure"`

    // The NextToken value to include in a future DescribeVolumes request. When
    // the results of a DescribeVolumes request exceed MaxResults, this value can
    // be used to retrieve the next page of results. This value is null when there
    // are no more results to return.
    NextToken *string `locationName:"nextToken" type:"string"`

    // Information about the volumes.
    Volumes []*Volume `locationName:"volumeSet" locationNameList:"item" type:"list"`
}

Okay.. That's cool, but what I want to mock the output of must live inside of Volumes []*VolumelocationName:"volumeSet" locationNameList:"item" type:"list"` so let's go a little deeper and see what that is...

type Volume struct {
    _ struct{} `type:"structure"`

    // Information about the volume attachments.
    Attachments []*VolumeAttachment `locationName:"attachmentSet" locationNameList:"item" type:"list"`

    // The Availability Zone for the volume.
    AvailabilityZone *string `locationName:"availabilityZone" type:"string"`

    // The time stamp when volume creation was initiated.
    CreateTime *time.Time `locationName:"createTime" type:"timestamp"`

    // Indicates whether the volume will be encrypted.
    Encrypted *bool `locationName:"encrypted" type:"boolean"`

    // The number of I/O operations per second (IOPS) that the volume supports.
    // For Provisioned IOPS SSD volumes, this represents the number of IOPS that
    // are provisioned for the volume. For General Purpose SSD volumes, this represents
    // the baseline performance of the volume and the rate at which the volume accumulates
    // I/O credits for bursting. For more information, see Amazon EBS Volume Types
    // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html)
    // in the Amazon Elastic Compute Cloud User Guide.
    //
    // Constraints: Range is 100-16,000 IOPS for gp2 volumes and 100 to 64,000IOPS
    // for io1 volumes, in most Regions. The maximum IOPS for io1 of 64,000 is guaranteed
    // only on Nitro-based instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances).
    // Other instance families guarantee performance up to 32,000 IOPS.
    //
    // Condition: This parameter is required for requests to create io1 volumes;
    // it is not used in requests to create gp2, st1, sc1, or standard volumes.
    Iops *int64 `locationName:"iops" type:"integer"`

    // The full ARN of the AWS Key Management Service (AWS KMS) customer master
    // key (CMK) that was used to protect the volume encryption key for the volume.
    KmsKeyId *string `locationName:"kmsKeyId" type:"string"`

    // The size of the volume, in GiBs.
    Size *int64 `locationName:"size" type:"integer"`

    // The snapshot from which the volume was created, if applicable.
    SnapshotId *string `locationName:"snapshotId" type:"string"`

    // The volume state.
    State *string `locationName:"status" type:"string" enum:"VolumeState"`

    // Any tags assigned to the volume.
    Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"`

    // The ID of the volume.
    VolumeId *string `locationName:"volumeId" type:"string"`

    // The volume type. This can be gp2 for General Purpose SSD, io1 for Provisioned
    // IOPS SSD, st1 for Throughput Optimized HDD, sc1 for Cold HDD, or standard
    // for Magnetic volumes.
    VolumeType *string `locationName:"volumeType" type:"string" enum:"VolumeType"`
}

Nice! this looks like some data that I want to mock the values of!

But over the last couple of days I have had no luck in actually mocking these values. Are they so nested that this type of mocking is not worth the effort? Even trying to use the github.com/aws/aws-sdk-go/service/ec2/ec2iface does not seem to help me wrap my head around how to properly package some mock value returns to test. Am I coming at TDD all wrong? am I missing something super obvious? I do not really have example code to show since I now no longer understand what I am trying to do.

Does anyone possibly have an example of how they have mocked this?

Body:
There is no way to mock the type, you are able to mock only implementation of the interface. In your case I assume that you are trying to call DescribeVolumes and in the response get value constructed by you.

To do that you need to create a mock like

type MockEC2API struct {
    ec2iface.EC2API // embedding of the interface is needed to skip implementation of all methods
    DescribeVolumesMethod func(*ec2.DescribeVolumesInput) (*ec2.DescribeVolumesOutput, error)
}

func (m *MockEC2API) DescribeVolumes(in *ec2.DescribeVolumesInput) (*ec2.DescribeVolumesOutput, error) {
    if m.DescribeVolumesMethod != nil {
        return m.DescribeVolumesMethod(in)
    }
    return nil, nil // return any value you think is good for you
}

In the test create instance of MockEC2API instead of the real ec2.EC2 and provide it with function that will be called and return your's prepared ec2.DescribeVolumesOutput result

...
ec2 := &MockEC2API{
    DescribeVolumesMethod: func(*ec2.DescribeVolumesInput) (*ec2.DescribeVolumesOutput, error) {
        return &ec2.DescribeVolumesOutput{...your initialization...}, nil
    }
}
...
output, err := ec2.DescribeVolumes(in) // this output will be your prepared initialization


问:
ImageMagick: Non-linear stretching an image along one axis
When downloading images from the METEOR M-2 satellite, the image is compressed near the edges. This is corrected by a windows utility called SmoothMeteor. The problem with this app is that it's windows only, and doesn't seem to have a batch mode.

Is it possible to use ImageMagick to stretch an image only along the X axis, so that in the center there is no stretching, but the closer it is near the border, the more stretching is applied?

An example is provided here:

Notice how the center of the map is largely unaffected but the clouds near the left edge look about 4 times wider than the original.

I would guess this is like a pincushion transformation but only on the X axis, but I'm not sure if I'm even in the right track.

答:
What is your platform? If on Unix-like (Linux, Mac OSX, Window 10 Unix or Windows w/Cygwin), then I have a bash shell script calling ImageMagick, called "xpand", that does what you ask.  See my web site at http://www.fmwconcepts.com/imagemagick/index.php

Input:

```<code>xpand -d 350 -m horizontal img.png result.png
</code>```

-d can be either a dimension or an aspect ratio (w:h). I note that my approach (a 2nd order stretch) seems to stretch the result a bit more than your SmoothMeteor tool.

Body:
What is your platform? If on Unix-like (Linux, Mac OSX, Window 10 Unix or Windows w/Cygwin), then I have a bash shell script calling ImageMagick, called "xpand", that does what you ask.  See my web site at http://www.fmwconcepts.com/imagemagick/index.php

Input:

xpand -d 350 -m horizontal img.png result.png

-d can be either a dimension or an aspect ratio (w:h). I note that my approach (a 2nd order stretch) seems to stretch the result a bit more than your SmoothMeteor tool.


问:
Troubles with Python - Postgresql on Jupyter Notebook | Mac OSX
I'm currently develop a Jupyter notebook with Python code, in Mac OSX Mojave 10.14.
I'm using Psycopg2 to get data from PostgreSQL to Python Dataframe.

The problem is the code works fine in Win 10, in two ways, but I not get data from the same query in Mac OSX.

I don't get any error, I just get an empty Dataframe. Nothing more. No error, no warning.

Anyone have been in the same trouble?

The used code is below:

First option:

```<code>cursor = conn.cursor()
query = """select * from table"""

cursor.execute(query)
data = data.append(cursor.fetchall())
data.columns = [desc[0] for desc in cursor.description]
</code>```

Second option:

```<code>data= pd.DataFrame()

for chunk in pd.read_sql("""select * from table""", con=conn, chunksize=5000):
    data= data.append(chunk)
</code>```

I expect a Dataframe with the data from PostgreSQL.

答: The problem was that I had a '%%time' statement before the query, to get the execute time of the cells. Funny. It seems in Mac OSX doesn't work with a piece of code below.</p>

Body:
I'm currently develop a Jupyter notebook with Python code, in Mac OSX Mojave 10.14.
I'm using Psycopg2 to get data from PostgreSQL to Python Dataframe.

The problem is the code works fine in Win 10, in two ways, but I not get data from the same query in Mac OSX.

I don't get any error, I just get an empty Dataframe. Nothing more. No error, no warning.

Anyone have been in the same trouble?

The used code is below:

First option:

cursor = conn.cursor()
query = """select * from table"""

cursor.execute(query)
data = data.append(cursor.fetchall())
data.columns = [desc[0] for desc in cursor.description]

Second option:

data= pd.DataFrame()

for chunk in pd.read_sql("""select * from table""", con=conn, chunksize=5000):
    data= data.append(chunk)

I expect a Dataframe with the data from PostgreSQL.


问:
Can't figure out the correct way to implement if statement on dataframe with apply lambda
Say I have a simple dataframe (df) with two columns (Name and Value). I want to add a third column (New Value) based on Name.

I have tried:

```<code>df['New Value'] = df[['Name ']].apply((lambda x: df['Value'] * 2 if x == 'John' else df['Value']) , axis=0)
</code>```

By doing this I get the following error:

ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index Name')

What I understand is that x is a Series and I cannot compare to a string, is this correct? If not, what does it mean?

In any case, how do I go around this problem?

答:
You can use where to do this:</p>

```<code>df['New Value'] = (df['Value'] * 2).where(df['Name'] == 'John',  df['Value'])
</code>```

Body:
Say I have a simple dataframe (df) with two columns (Name and Value). I want to add a third column (New Value) based on Name.

I have tried:

df['New Value'] = df[['Name ']].apply((lambda x: df['Value'] * 2 if x == 'John' else df['Value']) , axis=0)

By doing this I get the following error:

ValueError: ('The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().', 'occurred at index Name')

What I understand is that x is a Series and I cannot compare to a string, is this correct? If not, what does it mean?

In any case, how do I go around this problem?

Body:
You can use where to do this:

df['New Value'] = (df['Value'] * 2).where(df['Name'] == 'John',  df['Value'])


问:
`operator delete` with size parameter and without size parameter: which one is chosen when both are available?
When I run this code sample in GCC and Clang

```<code>struct S
{
  int a;

  void *operator new(size_t s)
  {
    std::cout << "new " << s << std::endl;
    return ::operator new(s);
  }

  void operator delete(void *p, size_t s) noexcept
  {
    std::cout << "delete " << s << std::endl;
    ::operator delete(p);
  }

  void operator delete(void *p) noexcept
  {
    std::cout << "delete " << "none" << std::endl;
    ::operator delete(p);
  }
};

int main()
{
  S *p = new S;
  delete p;
}
</code>```

I get the following output from both GCC and Clang

```<code>new 4
delete none
</code>```

which means that the compilers selected the "sizeless" version of operator delete.

However, if I try something similar with globally replaced operator new and operator delete functions

```<code>struct S
{
  int a;
};

void *operator new(size_t s)
{
  std::cout << "new " << s << std::endl;
  return std::malloc(s);
}

void operator delete(void *p, size_t s) noexcept
{
  std::cout << "delete " << s << std::endl;
  std::free(p);
}

void operator delete(void *p) noexcept
{
  std::cout << "delete " << "none" << std::endl;
  std::free(p);
}

int main()
{
  S *p = new S;
  delete p;
}
</code>```

From GCC I get

```<code>new 4
delete 4
</code>```

and from Clang I get

```<code>new 4
delete none
</code>```

I know that "sized" version of in-class operator delete has been present in C++ since C++98, but looking through C++98 I don't seem to be able to find a definitive answer to the question of what version of operator delete should be selected in the first example. Is it even specified?

And what about C++14 and its "sized" version of global operator delete in the second example? Does the language say which version should be selected?

答:
This is CWG issue 255, dating back to the year 2000. To quote its premise:

Paragraph 4 of 15.5 [class.free] speaks of looking up a deallocation
  function. While it is an error if a placement deallocation function
  alone is found by this lookup, there seems to be an assumption that a
  placement deallocation function and a usual deallocation function can
  both be declared in a given class scope without creating an ambiguity.
  The normal mechanism by which ambiguity is avoided when functions of
  the same name are declared in the same scope is overload resolution;
  however, there is no mention of overload resolution in the description
  of the lookup. In fact, there appears to be nothing in the current
  wording that handles this case. That is, the following example appears
  to be ill-formed, according to the current wording:

```<code>struct S {
    void operator delete(void*);
    void operator delete(void*, int);
};
void f(S* p) {
    delete p;    // ill-formed: ambiguous operator delete
}
</code>```

The status of the issue is currently "drafting", and as of writing this answer it appears still unresolved. There is no wording about overload resolution with regard to the deallocation functions.

Clang and GCC seem to be choosing arbitrarily. I'd argue it would have been better to emit some sort of diagnostic about the operator being ambiguous.

Body:
When I run this code sample in GCC and Clang

struct S
{
  int a;

  void *operator new(size_t s)
  {
    std::cout << "new " << s << std::endl;
    return ::operator new(s);
  }

  void operator delete(void *p, size_t s) noexcept
  {
    std::cout << "delete " << s << std::endl;
    ::operator delete(p);
  }

  void operator delete(void *p) noexcept
  {
    std::cout << "delete " << "none" << std::endl;
    ::operator delete(p);
  }
};

int main()
{
  S *p = new S;
  delete p;
}

I get the following output from both GCC and Clang

new 4
delete none

which means that the compilers selected the "sizeless" version of operator delete.

However, if I try something similar with globally replaced operator new and operator delete functions

struct S
{
  int a;
};

void *operator new(size_t s)
{
  std::cout << "new " << s << std::endl;
  return std::malloc(s);
}

void operator delete(void *p, size_t s) noexcept
{
  std::cout << "delete " << s << std::endl;
  std::free(p);
}

void operator delete(void *p) noexcept
{
  std::cout << "delete " << "none" << std::endl;
  std::free(p);
}

int main()
{
  S *p = new S;
  delete p;
}

From GCC I get

new 4
delete 4

and from Clang I get

new 4
delete none

I know that "sized" version of in-class operator delete has been present in C++ since C++98, but looking through C++98 I don't seem to be able to find a definitive answer to the question of what version of operator delete should be selected in the first example. Is it even specified?

And what about C++14 and its "sized" version of global operator delete in the second example? Does the language say which version should be selected?

Body:
This is CWG issue 255, dating back to the year 2000. To quote its premise:

Paragraph 4 of 15.5 [class.free] speaks of looking up a deallocation
  function. While it is an error if a placement deallocation function
  alone is found by this lookup, there seems to be an assumption that a
  placement deallocation function and a usual deallocation function can
  both be declared in a given class scope without creating an ambiguity.
  The normal mechanism by which ambiguity is avoided when functions of
  the same name are declared in the same scope is overload resolution;
  however, there is no mention of overload resolution in the description
  of the lookup. In fact, there appears to be nothing in the current
  wording that handles this case. That is, the following example appears
  to be ill-formed, according to the current wording:

struct S {
    void operator delete(void*);
    void operator delete(void*, int);
};
void f(S* p) {
    delete p;    // ill-formed: ambiguous operator delete
}

The status of the issue is currently "drafting", and as of writing this answer it appears still unresolved. There is no wording about overload resolution with regard to the deallocation functions.

Clang and GCC seem to be choosing arbitrarily. I'd argue it would have been better to emit some sort of diagnostic about the operator being ambiguous.


问:
yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker
I'm trying to update Orion ContextBroker using the command yum install contextBroker. Unfortunatelly I get the following error:

Loaded plugins: fastestmirror, refresh-packagekit, security Loading

mirror speeds from cached hostfile

Error: Cannot retrieve metalink for repository: epel. Please verify
  its path and try again

What could be going wrong ?

答:
None of these worked for me (I didn't even try the hacks like manually editing the repo file).

However it worked after a simple yum update -y

ContentLicense: CC BY-SA 3.0


问:
Comparison between two integers in GLSL
I want to build a fragment shader, and I realized that the comparison between two int in glsl 1.5.0 will return always false. I am using integers as an enumeration in a method parameter. This is the problem in a simple way and this code has the same result.

void main(){
    int x = 5;
    #if(x == 5)
        gl_FragColor = vec4(1.0);
    #else
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    #endif
}
```

<p>I tried this code and the condition <code>x == int(2)</code> will return always true!</p>

<pre class="lang-c prettyprint-override"><code>void main(){
    int x = 5;
    #if(x == int(2))
        gl_FragColor = vec4(1.0);
    #else
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    #endif
}
</code>```

So, what should I do to compare two integers in the right way?

答:
#if, #else and #endif are  preprocessor statements. But int x = 5; is a local variable. The preprocessor processes the source string, it is part of the comoilation process, but it is done before the actual compilation. The variable x has no meaning for the preprocessor.

A x for the preprocessor can be defines a follow:

#define x 5

#if(x == 5)
        gl_FragColor = vec4(1.0);
#else
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
#endif
```

<p>But a glsl <code>if</code> statement start with the keyword <code>if</code> followed by a bool-expression and a statement. Optional followed by the keyword <code>else</code> and another statement:</p>

<pre class="lang-c prettyprint-override"><code>int x = 5;
if (x == 5)
{
    gl_FragColor = vec4(1.0);
}
else
{
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
</code>```

In this case the curly braces can be skipped, because in each case there is only a single statement.

Note, a ternary operator can be used, too:

gl_FragColor = x==5 ? vec4(1.0) : vec4(1.0, 0.0, 0.0, 1.0);
```

This all can be read in the OpenGL Shading Language 1.50 Specification in detail. The preprocessor is explained in chapter "3.3 Preprocessor", the if statement is specified in chapter "6.2 Selection" and and the Ternary operator in chapter "5.8 Assignments"

Title: Comparison between two integers in GLSL

Body:
I want to build a fragment shader, and I realized that the comparison between two int in glsl 1.5.0 will return always false. I am using integers as an enumeration in a method parameter. This is the problem in a simple way and this code has the same result.

void main(){
    int x = 5;
    #if(x == 5)
        gl_FragColor = vec4(1.0);
    #else
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    #endif
}

I tried this code and the condition x == int(2) will return always true!

void main(){
    int x = 5;
    #if(x == int(2))
        gl_FragColor = vec4(1.0);
    #else
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    #endif
}

So, what should I do to compare two integers in the right way?

Body:
#if, #else and #endif are  preprocessor statements. But int x = 5; is a local variable. The preprocessor processes the source string, it is part of the comoilation process, but it is done before the actual compilation. The variable x has no meaning for the preprocessor.

A x for the preprocessor can be defines a follow:

#define x 5

#if(x == 5)
        gl_FragColor = vec4(1.0);
#else
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
#endif

But a glsl if statement start with the keyword if followed by a bool-expression and a statement. Optional followed by the keyword else and another statement:

int x = 5;
if (x == 5)
{
    gl_FragColor = vec4(1.0);
}
else
{
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

In this case the curly braces can be skipped, because in each case there is only a single statement.

Note, a ternary operator can be used, too:

gl_FragColor = x==5 ? vec4(1.0) : vec4(1.0, 0.0, 0.0, 1.0);

This all can be read in the OpenGL Shading Language 1.50 Specification in detail. The preprocessor is explained in chapter "3.3 Preprocessor", the if statement is specified in chapter "6.2 Selection" and and the Ternary operator in chapter "5.8 Assignments"


问:
How do I create a class to help me log my application user activity? (clean coding and code refactoring question)
Currently when a user performs a CRUD action I log it in the database:

```<code>var user = User.Identity.Name;
var log = (from l in db.AppLogs where l.UserName == user select l).ToList();
var logresult = (from lr in log select lr).LastOrDefault();
var loggedUser = (from lu in db.AMProfiles where lu.UserName == logresult.UserName select lu).SingleOrDefault();
var logAppName = "My Application";
var logRequestType = "Create New Movie - " + Movie.Name;

if (ModelState.IsValid)
{
    AMLog userLog = new AMLog
    {
        CreateDate = DateTime.Now,
        UserId = Convert.ToInt32(loggedUser.EmployeeId),
        AppName = logAppName,
        RequestType = logRequestType,
        LogId = logresult.Id
    };
    db.MADMovies.Add(mADMovies);
    db.SaveChanges();
}
</code>```

The problem here is that I know this is not very clean, repetitive and that there should be a better way of doing this.

What I would like to do instead is use a class that gets called when a CRUD action is performed. How is this done?

答:
I typically use a custom ActionFilter to accomplish things like this.

Get some types going or whatever you need:

```<code>public enum AuditEventType
{
    LoggedIn,
    LoggedOut,
    ViewedPage,
    Etc
}
</code>```

Create an action filter class:

```<code>public class AuditEvent : ActionFilterAttribute
{
    AuditEventType Type;

    public AuditEvent(AuditEventType type)
    {
        Type = type;
    }

    public override OnActionExecuted()
    {
         //log user name and audit event to db
    }
}

</code>```

Decorate your controller method you want to log:

```<code>[HttpPost]
[AuditEvent(AuditEventType.LoggedIn)]
public ActionResult Login(LoginModel model)
{
   //do login logic
}
</code>```

Body:
Currently when a user performs a CRUD action I log it in the database:

var user = User.Identity.Name;
var log = (from l in db.AppLogs where l.UserName == user select l).ToList();
var logresult = (from lr in log select lr).LastOrDefault();
var loggedUser = (from lu in db.AMProfiles where lu.UserName == logresult.UserName select lu).SingleOrDefault();
var logAppName = "My Application";
var logRequestType = "Create New Movie - " + Movie.Name;

if (ModelState.IsValid)
{
    AMLog userLog = new AMLog
    {
        CreateDate = DateTime.Now,
        UserId = Convert.ToInt32(loggedUser.EmployeeId),
        AppName = logAppName,
        RequestType = logRequestType,
        LogId = logresult.Id
    };
    db.MADMovies.Add(mADMovies);
    db.SaveChanges();
}

The problem here is that I know this is not very clean, repetitive and that there should be a better way of doing this.

What I would like to do instead is use a class that gets called when a CRUD action is performed. How is this done?

Body:
I typically use a custom ActionFilter to accomplish things like this.

Get some types going or whatever you need:

public enum AuditEventType
{
    LoggedIn,
    LoggedOut,
    ViewedPage,
    Etc
}

Create an action filter class:

public class AuditEvent : ActionFilterAttribute
{
    AuditEventType Type;

    public AuditEvent(AuditEventType type)
    {
        Type = type;
    }

    public override OnActionExecuted()
    {
         //log user name and audit event to db
    }
}

Decorate your controller method you want to log:

[HttpPost]
[AuditEvent(AuditEventType.LoggedIn)]
public ActionResult Login(LoginModel model)
{
   //do login logic
}


问:
How to use a foreach loop correctly with $_COOKIE with PHP?
If have 2 errors:

Invalid argument supplied for foreach()...

Use of undefined constant c - assumed 'c' in...

I first am trying to find if the cookie exists.  Then if a duplicate cookie exists in  the array.

I was looking at other examples on here, but they seems to show the same foreach loops.  Is there something I am missing?

```<code>$seo = "perma-link"
$count = 0;
$duplicate = 0;
if (isset($_COOKIE['c'])) {
    foreach($_COOKIE['c'] as $key => $value) {
        if($value === $seo){
            $duplicate = 1;
        }
    }
} else {
    setcookie(c[$count], $seo, time()+3600);
    $duplicate = 1;
}
if($duplicate == 0){
    $count = count($_COOKIE['c']);
    setcookie(c[$count], $seo, time()+3600);
}
</code>```

答:
I did one too many foreach loops and "c[$count]" has to have quotation marks to work.  Fixed it.  I appreciate the feedback James Bond.</p>

```<code>    $seo = "perma-link"
    $count = 0;
    $duplicate = 0;
    if (isset($_COOKIE['c'])) {
        foreach($_COOKIE as $k => $v) {
                if($k == "c" && $v == $seo){
                    $duplicate = 1;
                }
         }
    }else{
        setcookie("c[$count]", $seo, time()+3600);
        $duplicate = 1;
    }
    if($duplicate ==0){
        $count = count($_COOKIE['c']);
        setcookie("c[$count]", $seo, time()+3600);
    }
</code>```

Body:
If have 2 errors:

Invalid argument supplied for foreach()...

Use of undefined constant c - assumed 'c' in...

I first am trying to find if the cookie exists.  Then if a duplicate cookie exists in  the array.

I was looking at other examples on here, but they seems to show the same foreach loops.  Is there something I am missing?

$seo = "perma-link"
$count = 0;
$duplicate = 0;
if (isset($_COOKIE['c'])) {
    foreach($_COOKIE['c'] as $key => $value) {
        if($value === $seo){
            $duplicate = 1;
        }
    }
} else {
    setcookie(c[$count], $seo, time()+3600);
    $duplicate = 1;
}
if($duplicate == 0){
    $count = count($_COOKIE['c']);
    setcookie(c[$count], $seo, time()+3600);
}

Body:
I did one too many foreach loops and "c[$count]" has to have quotation marks to work.  Fixed it.  I appreciate the feedback James Bond.

    $seo = "perma-link"
    $count = 0;
    $duplicate = 0;
    if (isset($_COOKIE['c'])) {
        foreach($_COOKIE as $k => $v) {
                if($k == "c" && $v == $seo){
                    $duplicate = 1;
                }
         }
    }else{
        setcookie("c[$count]", $seo, time()+3600);
        $duplicate = 1;
    }
    if($duplicate ==0){
        $count = count($_COOKIE['c']);
        setcookie("c[$count]", $seo, time()+3600);
    }


问:
Potentially faulty or weird behavior for pandas.series.isin
I have 2 tables in my database (visits, events).

visits has a primary key visit_id,
events_and_pages has a column visit_id which is sort of a foreign key of visits. (An events row can belong to 0 to 1 visit)

What I want to do: Filter-out from events table all the visit_id that don't belong to visits table. Simple task.

I have the data for each of those tables stored in pandas.DataFrame, respectively df_visits and df_events

I do the following operation :

len(set(df_visits.visit_id) - set(df_events.visit_id)) I get a result of 1670, which is compliant with what I should expect.

But when I do

```<code>filter_real_v = df_events.visit_id.isin(set(visits.visit_id))
filter_real_v.value_counts() # I get only True values

filter_real_v = df_events.visit_id.isin(visits.visit_id)
filter_real_v.value_counts() # I get only True values
</code>```

Even weirder, when I use

```<code>pd.DataFrame(df_events.visit_id).isin(real_visits)).visit_id.value_counts() #I get all False values except 8 that are True

pd.DataFrame(df_events.visit_id).isin(set(real_visits)).visit_id.value_counts() #I get all True values
</code>```

What is going on here? And how can I define a filter for which visit_id exists in events but not in visits?

Please find in this link, the df_events and df_visits csv files to reproduce this error (comma separated index,visit_id)

EDIT : Add snippet for minimal reproducible code:

Download the files in the link and put them in a file_path_events & file_path_visits of your chosing

Execute the code bellow:

```<code>import pandas as pd
events = pd.read_csv("df_events.csv")
events.set_index('index',inplace=True)
visits = pd.read_csv("df_visits.csv")
visits.set_index('index',inplace=True)
correct_delta = len(set(visits.visit_id) - set(events.visit_id))
print(correct_delta) #1670
filter_real_v = events.visit_id.isin(set(visits.visit_id))
bad_delta = filter_real_v.value_counts()
print(bad_delta[True]) #702680

</code>```

Best regards

答:
Everything is behaving correctly, your just misinterpreting the set operation "-"

len(set(df_visits.visit_id) - set(df_events.visit_id))

Will return the values of df_visits.visit_id not in df_events.visit_id. Note: If values of df_events.visit_id are not in df_visits.visit_id they will not be represented here. This is how sets work.

For example:

```<code>set([1,2,3,9]) - set([9,10,11])

Output:
{1, 2, 3}
</code>```

Notice how 10 or 11 do not show up in the answer. None of the second set will as a matter of fact. Only the values in the second set will be taken away from the first set.

With isin() you are effectively doing:

```<code>visits['visit_id'].isin(df_events['visit_id'].values).value_counts()

True     56071
False     1670

# Note 1670 is the exact same you got in your set operation
</code>```

and not:

```<code>df_events['visit_id'].isin(visits['visit_id'].values).value_counts()

True    702680
</code>```

Body:
I have 2 tables in my database (visits, events).

visits has a primary key visit_id,
events_and_pages has a column visit_id which is sort of a foreign key of visits. (An events row can belong to 0 to 1 visit)

What I want to do: Filter-out from events table all the visit_id that don't belong to visits table. Simple task.

I have the data for each of those tables stored in pandas.DataFrame, respectively df_visits and df_events

I do the following operation :

len(set(df_visits.visit_id) - set(df_events.visit_id)) I get a result of 1670, which is compliant with what I should expect.

But when I do

filter_real_v = df_events.visit_id.isin(set(visits.visit_id))
filter_real_v.value_counts() # I get only True values

filter_real_v = df_events.visit_id.isin(visits.visit_id)
filter_real_v.value_counts() # I get only True values

Even weirder, when I use

pd.DataFrame(df_events.visit_id).isin(real_visits)).visit_id.value_counts() #I get all False values except 8 that are True

pd.DataFrame(df_events.visit_id).isin(set(real_visits)).visit_id.value_counts() #I get all True values

What is going on here? And how can I define a filter for which visit_id exists in events but not in visits?

Please find in this link, the df_events and df_visits csv files to reproduce this error (comma separated index,visit_id)

EDIT : Add snippet for minimal reproducible code:

Download the files in the link and put them in a file_path_events & file_path_visits of your chosing

Execute the code bellow:

import pandas as pd
events = pd.read_csv("df_events.csv")
events.set_index('index',inplace=True)
visits = pd.read_csv("df_visits.csv")
visits.set_index('index',inplace=True)
correct_delta = len(set(visits.visit_id) - set(events.visit_id))
print(correct_delta) #1670
filter_real_v = events.visit_id.isin(set(visits.visit_id))
bad_delta = filter_real_v.value_counts()
print(bad_delta[True]) #702680

Best regards

Body:
Everything is behaving correctly, your just misinterpreting the set operation "-"

len(set(df_visits.visit_id) - set(df_events.visit_id))

Will return the values of df_visits.visit_id not in df_events.visit_id. Note: If values of df_events.visit_id are not in df_visits.visit_id they will not be represented here. This is how sets work.

For example:

set([1,2,3,9]) - set([9,10,11])

Output:
{1, 2, 3}

Notice how 10 or 11 do not show up in the answer. None of the second set will as a matter of fact. Only the values in the second set will be taken away from the first set.

With isin() you are effectively doing:

visits['visit_id'].isin(df_events['visit_id'].values).value_counts()

True     56071
False     1670

# Note 1670 is the exact same you got in your set operation

and not:

df_events['visit_id'].isin(visits['visit_id'].values).value_counts()

True    702680


问:
Creating an array of structs by adding dynamically some struct-elements
I've been struggling with C pointers for hours now. I'm trying to create a C program which manages flights. A flight contains the following:

```<code>flight-number, from, to, date, price

OS772,Vienna,New York,15.12.2018,638.00
</code>```

Therefore, I'm reading a textfile of this given structure. On every line read, I need to create another struct and add it to my array or "list" of structs.

The struct looks like:

```<code>typedef struct flights {
    char *flnum;
    char *from;
    char *to;
    char *date;
    float price;
    struct person *fPerson;
}flights;
</code>```

My problem: Inside the function, the array of structs is created properly. But back in the main-function, the pointer to the array called 'flights **flight_list' is still NULL.

Here is the code (only the necessary parts):

```<code>int main(void) {

    flights **flight_list = NULL;
    int numFlights = 0;

    if (!(numFlights = load_flights(flight_list)))
        return EXIT_FAILURE;

    /* value of flight_list = 0x0000 -> unchanged! */
    /* ... */
</code>```

Function short load_flights(flights **flight_list):

```<code>short load_flights(flights **flight_list) {

    FILE *fp = NULL;
    char file_buffer[256] = {};
    int i = 0;

    if (fp = fopen("flights.txt", "r")) {

        /* create array of structs */
        flight_list = (flights **)calloc(1, sizeof(int));

        while (!feof(fp)) {

            /* read current line of flight from textfile */
            fgets(file_buffer, sizeof(file_buffer), fp);

            /* create a new struct and add it to the array */
            if ((flight_list[i] = (flights *)calloc(1, sizeof(flights))) != NULL) {

                /* create every variable of the struct */
                flight_list[i]->flnum = (char *)calloc(1, strlen(ptr)+1);

                /* ... */

            }

            i++;
        }
    }
    else return 0;

    /* values of the struct-array are properly set; look in attached picture */

    return i;
}
</code>```

This image was taken while debugging the array-creation process before return i;:

And here outside the function; inside main:

So, why is my array of structs gone in the main-function?

答:
You need to pass the address of a pointer variable to load_flights. Then load_flights needs to indirect through the variable to modify the caller's variable.

To handle the dynamic size of the input, you need to use realloc() each time through the loop to grow the array.

```<code>int main(void) {

    flights **flight_list = NULL;
    int numFlights = 0;

    if (!(numFlights = load_flights(&flight_list)))
        return EXIT_FAILURE;

    /* ... */
}

short load_flights(flights ***flight_list) {

    FILE *fp = NULL;
    char file_buffer[256] = {};
    int i = 0;

    if (fp = fopen("flights.txt", "r")) {

        /* create array of structs */
        flight_list **temp_flight_list = NULL;

        /* read current line of flight from textfile */
        while (fgets(file_buffer, sizeof(file_buffer), fp)) {
            // Grow the flight list array
            flights **new_flight_list = realloc(*flight_list, (i+1) * sizeof(flight_list *));
            if (new_flight_list == NULL) { // allocation failed, throw everything away
                for (int j = 0; j < i-1; j++) {
                    free(temp_flight_list[i]->flnum);
                    free(temp_flight_list[i]->from);
                    /* ... */
                    free(temp_flight_list[i]);
                }
                free(temp_flight_list);
                return 0;
            }
            temp_flight_list = new_flight_list;
            /* create a new struct and add it to the array */
            if ((temp_flight_list[i] = calloc(1, sizeof(flights))) != NULL) {
                // Parse the buffer ...
                /* create every variable of the struct */
                temp_flight_list[i]->flnum = calloc(1, strlen(ptr)+1);

                /* ... */

            } else { // allocation failed, throw everything away
                for (int j = 0; j < i-1; j++) {
                    free(temp_flight_list[i]->flnum);
                    free(temp_flight_list[i]->from);
                    /* ... */
                    free(temp_flight_list[i]);
                }
                free(temp_flight_list);
                return 0;
            }
            i++;
        }
        // Store new flight list in caller's variable
        *flight_list = temp_flight_list;
        return i;
    }
    else return 0;

}
</code>```

See also

Do I cast the result of malloc?

and

Why is “while (!feof(file))” always wrong?

Body:
I've been struggling with C pointers for hours now. I'm trying to create a C program which manages flights. A flight contains the following:

flight-number, from, to, date, price

OS772,Vienna,New York,15.12.2018,638.00

Therefore, I'm reading a textfile of this given structure. On every line read, I need to create another struct and add it to my array or "list" of structs.

The struct looks like:

typedef struct flights {
    char *flnum;
    char *from;
    char *to;
    char *date;
    float price;
    struct person *fPerson;
}flights;

My problem: Inside the function, the array of structs is created properly. But back in the main-function, the pointer to the array called 'flights **flight_list' is still NULL.

Here is the code (only the necessary parts):

int main(void) {

    flights **flight_list = NULL;
    int numFlights = 0;

    if (!(numFlights = load_flights(flight_list)))
        return EXIT_FAILURE;

    /* value of flight_list = 0x0000 -> unchanged! */
    /* ... */

Function short load_flights(flights **flight_list):

short load_flights(flights **flight_list) {

    FILE *fp = NULL;
    char file_buffer[256] = {};
    int i = 0;

    if (fp = fopen("flights.txt", "r")) {

        /* create array of structs */
        flight_list = (flights **)calloc(1, sizeof(int));

        while (!feof(fp)) {

            /* read current line of flight from textfile */
            fgets(file_buffer, sizeof(file_buffer), fp);

            /* create a new struct and add it to the array */
            if ((flight_list[i] = (flights *)calloc(1, sizeof(flights))) != NULL) {

                /* create every variable of the struct */
                flight_list[i]->flnum = (char *)calloc(1, strlen(ptr)+1);

                /* ... */

            }

            i++;
        }
    }
    else return 0;

    /* values of the struct-array are properly set; look in attached picture */

    return i;
}

This image was taken while debugging the array-creation process before return i;:

And here outside the function; inside main:

So, why is my array of structs gone in the main-function?

Body:
You need to pass the address of a pointer variable to load_flights. Then load_flights needs to indirect through the variable to modify the caller's variable.

To handle the dynamic size of the input, you need to use realloc() each time through the loop to grow the array.

int main(void) {

    flights **flight_list = NULL;
    int numFlights = 0;

    if (!(numFlights = load_flights(&flight_list)))
        return EXIT_FAILURE;

    /* ... */
}

short load_flights(flights ***flight_list) {

    FILE *fp = NULL;
    char file_buffer[256] = {};
    int i = 0;

    if (fp = fopen("flights.txt", "r")) {

        /* create array of structs */
        flight_list **temp_flight_list = NULL;

        /* read current line of flight from textfile */
        while (fgets(file_buffer, sizeof(file_buffer), fp)) {
            // Grow the flight list array
            flights **new_flight_list = realloc(*flight_list, (i+1) * sizeof(flight_list *));
            if (new_flight_list == NULL) { // allocation failed, throw everything away
                for (int j = 0; j < i-1; j++) {
                    free(temp_flight_list[i]->flnum);
                    free(temp_flight_list[i]->from);
                    /* ... */
                    free(temp_flight_list[i]);
                }
                free(temp_flight_list);
                return 0;
            }
            temp_flight_list = new_flight_list;
            /* create a new struct and add it to the array */
            if ((temp_flight_list[i] = calloc(1, sizeof(flights))) != NULL) {
                // Parse the buffer ...
                /* create every variable of the struct */
                temp_flight_list[i]->flnum = calloc(1, strlen(ptr)+1);

                /* ... */

            } else { // allocation failed, throw everything away
                for (int j = 0; j < i-1; j++) {
                    free(temp_flight_list[i]->flnum);
                    free(temp_flight_list[i]->from);
                    /* ... */
                    free(temp_flight_list[i]);
                }
                free(temp_flight_list);
                return 0;
            }
            i++;
        }
        // Store new flight list in caller's variable
        *flight_list = temp_flight_list;
        return i;
    }
    else return 0;

}

See also

Do I cast the result of malloc?

and

Why is “while (!feof(file))” always wrong?


问:
Regular expression misses match at beginning of string
I have strings of as and bs. I want to extract all overlapping subsequences, where a subsequence is a single a surrounding by any number of bs. This is the regex I wrote:

```<code>import re

pattern = """(?=            # inside lookahead for overlapping results
             (?:a|^)        # match at beginning of str or after a
             (b* (?:a) b*)  # one a between any number of bs
             (?:a|$))       # at end of str or before next a
          """
a_between_bs = re.compile(pattern, re.VERBOSE)
</code>```

It seems to work as expected, except when the very first character in the string is an a, in which case this subsequence is missed:

```<code>a_between_bs.findall("bbabbba")
# ['bbabbb', 'bbba']
a_between_bs.findall("abbabb")
# ['bbabb']
</code>```

I don't understand what is happening. If I change the order of how a potential match could start, the results also change:

```<code>pattern = """(?=
             (?:^|a)        # a and ^ swapped
             (b* (?:a) b*)
             (?:a|$))
          """
a_between_bs = re.compile(pattern, re.VERBOSE)

a_between_bs.findall("abbabb")
# ['abb']
</code>```

I would have expected this to be symmetric, so that strings ending in an a might also be missed, but this doesn't appear to be the case. What is going on?

Edit:

I assumed that solutions to the toy example above would translate to my full problem, but that doesn't seem to be the case, so I'm elaborating now (sorry about that). I am trying to extract "syllables" from transcribed words. A "syllable" is a vowel or a diphtongue, preceded and followed by any number of consonants. This is my regular expression to extract them:

```<code>vowels = 'æɑəɛiɪɔuʊʌ'
diphtongues = "|".join(('aj', 'aw', 'ej', 'oj', 'ow'))
consonants = 'θwlmvhpɡŋszbkʃɹdnʒjtðf'

pattern = f"""(?=
          (?:[{vowels}]|^|{diphtongues})
          ([{consonants}]* (?:[{vowels}]|{diphtongues}) [{consonants}]*)
          (?:[{vowels}]|$|{diphtongues})
          )
          """
syllables = re.compile(pattern, re.VERBOSE)
</code>```

The tricky bit is that the diphtongues end in consonants (j or w), which I don't want to be included in the next syllable. So replacing the first non-capturing group by a double negative (?<![{consonants}]) doesn't work. I tried to instead replace that group by a positive lookahead (?<=[{vowels}]|^|{diphtongues}), but regex won't accept different lengths (even removing the diphtongues doesn't work, apparently ^ is of a different length).

So this is the problematic case with the pattern above:

```<code>syllables.findall('æbə')
# ['bə']
# should be: ['æb', 'bə']
</code>```

Edit 2:
I've switched to using regex, which allows variable-width lookbehinds, which solves the problem. To my surprise, it even appears to be faster than the re module in the standard library. I'd still like to know how to get this working with the re module, though. (:

答: Remember that python "short-circuits", so, if it matches "^", its not going to continue looking to see if it matches "a" too. This will "consume" the matching character, so in cases where it matches "a", "a" is consumed and not available for the next group to match, and because using the (?:) syntax is non-capturing, that "a" is "lost", and not available to be captured by the next grouping (b*(?:a)b*), whereas when "^" is consumed by the first grouping, that first "a" would match in the second grouping.</p>

Body:
I have strings of as and bs. I want to extract all overlapping subsequences, where a subsequence is a single a surrounding by any number of bs. This is the regex I wrote:

import re

pattern = """(?=            # inside lookahead for overlapping results
             (?:a|^)        # match at beginning of str or after a
             (b* (?:a) b*)  # one a between any number of bs
             (?:a|$))       # at end of str or before next a
          """
a_between_bs = re.compile(pattern, re.VERBOSE)

It seems to work as expected, except when the very first character in the string is an a, in which case this subsequence is missed:

a_between_bs.findall("bbabbba")
# ['bbabbb', 'bbba']
a_between_bs.findall("abbabb")
# ['bbabb']

I don't understand what is happening. If I change the order of how a potential match could start, the results also change:

pattern = """(?=
             (?:^|a)        # a and ^ swapped
             (b* (?:a) b*)
             (?:a|$))
          """
a_between_bs = re.compile(pattern, re.VERBOSE)

a_between_bs.findall("abbabb")
# ['abb']

I would have expected this to be symmetric, so that strings ending in an a might also be missed, but this doesn't appear to be the case. What is going on?

Edit:

I assumed that solutions to the toy example above would translate to my full problem, but that doesn't seem to be the case, so I'm elaborating now (sorry about that). I am trying to extract "syllables" from transcribed words. A "syllable" is a vowel or a diphtongue, preceded and followed by any number of consonants. This is my regular expression to extract them:

vowels = 'æɑəɛiɪɔuʊʌ'
diphtongues = "|".join(('aj', 'aw', 'ej', 'oj', 'ow'))
consonants = 'θwlmvhpɡŋszbkʃɹdnʒjtðf'

pattern = f"""(?=
          (?:[{vowels}]|^|{diphtongues})
          ([{consonants}]* (?:[{vowels}]|{diphtongues}) [{consonants}]*)
          (?:[{vowels}]|$|{diphtongues})
          )
          """
syllables = re.compile(pattern, re.VERBOSE)

The tricky bit is that the diphtongues end in consonants (j or w), which I don't want to be included in the next syllable. So replacing the first non-capturing group by a double negative (?<![{consonants}]) doesn't work. I tried to instead replace that group by a positive lookahead (?<=[{vowels}]|^|{diphtongues}), but regex won't accept different lengths (even removing the diphtongues doesn't work, apparently ^ is of a different length).

So this is the problematic case with the pattern above:

syllables.findall('æbə')
# ['bə']
# should be: ['æb', 'bə']

Edit 2:
I've switched to using regex, which allows variable-width lookbehinds, which solves the problem. To my surprise, it even appears to be faster than the re module in the standard library. I'd still like to know how to get this working with the re module, though. (:


问:
How to compare two arrays by multiple columns (row with row)
I have two tables in one spreadsheet. both have the same columns - Name, City, Province. My goal is to compare both and if three out of three values in a row match, then pull "Yes", if not, pull "No". I compare rows with rows in these two tables (not random cells).

I have not found a proper formula, so probably need to code it.

I have found a good code, but it works only for looking at the same values in one array. I hope it could be adapted to my problem. Or maybe I need another one.

```<code>Sub Compare()
    Dim row As Integer
    row = 2
    Dim firstColumn As String
    firstColumn = "H"
    Dim lastColumn As String
    lastColumn = "J"
    Dim resultsColumn As String
    resultsColumn = "M"
    Dim isFoundText As String
    isFoundText = "YES"
    Dim isNotFoundText As String
    isNotFoundText = "NO"

    Do While Range("B" & row).Value <> ""

        Dim startChar As Integer
        startChar = Asc(firstColumn)
        Dim endChar As Integer
        endChar = Asc(lastColumn)
        Dim i As Integer
        Dim hasMatch As Boolean
        hasMatch = False

        For i = startChar To endChar
            If Range(Chr(i) & row).Value = Range(Chr(i + 1) & row).Value Then
                hasMatch = True
            End If
            If Range(Chr(startChar) & row).Value = Range(Chr(i + 1) & row).Value Then
                hasMatch = True
            End If
        Next i

        If (hasMatch) Then
            Range(resultsColumn & row).Value = isFoundText
        Else
            Range(resultsColumn & row).Value = isNotFoundText
        End If
        row = row + 1
    Loop

End Sub
</code>```

答:
For this type of task it's better to move that data to Variant Arrays and do the looping over those (much faster). Also, the the pattern matching can be generalised away from the data, making for a more reusable solution and seperation of concerns

The Compare Function

```<code>Private Function CompareColumns(Table1 As Range, Table2 As Range, ColPairs() As Variant, Optional IsMatch As Variant = True, Optional NoMatch As Variant = False) As Variant
    Dim Table1Data As Variant
    Dim Table2Data As Variant
    Dim OutputData As Variant
    Dim rw1 As Long, rw2 As Long
    Dim Col As Long
    Dim FoundMatch As Boolean

    ' Move data to variant arrays
    Table1Data = Table1.Value2
    Table2Data = Table2.Value2

    ' Size return array
    ReDim OutputData(1 To UBound(Table1Data, 1), 1 To 1)

    ' Loop the arrays
    For rw2 = 1 To UBound(Table2Data, 1)
        OutputData(rw2, 1) = NoMatch ' initialise
        For rw1 = 1 To UBound(Table1Data, 1)
            FoundMatch = True
            For Col = LBound(ColPairs, 1) To UBound(ColPairs)
                If Table1Data(rw1, ColPairs(Col, 1)) <> Table2Data(rw2, ColPairs(Col, 2)) Then
                    FoundMatch = False ' column not a match, move to next row
                    Exit For
                End If
            Next
            If FoundMatch Then ' found a match
                OutputData(rw2, 1) = IsMatch
                Exit For ' exit Table2 loop when match found
            End If
        Next
    Next
    ' Return result to caller
    CompareColumns = OutputData
End Function
</code>```

Use it like this

```<code>Sub Compare()
    Dim ws As Worksheet
    Dim Table1 As Range
    Dim Table2 As Range
    Dim Output As Range
    Dim OutputTable As Variant
    Dim ColPairs() As Variant

    Set ws = ActiveSheet ' update to suit your needs

    ' Set up ranges by any means you choose
    With ws
        Set Table1 = .Range(.Cells(2, 1), .Cells(.Rows.Count, 3).End(xlUp))
        Set Table2 = .Range(.Cells(2, 10), .Cells(.Rows.Count, 8).End(xlUp))
        Set Output = .Cells(2, 13).Resize(Table2.Rows.Count, 1)
    End With

    'Specify columns to compare
    ReDim ColPairs(1 To 3, 1 To 2)
    ColPairs(1, 1) = 1: ColPairs(1, 2) = 3
    ColPairs(2, 1) = 2: ColPairs(2, 2) = 2
    ColPairs(3, 1) = 3: ColPairs(3, 2) = 1

    ' Call Match function
    OutputTable = CompareColumns(Table1, Table2, ColPairs, "Yes", "No")

    ' Place Output on sheet
    Output = OutputTable
End Sub
</code>```

Body:
I have two tables in one spreadsheet. both have the same columns - Name, City, Province. My goal is to compare both and if three out of three values in a row match, then pull "Yes", if not, pull "No". I compare rows with rows in these two tables (not random cells).

I have not found a proper formula, so probably need to code it.

I have found a good code, but it works only for looking at the same values in one array. I hope it could be adapted to my problem. Or maybe I need another one.

Sub Compare()
    Dim row As Integer
    row = 2
    Dim firstColumn As String
    firstColumn = "H"
    Dim lastColumn As String
    lastColumn = "J"
    Dim resultsColumn As String
    resultsColumn = "M"
    Dim isFoundText As String
    isFoundText = "YES"
    Dim isNotFoundText As String
    isNotFoundText = "NO"

    Do While Range("B" & row).Value <> ""

        Dim startChar As Integer
        startChar = Asc(firstColumn)
        Dim endChar As Integer
        endChar = Asc(lastColumn)
        Dim i As Integer
        Dim hasMatch As Boolean
        hasMatch = False

        For i = startChar To endChar
            If Range(Chr(i) & row).Value = Range(Chr(i + 1) & row).Value Then
                hasMatch = True
            End If
            If Range(Chr(startChar) & row).Value = Range(Chr(i + 1) & row).Value Then
                hasMatch = True
            End If
        Next i

        If (hasMatch) Then
            Range(resultsColumn & row).Value = isFoundText
        Else
            Range(resultsColumn & row).Value = isNotFoundText
        End If
        row = row + 1
    Loop

End Sub

Body:
For this type of task it's better to move that data to Variant Arrays and do the looping over those (much faster). Also, the the pattern matching can be generalised away from the data, making for a more reusable solution and seperation of concerns

The Compare Function

Private Function CompareColumns(Table1 As Range, Table2 As Range, ColPairs() As Variant, Optional IsMatch As Variant = True, Optional NoMatch As Variant = False) As Variant
    Dim Table1Data As Variant
    Dim Table2Data As Variant
    Dim OutputData As Variant
    Dim rw1 As Long, rw2 As Long
    Dim Col As Long
    Dim FoundMatch As Boolean

    ' Move data to variant arrays
    Table1Data = Table1.Value2
    Table2Data = Table2.Value2

    ' Size return array
    ReDim OutputData(1 To UBound(Table1Data, 1), 1 To 1)

    ' Loop the arrays
    For rw2 = 1 To UBound(Table2Data, 1)
        OutputData(rw2, 1) = NoMatch ' initialise
        For rw1 = 1 To UBound(Table1Data, 1)
            FoundMatch = True
            For Col = LBound(ColPairs, 1) To UBound(ColPairs)
                If Table1Data(rw1, ColPairs(Col, 1)) <> Table2Data(rw2, ColPairs(Col, 2)) Then
                    FoundMatch = False ' column not a match, move to next row
                    Exit For
                End If
            Next
            If FoundMatch Then ' found a match
                OutputData(rw2, 1) = IsMatch
                Exit For ' exit Table2 loop when match found
            End If
        Next
    Next
    ' Return result to caller
    CompareColumns = OutputData
End Function

Use it like this

Sub Compare()
    Dim ws As Worksheet
    Dim Table1 As Range
    Dim Table2 As Range
    Dim Output As Range
    Dim OutputTable As Variant
    Dim ColPairs() As Variant

    Set ws = ActiveSheet ' update to suit your needs

    ' Set up ranges by any means you choose
    With ws
        Set Table1 = .Range(.Cells(2, 1), .Cells(.Rows.Count, 3).End(xlUp))
        Set Table2 = .Range(.Cells(2, 10), .Cells(.Rows.Count, 8).End(xlUp))
        Set Output = .Cells(2, 13).Resize(Table2.Rows.Count, 1)
    End With

    'Specify columns to compare
    ReDim ColPairs(1 To 3, 1 To 2)
    ColPairs(1, 1) = 1: ColPairs(1, 2) = 3
    ColPairs(2, 1) = 2: ColPairs(2, 2) = 2
    ColPairs(3, 1) = 3: ColPairs(3, 2) = 1

    ' Call Match function
    OutputTable = CompareColumns(Table1, Table2, ColPairs, "Yes", "No")

    ' Place Output on sheet
    Output = OutputTable
End Sub


问:
Is toString() only useful for debugging?
Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.

EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

答:
No, the key is that you're supposed to override the default implementation of ToString() to make it useful. ToString() can be a great way to output the value of something back to the UI.

A simple example would be if you have a Name class with a three strings (First, Middle, Last). You can have a ToString() method that formats it for the UI: "Last, First Middle" for example.

Or a class that stores a mathematical operation (values Left=2, Right=3, Result=6 and an operator enum=Multiply). Call ToString() to get "2 * 3 = 6".

However, it is probably more common to have a variety of different To<qualifier>String() methods, like the .NET DateTime class. (ToShortDateString(), ToLongDateString(), ToLongTimeString(), ...)

Edit: As for why it's rooted at the Object class, it's simply because ToString() is a valid operation for anything.

Additionally, strings can be a good way of marshaling between data types or data consumers, because it's (practically) guaranteed to be parsable and doesn't require extra encoding or care.

OwnerDisplayName: Camilo Díaz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Camilo Díaz

OwnerDisplayName: lc

LastEditorDisplayName: lc


问:
Question concerning File Handling
i got the following problem :
i am trying to create a file with the following Code :

```<code>NSString *homeDirectory = NSHomeDirectory();
NSString *documentDirectory = [homeDirectory stringByAppendingPathComponent:@"Documents"];
NSString *filePath = [documentDirectory stringByAppendingPathComponent:@"Test.txt"];

NSFileHandle *savedFile = nil;
savedFile = [[NSFileHandle FileHandleForWritingAtPath:filePath]retain];

NSString *data = @"testmessage";
[savedFile writeData:[string dataUsingEncoding:NSUTF8StringEncoding]];
[savedFile synchronizeFile];
[savedFile closeFile];
</code>```

My Question is  the following. Running this on a MAC does not give me any Errors whatsoever. But the File itself seems to be nonexistant or at least not locateable.
I need to find and access the File and i have to be able to export it to my Mac using a mobile iOS Device

thanks in advance :)

h4wkeye

答:
You need to check that savedFile is not nil (see the docs here).</p>

```<code>NSString *homeDirectory = NSHomeDirectory();
NSString *documentDirectory = [homeDirectory stringByAppendingPathComponent:@"Documents"];
NSString *filePath = [documentDirectory stringByAppendingPathComponent:@"Test.txt"];

NSFileHandle *savedFile = nil;
savedFile = [[NSFileHandle fileHandleForWritingAtPath:filePath]retain];

if (nil == savedFile) {
    NSLog(@"Could not create saved file at %@", filePath);
}

NSString *data = @"testmessage";
[savedFile writeData:[string dataUsingEncoding:NSUTF8StringEncoding]];
[savedFile synchronizeFile];
[savedFile closeFile];
</code>```

Title: Question concerning File Handling

Body:
i got the following problem :
i am trying to create a file with the following Code :

NSString *homeDirectory = NSHomeDirectory();
NSString *documentDirectory = [homeDirectory stringByAppendingPathComponent:@"Documents"];
NSString *filePath = [documentDirectory stringByAppendingPathComponent:@"Test.txt"];

NSFileHandle *savedFile = nil;
savedFile = [[NSFileHandle FileHandleForWritingAtPath:filePath]retain];

NSString *data = @"testmessage";
[savedFile writeData:[string dataUsingEncoding:NSUTF8StringEncoding]];
[savedFile synchronizeFile];
[savedFile closeFile];

My Question is  the following. Running this on a MAC does not give me any Errors whatsoever. But the File itself seems to be nonexistant or at least not locateable.
I need to find and access the File and i have to be able to export it to my Mac using a mobile iOS Device

thanks in advance :)

h4wkeye

Body:
You need to check that savedFile is not nil (see the docs here).

NSString *homeDirectory = NSHomeDirectory();
NSString *documentDirectory = [homeDirectory stringByAppendingPathComponent:@"Documents"];
NSString *filePath = [documentDirectory stringByAppendingPathComponent:@"Test.txt"];

NSFileHandle *savedFile = nil;
savedFile = [[NSFileHandle fileHandleForWritingAtPath:filePath]retain];

if (nil == savedFile) {
    NSLog(@"Could not create saved file at %@", filePath);
}

NSString *data = @"testmessage";
[savedFile writeData:[string dataUsingEncoding:NSUTF8StringEncoding]];
[savedFile synchronizeFile];
[savedFile closeFile];


问:
Deducing the template parameter of a templated class argument: const issue
I think the problem is fairly common, so there should be a known solution. I came up with one, but I'm not really satisfied, so I'm asking here, hoping someone can help.

Say I have a function, whose signature is

```<code>template<typename T>
void foo(const MyArray<const T>& x);
</code>```

The const in the template parameter is to prevent me from changin the array content, since (for reasons beyond this question), the accessors ([] and ()) of MyArray<T> are always marked const, and return references to T (hence, the const ensure safety, since MyArray<T>::operator[] returns T&, while MyArray<const T>::operator[] returns const T&).

Great. However, templates with different template arguments are non related, so I can't bind a reference to MyClass<T> to a reference of MyClass<const T>, meaning I can't do this

```<code>MyArray<double> ar(/*blah*/);
foo(ar);
</code>```

Notice that, without a reference, the code above would work provided that there is a copy constructor that lets me create MyArray<const T> from MyArray<T>. However, I don't want to remove the reference, since the array construction would happen a lot of times, and, despite relatively cheap, its cost would add up.

So the question: how can I call foo with an MyArray<T>?

My only solution so far is the following:

```<code>MyArray<T> ar(/*blah*/);
foo(reinterpret_cast<MyArray<const T>>(ar));
</code>```

(actually in my code I hid the reinterpret cast in an inlined function with more verbose name, but the end game is the same). The class MyArray does not have a specialization for const T that makes it not reinterpretable, so the cast should be 'safe'. But this is not really a nice solution to read. An alternative, would be to duplicate foo's signature, to have a version taking MyArray<T>, which implementation does the cast and calls the const version. The problem with this is code duplication (and I have quite a few functions foo that need to be duplicated).

Perhaps some extra template magic on the signature of foo? The goal is to pass both MyArray<T> and MyArray<const T>, while still retaining const-correctness (i.e., make the compiler bark if I accidentally change the input in the function body).

Edit 1: The class MyArray (whose implementation is not under my control), has const accessors, since it stores pointers. So calling v[3] will modify the values in the array, but not the members stored in the class (namely a pointer and some smart-pointer-like metadata). In other words, the object is de facto not modified by accessors, though the array is. It's a semantic distinction. Not sure why they went this direction (I have an idea, but too long to explain).

Edit 2: I accepted one of the two answers (though they were somewhat similar). I am not sure (for reasons long to explain) that the wrapper class is doable in my case (maybe, I have to think about it). I am also puzzled by the fact that, while

```<code>template<typename T>
void foo(const MyArray<const T>& x);
MyArray<int> a;
foo(a);
</code>```

does not compile, the following does

```<code>void foo(const MyArray<const int>& x);
MyArray<int> a;
foo(a);
</code>```

Note: MyArray does offer a templated "copy constructor" with signature

```<code>template<typename S>
MyArray(const MyArray<S>&);
</code>```

so it can create MyArray<const T> from MyArray<T>. I am puzzled why it works when T is explicit, while it doesn't if T is a template parameter.

答:
Here's an ugly but effective way to have a function use one type, but also get the compiler to check that the same code would compile if it used a different type instead:</p>

```<code>template <typename From, typename To>
struct xfer_refs_cv
{
    using type = To;
};
template <typename From, typename To>
struct xfer_refs_cv<const From, To>
{
    using type = const typename xfer_refs_cv<From, To>::type;
};
template <typename From, typename To>
struct xfer_refs_cv<volatile From, To>
{
    using type = volatile typename xfer_refs_cv<From, To>::type;
};
template <typename From, typename To>
struct xfer_refs_cv<From&, To>
{
    using type = typename xfer_refs_cv<From, To>::type&;
};
template <typename From, typename To>
struct xfer_refs_cv<From&&, To>
{
    using type = typename xfer_refs_cv<From, To>::type&&;
};

template <typename CheckType, typename Func, typename CallType>
constexpr decltype(auto) check_and_call(Func&& f, CallType&& call_arg)
    noexcept(noexcept(std::forward<Func>(f)(std::forward<CallType>(call_arg))))
{
    (void) decltype(std::declval<Func&&>()
      (std::declval<typename xfer_refs_cv<CallType&&, CheckType>::type>()), 0){};
    return std::forward<Func>(f)(std::forward<CallType>(call_arg));
}

template<typename T>
void foo(const MyArray<T>& x)
{
    check_and_call<MyArray<const T>>(
        [](auto&& x) {
        // Function implementation here.
    }, x);
}
</code>```

Body:
I think the problem is fairly common, so there should be a known solution. I came up with one, but I'm not really satisfied, so I'm asking here, hoping someone can help.

Say I have a function, whose signature is

template<typename T>
void foo(const MyArray<const T>& x);

The const in the template parameter is to prevent me from changin the array content, since (for reasons beyond this question), the accessors ([] and ()) of MyArray<T> are always marked const, and return references to T (hence, the const ensure safety, since MyArray<T>::operator[] returns T&, while MyArray<const T>::operator[] returns const T&).

Great. However, templates with different template arguments are non related, so I can't bind a reference to MyClass<T> to a reference of MyClass<const T>, meaning I can't do this

MyArray<double> ar(/*blah*/);
foo(ar);

Notice that, without a reference, the code above would work provided that there is a copy constructor that lets me create MyArray<const T> from MyArray<T>. However, I don't want to remove the reference, since the array construction would happen a lot of times, and, despite relatively cheap, its cost would add up.

So the question: how can I call foo with an MyArray<T>?

My only solution so far is the following:

MyArray<T> ar(/*blah*/);
foo(reinterpret_cast<MyArray<const T>>(ar));

(actually in my code I hid the reinterpret cast in an inlined function with more verbose name, but the end game is the same). The class MyArray does not have a specialization for const T that makes it not reinterpretable, so the cast should be 'safe'. But this is not really a nice solution to read. An alternative, would be to duplicate foo's signature, to have a version taking MyArray<T>, which implementation does the cast and calls the const version. The problem with this is code duplication (and I have quite a few functions foo that need to be duplicated).

Perhaps some extra template magic on the signature of foo? The goal is to pass both MyArray<T> and MyArray<const T>, while still retaining const-correctness (i.e., make the compiler bark if I accidentally change the input in the function body).

Edit 1: The class MyArray (whose implementation is not under my control), has const accessors, since it stores pointers. So calling v[3] will modify the values in the array, but not the members stored in the class (namely a pointer and some smart-pointer-like metadata). In other words, the object is de facto not modified by accessors, though the array is. It's a semantic distinction. Not sure why they went this direction (I have an idea, but too long to explain).

Edit 2: I accepted one of the two answers (though they were somewhat similar). I am not sure (for reasons long to explain) that the wrapper class is doable in my case (maybe, I have to think about it). I am also puzzled by the fact that, while

template<typename T>
void foo(const MyArray<const T>& x);
MyArray<int> a;
foo(a);

does not compile, the following does

void foo(const MyArray<const int>& x);
MyArray<int> a;
foo(a);

Note: MyArray does offer a templated "copy constructor" with signature

template<typename S>
MyArray(const MyArray<S>&);

so it can create MyArray<const T> from MyArray<T>. I am puzzled why it works when T is explicit, while it doesn't if T is a template parameter.

Body:
Here's an ugly but effective way to have a function use one type, but also get the compiler to check that the same code would compile if it used a different type instead:

template <typename From, typename To>
struct xfer_refs_cv
{
    using type = To;
};
template <typename From, typename To>
struct xfer_refs_cv<const From, To>
{
    using type = const typename xfer_refs_cv<From, To>::type;
};
template <typename From, typename To>
struct xfer_refs_cv<volatile From, To>
{
    using type = volatile typename xfer_refs_cv<From, To>::type;
};
template <typename From, typename To>
struct xfer_refs_cv<From&, To>
{
    using type = typename xfer_refs_cv<From, To>::type&;
};
template <typename From, typename To>
struct xfer_refs_cv<From&&, To>
{
    using type = typename xfer_refs_cv<From, To>::type&&;
};

template <typename CheckType, typename Func, typename CallType>
constexpr decltype(auto) check_and_call(Func&& f, CallType&& call_arg)
    noexcept(noexcept(std::forward<Func>(f)(std::forward<CallType>(call_arg))))
{
    (void) decltype(std::declval<Func&&>()
      (std::declval<typename xfer_refs_cv<CallType&&, CheckType>::type>()), 0){};
    return std::forward<Func>(f)(std::forward<CallType>(call_arg));
}

template<typename T>
void foo(const MyArray<T>& x)
{
    check_and_call<MyArray<const T>>(
        [](auto&& x) {
        // Function implementation here.
    }, x);
}


问:
Getting sheet names from a large Excel file
I am using Python 3.7 and using OpenPyxl to read the sheet names from a large excel workbook (29MB) with 10 tabs.

```<code>import openpyxl
from openpyxl import load_workbook
wb = load_workbook(filename='h:\\Master_Portfoliio.xlsx')
print(wb.sheetnames)
</code>```

The code above works for smaller files but when I use the same code for this file, the code just hangs.  I would like to read the sheet names and then remove a tab and then copy a tab from another excel workbook into this workbook.

答:
Have you tried the read_only = True flag?

```<code>wb = load_workbook(filename='h:\\Master_Portfoliio.xlsx', read_only = True)
</code>```

Body:
I am using Python 3.7 and using OpenPyxl to read the sheet names from a large excel workbook (29MB) with 10 tabs.

import openpyxl
from openpyxl import load_workbook
wb = load_workbook(filename='h:\\Master_Portfoliio.xlsx')
print(wb.sheetnames)

The code above works for smaller files but when I use the same code for this file, the code just hangs.  I would like to read the sheet names and then remove a tab and then copy a tab from another excel workbook into this workbook.

Body:
Have you tried the read_only = True flag?

wb = load_workbook(filename='h:\\Master_Portfoliio.xlsx', read_only = True)


问:
Encoding error when trying to obtain list of files from Google Drive Api v3
I am trying to learn how to program a web app that queries Google Drive Api. My web is in python-Flask. I've gone through most details successfully but I'm stuck here:

@app.route('/analyze')
def analyze():
    if 'credentials' not in session:
        return redirect('authorize')
    credentials = google.oauth2.credentials.Credentials(session['credentials'])

drive_service = googleapiclient.discovery.build('drive', 'v3', credentials=credentials)
    files = drive_service.files().list().execute()
```

The credentials are loaded from the session (the user goes through the authorization flow in a different page / script). On this script, we recover the session and make a call to the Google Api:

But the call drive.files().list().execute() fails

The error is in the API's response and is as follows:

ValueError: {'client_id': 'heregoesclientid', 'client_secret': 'thisisclientsecret', 'refresh_token': 'xxxxxxxxxxxxxxxxxx', 'scopes': ['https://www.googleapis.com/auth/drive'], 'token': 'xxxxxxxxxxxxxxxxxxxxxxxx', 'token_uri': 'https://oauth2.googleapis.com/token'} could not be converted to unicode

Why can't the response be converted to Unicode? Is this a bug in Google API? Is there anything I could do to solve this?

答:
If you're using the google-auth package, you need to pass the values into Credentials individually, instead of a dict: See here.

Your code may then look like:

```<code>    sc = session['credentials']
    credentials = google.oauth2.credentials.Credentials(
        token=sc.get('token'),
        client_id=sc.get('client_id'),
        ...etc

    )
</code>```

Hope this helps, or let me know if you're not using google-auth, as this will be irrelevant.

Body:
I am trying to learn how to program a web app that queries Google Drive Api. My web is in python-Flask. I've gone through most details successfully but I'm stuck here:

@app.route('/analyze')
def analyze():
    if 'credentials' not in session:
        return redirect('authorize')
    credentials = google.oauth2.credentials.Credentials(session['credentials'])

drive_service = googleapiclient.discovery.build('drive', 'v3', credentials=credentials)
    files = drive_service.files().list().execute()

The credentials are loaded from the session (the user goes through the authorization flow in a different page / script). On this script, we recover the session and make a call to the Google Api:

But the call drive.files().list().execute() fails

The error is in the API's response and is as follows:

ValueError: {'client_id': 'heregoesclientid', 'client_secret': 'thisisclientsecret', 'refresh_token': 'xxxxxxxxxxxxxxxxxx', 'scopes': ['https://www.googleapis.com/auth/drive'], 'token': 'xxxxxxxxxxxxxxxxxxxxxxxx', 'token_uri': 'https://oauth2.googleapis.com/token'} could not be converted to unicode

Why can't the response be converted to Unicode? Is this a bug in Google API? Is there anything I could do to solve this?

Body:
If you're using the google-auth package, you need to pass the values into Credentials individually, instead of a dict: See here.

Your code may then look like:

    sc = session['credentials']
    credentials = google.oauth2.credentials.Credentials(
        token=sc.get('token'),
        client_id=sc.get('client_id'),
        ...etc

    )

Hope this helps, or let me know if you're not using google-auth, as this will be irrelevant.


问:
How to operate bitwise? (Operator & cannot be applied to Integer or int)
I want to check some permissions on an android app, I got these permissions from an API I use for different devices and coding languages, but this is my first attempt on JAVA (Android), and seems it is different.

In my App these permissions are in a class which returns them as an Integer, so if I want to check if the user can delete (decimal 4) I want to do something like this:

```<code>if(MyClass.getBit()&4){ // Is bit 2 on?
    // Yes, is on
}
</code>```

I got the following error:

Required Boolean, Found Int.

That's ok, I can made it boolean:

```<code>if(MyClass.getBit()&4 != 0){ // Is bit&4 not 0?
    // Yes, it is different
}
</code>```

I get a new error:

Operator '&' cannot be applied to 'java.lang.Integer', 'boolean'

So I changed the returned value to int, I got the same:

Operator '&' cannot be applied to 'int', 'boolean'

Seems like I am not going on the correct way...

How to operate bitwises on Android?

答:
It's a precedence issue, you have to add parentheses,

```<code>if ((MyClass.getBit()&4) != 0){ // Is bit&4 not 0?
    // Yes, it is different
}
</code>```

Without parentheses, it would perform the  (4 != 0) part first, which returns a boolean, then do the AND operator on that boolean and the integer on the left.

Body:
I want to check some permissions on an android app, I got these permissions from an API I use for different devices and coding languages, but this is my first attempt on JAVA (Android), and seems it is different.

In my App these permissions are in a class which returns them as an Integer, so if I want to check if the user can delete (decimal 4) I want to do something like this:

if(MyClass.getBit()&4){ // Is bit 2 on?
    // Yes, is on
}

I got the following error:

Required Boolean, Found Int.

That's ok, I can made it boolean:

if(MyClass.getBit()&4 != 0){ // Is bit&4 not 0?
    // Yes, it is different
}

I get a new error:

Operator '&' cannot be applied to 'java.lang.Integer', 'boolean'

So I changed the returned value to int, I got the same:

Operator '&' cannot be applied to 'int', 'boolean'

Seems like I am not going on the correct way...

How to operate bitwises on Android?

Body:
It's a precedence issue, you have to add parentheses,

if ((MyClass.getBit()&4) != 0){ // Is bit&4 not 0?
    // Yes, it is different
}

Without parentheses, it would perform the  (4 != 0) part first, which returns a boolean, then do the AND operator on that boolean and the integer on the left.


问:
D3.js TypeError: attempted to assign readonly property

I'm trying to display a forced-directed network graph using D3.js with the network graph json itself generated by Cytoscape.

Edit: Issue is recreated with Bl.ock Builder

```<code><html>
<!DOCTYPE html>
<meta charset="utf-8">
<style>

    .links line {
        stroke: #999;
        stroke-opacity: 0.6;
    }

    .nodes circle {
        stroke: #fff;
        stroke-width: 1.5px;
    }

</style>
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script type="text/javascript">
    var svg = d3.select("svg"),
        width = +svg.attr("width"),
        height = +svg.attr("height");

    var color = d3.scaleOrdinal(d3.schemeCategory20);

    var simulation = d3.forceSimulation()
        .force("link", d3.forceLink().id(function(d) { return d.id;     }))
    .force("charge", d3.forceManyBody())
    .force("center", d3.forceCenter(width / 2, height / 2));

d3.json("onemode2.json", function(error, graph) {
    if (error) throw error;

    var link = svg.append("g")
        .attr("class", "links")
        .selectAll("line")
        .data(graph.links)
        .enter().append("line")
        .attr("stroke-width", function(d) { return Math.sqrt(d.value); });

    var node = svg.append("g")
        .attr("class", "nodes")
        .selectAll("circle")
        .data(graph.nodes)
        .enter().append("circle")
        .attr("r", 5)
        .attr("fill", function(d) { return color(d.group); })
        .call(d3.drag()
            .on("start", dragstarted)
            .on("drag", dragged)
            .on("end", dragended));

    node.append("title")
        .text(function(d) { return d.id; });

    simulation
        .nodes(graph.nodes)
        .on("tick", ticked);

    simulation.force("link")
        .links(graph.links);

    function ticked() {
        link
            .attr("x1", function(d) { return d.source.x; })
            .attr("y1", function(d) { return d.source.y; })
            .attr("x2", function(d) { return d.target.x; })
            .attr("y2", function(d) { return d.target.y; });

        node
            .attr("cx", function(d) { return d.x; })
            .attr("cy", function(d) { return d.y; });
    }
});

function dragstarted(d) {
    if (!d3.event.active) simulation.alphaTarget(0.3).restart();
    d.fx = d.x;
    d.fy = d.y;
}

function dragged(d) {
    d.fx = d3.event.x;
    d.fy = d3.event.y;
}

    function dragended(d) {
        if (!d3.event.active) simulation.alphaTarget(0);
        d.fx = null;
        d.fy = null;
    }

</script>
</html>
</code>```

This should look like https://bl.ocks.org/mbostock/4062045. And the strange thing is that this worked with this data.

But what I'm getting looks like:

Any help would be appreciated!

答: Validate your "links", if either "source" or "target" has no corresponding "id" in "nodes" array that kind of error occurs</p>

Body:
I'm trying to display a forced-directed network graph using D3.js with the network graph json itself generated by Cytoscape.

Edit: Issue is recreated with Bl.ock Builder

<!DOCTYPE html>
<meta charset="utf-8">

<svg width="960" height="600"></svg>

This should look like https://bl.ocks.org/mbostock/4062045. And the strange thing is that this worked with this data.

But what I'm getting looks like:

Any help would be appreciated!


问:
HTML5 Dynamically create Canvas
Hi there I have a question about dynamically creating a canvas using javascript.

I create a canvas like this:

```<code>var canvas = document.createElement('canvas');
canvas.id     = "CursorLayer";
canvas.width  = 1224;
canvas.height = 768;
canvas.style.zIndex   = 8;
canvas.style.position = "absolute";
canvas.style.border   = "1px solid";
</code>```

but when I try to locate it, I get a null value:

```<code>cursorLayer = document.getElementById("CursorLayer");
</code>```

Am I doing it wrong? Is there a better way to create a canvas using JavaScript?

答:
Alternative

Use element .innerHTML= which is quite fast in modern browsers

document.body.innerHTML = "<canvas width=500 height=150 id='CursorLayer'>";

// TEST

var ctx = CursorLayer.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(100, 100, 50, 50);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas { border: 1px solid black }</code>```

Title: HTML5 Dynamically create Canvas

Body:
Hi there I have a question about dynamically creating a canvas using javascript.

I create a canvas like this:

var canvas = document.createElement('canvas');
canvas.id     = "CursorLayer";
canvas.width  = 1224;
canvas.height = 768;
canvas.style.zIndex   = 8;
canvas.style.position = "absolute";
canvas.style.border   = "1px solid";

but when I try to locate it, I get a null value:

cursorLayer = document.getElementById("CursorLayer");

Am I doing it wrong? Is there a better way to create a canvas using JavaScript?

Body:
Alternative

Use element .innerHTML= which is quite fast in modern browsers

document.body.innerHTML = "<canvas width=500 height=150 id='CursorLayer'>";

// TEST

var ctx = CursorLayer.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(100, 100, 50, 50);

canvas { border: 1px solid black }


问:
Reference input ngModel to object in ngFor loop
I am trying to generate dynamic form using the array. In that array I am providing the FieldLabel & DataModel.
Here I want to use DataModel as the object reference. I want to update the referenced model when user update the value in Input Field.
I have searched a lot but not able to find the solution yet.

Is there any other way to achieve what I want?

I have tried Iterating the model and used the DataModel attribute in [(ngModel)] but it is taking that as a STRING (which is valid)  but I don't want this. I want to reference the main object instead of taking that as a string.

```<code>obj : any = {
      FirstName:"Taha",
      MiddleName:"Faheem",
      LastName:"Hussain",
      Address:
        {
          CurrentAddress:"USA",
          PermanentAddress:"Pakistan"
        }
  }

  fields: any[] = [
    {
      "FieldLabel": "First Name",
      "DataModel": "obj.FirstName"
    },
    {
      "FieldLabel": "Middle Name",
      "DataModel":"obj.MiddleName"
    },
    {
      "FieldLabel": "Current Address",
      "DataModel":"obj.Address.CurrentAddress"
    }
  ];
</code>```

```<code><div class="container" fxLayout="column" fxLayoutGap="10px">
  <div *ngFor="let field of fields">
    <input placeholder="{{field.FieldLabel | uppercase}}" [(ngModel)]="field.DataModel">
  </div>
  <div>
    <input placeholder="Last Name" [(ngModel)]="obj.LastName">
  </div>
  <br> {{obj|json}}
</div>
</code>```

I want to update the obj with the value user enter in ngFor input fields.

I am working to generated the complete dynamic form along with the formula on each fields using this approach.
Is there any better approach to get the desired result?

答:
By creating fields array and having DataModel, you have disconnected the original "obj" with input. If you want to take this approach then do following [Or see the following stackblitz - https://stackblitz.com/edit/angular-pdpqog?file=app/app.component.ts]- </p>

```<code>obj : any = {
      FirstName:"Taha",
      MiddleName:"Faheem",
      LastName:"Hussain"
  }

  fields: any[] = [
    {
      "FieldLabel": "Person Name",
      "property": 'FirstName',
      "value": this.obj.FirstName
    },
    {
      "FieldLabel": "Current Address",
      "property": 'MiddleName',
      "value": this.obj.MiddleName
    }
  ];

  onChange($event, field) {
    this.obj[field.property] = $event;
  }

<div class="container" fxLayout="column" fxLayoutGap="10px">
  <div *ngFor="let field of fields">
    <input placeholder="{{field.FieldLabel | uppercase}}" [ngModel]="field.value" (ngModelChange)="onChange($event, field)">
  </div>
  <div>
    <input placeholder="Last Name" [(ngModel)]="obj.LastName">
  </div>
  <br> {{obj|json}}
</div>
</code>```

Body:
I am trying to generate dynamic form using the array. In that array I am providing the FieldLabel & DataModel.
Here I want to use DataModel as the object reference. I want to update the referenced model when user update the value in Input Field.
I have searched a lot but not able to find the solution yet.

Is there any other way to achieve what I want?

I have tried Iterating the model and used the DataModel attribute in [(ngModel)] but it is taking that as a STRING (which is valid)  but I don't want this. I want to reference the main object instead of taking that as a string.

obj : any = {
      FirstName:"Taha",
      MiddleName:"Faheem",
      LastName:"Hussain",
      Address:
        {
          CurrentAddress:"USA",
          PermanentAddress:"Pakistan"
        }
  }

  fields: any[] = [
    {
      "FieldLabel": "First Name",
      "DataModel": "obj.FirstName"
    },
    {
      "FieldLabel": "Middle Name",
      "DataModel":"obj.MiddleName"
    },
    {
      "FieldLabel": "Current Address",
      "DataModel":"obj.Address.CurrentAddress"
    }
  ];

    <input placeholder="{{field.FieldLabel | uppercase}}" [(ngModel)]="field.DataModel">

    <input placeholder="Last Name" [(ngModel)]="obj.LastName">

 {{obj|json}}

I want to update the obj with the value user enter in ngFor input fields.

I am working to generated the complete dynamic form along with the formula on each fields using this approach.
Is there any better approach to get the desired result?

Body:
By creating fields array and having DataModel, you have disconnected the original "obj" with input. If you want to take this approach then do following [Or see the following stackblitz - https://stackblitz.com/edit/angular-pdpqog?file=app/app.component.ts]-

obj : any = {
      FirstName:"Taha",
      MiddleName:"Faheem",
      LastName:"Hussain"
  }

  fields: any[] = [
    {
      "FieldLabel": "Person Name",
      "property": 'FirstName',
      "value": this.obj.FirstName
    },
    {
      "FieldLabel": "Current Address",
      "property": 'MiddleName',
      "value": this.obj.MiddleName
    }
  ];

  onChange($event, field) {
    this.obj[field.property] = $event;
  }

<div class="container" fxLayout="column" fxLayoutGap="10px">
  <div *ngFor="let field of fields">
    <input placeholder="{{field.FieldLabel | uppercase}}" [ngModel]="field.value" (ngModelChange)="onChange($event, field)">
  </div>
  <div>
    <input placeholder="Last Name" [(ngModel)]="obj.LastName">
  </div>
  <br> {{obj|json}}
</div>