问:
How to add part of time in Android
I have a code returning me a string (HH:mm).

```<code>SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.util.Date dateObj;
        try {
            dateObj = curFormater.parse(start);

            SimpleDateFormat postFormater = new SimpleDateFormat("HH:mm");
            String newDateStr = postFormater.format(dateObj);
            startView.setText(newDateStr);
            Emission_start = newDateStr;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            Log.d(" * Error", e.toString());
        }
</code>```

It works great... But right now I would like to:

add x (is dynamically provided) minutes (x = from 5 to 1000 minutes) and transform to time (example time:3:45, add 25 minutes, transform to time 4:10)

Get current time and calculate difference between current time and time from step 1 (4:10)

Get time difference (from step 2) in minutes!

Thanks for your help!

答:
I haven't tested, but something like this should work:

long newDate = dateObj.getTime() +
(x * 60 * 1000)

long diff =
System.currentTimeMillis() - newDate

double diffInMins = diff / (60.0 * 1000.0)

Title: How to add part of time in Android

Body:
I have a code returning me a string (HH:mm).

SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        java.util.Date dateObj;
        try {
            dateObj = curFormater.parse(start);

            SimpleDateFormat postFormater = new SimpleDateFormat("HH:mm");
            String newDateStr = postFormater.format(dateObj);
            startView.setText(newDateStr);
            Emission_start = newDateStr;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            Log.d(" * Error", e.toString());
        }

It works great... But right now I would like to:

add x (is dynamically provided) minutes (x = from 5 to 1000 minutes) and transform to time (example time:3:45, add 25 minutes, transform to time 4:10)

Get current time and calculate difference between current time and time from step 1 (4:10)

Get time difference (from step 2) in minutes!

Thanks for your help!


来源: stackexchange

问:
Flutter application throws Http Exception and instantly crashes
currently I'm having a problem with running flutter applications. I tried to search solutions, but none of them was actually my case. The problem is, when I try to install an application, sometimes it starts running, but instantly crashes, or not even build, and throws this exception (even with flutter demo project):

```<code>Error connecting to the service protocol: HttpException: Connection closed before full header was received, uri = http://127.0.0.1:57564/ws".
</code>```

What I've tried so far: Cleaning cashes, reinstall flutter/android studio. I got this problem only with a few (android os) mobile.
        import 'package:flutter/material.dart';

```<code>void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(appBar: AppBar(title: Text("App"))),
    );
  }
}
</code>```

答:
I solved this problem creating a new emulator device but NOT using the most recent Android Image.

Android Studio > Configure > AVD Manager > Create Virtual Device > (Choose a device model) > (Select a system image, but NOT the most recent)

In my case, I had the following Android images as choices: Q, Pie 28, Oreo 27 and 26, etc.
I selected Pie 28 and the problem was solved. The problem was occuring with Android Q (most recent).

ContentLicense: CC BY-SA 4.0

Body:
currently I'm having a problem with running flutter applications. I tried to search solutions, but none of them was actually my case. The problem is, when I try to install an application, sometimes it starts running, but instantly crashes, or not even build, and throws this exception (even with flutter demo project):

Error connecting to the service protocol: HttpException: Connection closed before full header was received, uri = http://127.0.0.1:57564/ws".

What I've tried so far: Cleaning cashes, reinstall flutter/android studio. I got this problem only with a few (android os) mobile.
        import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(appBar: AppBar(title: Text("App"))),
    );
  }
}


问:
Lambda as a function parameter -> accept methods only from particular class
I wish to find solution to force emit(S.() -> S) function to accept as parameters, only methods from generic S class. Current solution accepts all lambda methods which returns S.
S is a generic class which has methods to reduce/modify own parameters. I want only those methods to be called in emit. It guarantees that every method passed to emit is "pure function" (all methods in S are pure)

```<code>val _uiState = MutableLiveData<S>()
var state: S
fun emit(reduction: S.() -> S) {
        state = reduction.invoke(state)
        if (_uiState.value != state) {
            _uiState.postValue(state)
        }
    }
</code>```

答:
For this, functions simply aren't an appropriate type. I'd declare a type whose values correspond to methods of S, so

```<code>class S {
    fun method1(x: String): S = ...
    fun method2(): S = ...
    ...

    sealed class Transform {
        operator fun invoke(s: S): S = when(this) {
            is Method1 -> s.method1(x)
            is Method2 -> s.method2()
            ...
        }

        class Method1(val x: String) : Transform
        object Method2 : Transform
    }
}

fun emit(reduction: S.Transform) {
    state = reduction.invoke(state)
    if (_uiState.value != state) {
        _uiState.postValue(state)
    }
}
</code>```

With some effort, Transform can be auto-generated (e.g. using an annotation processor, as you mention in a comment), but it may not be worth it depending on how many classes and methods you need to handle and how often they change.

Body:
I wish to find solution to force emit(S.() -> S) function to accept as parameters, only methods from generic S class. Current solution accepts all lambda methods which returns S.
S is a generic class which has methods to reduce/modify own parameters. I want only those methods to be called in emit. It guarantees that every method passed to emit is "pure function" (all methods in S are pure)

val _uiState = MutableLiveData<S>()
var state: S
fun emit(reduction: S.() -> S) {
        state = reduction.invoke(state)
        if (_uiState.value != state) {
            _uiState.postValue(state)
        }
    }

Body:
For this, functions simply aren't an appropriate type. I'd declare a type whose values correspond to methods of S, so

class S {
    fun method1(x: String): S = ...
    fun method2(): S = ...
    ...

    sealed class Transform {
        operator fun invoke(s: S): S = when(this) {
            is Method1 -> s.method1(x)
            is Method2 -> s.method2()
            ...
        }

        class Method1(val x: String) : Transform
        object Method2 : Transform
    }
}

fun emit(reduction: S.Transform) {
    state = reduction.invoke(state)
    if (_uiState.value != state) {
        _uiState.postValue(state)
    }
}

With some effort, Transform can be auto-generated (e.g. using an annotation processor, as you mention in a comment), but it may not be worth it depending on how many classes and methods you need to handle and how often they change.


问:
Restrict access to images in bucket to authenticated users
Looking for instructions on how to setup Google Cloud Storage bucket with images that only authenticated users can access.

Our application uses Firstore and Cloud Storage. We store images in GCS buckets which we do not want publicly visible on the NET.
We have setup storage rules

```<code>allow read: if request.auth.uid != null;
</code>```

We have also configured the bucket in our Firebase config settings.
We then use the storage API to getDownloadURL() for the target path.
This works and we are able to see the images. However, if we copy the Image URL from the page and go to another browser (that is not logged in) that browser is able to download the image.

Question: what is the correct (and most efficient) way to configure and access a GCS bucket such that only authenticated users authenticated using Firebase signInWithEmailAndPassword() can view the images.

Here is what we do currently (Angular and AngularFire)

```<code>// Assumes storage is an instance of the AngularFireStorage service
this.storage.getDownloadURL('/thumbs/imagename.jpg')
  .subscribe(path => {
     this.imgSrc = path;
});
</code>```

As described above, the resulting path is public and the above process is very slow - images take a long time to appear on the screen.

I am guessing this is not the right approach?

答: The content behind a download URLs can always be viewed by anyone who simply has the URL.  You can't change this behavior.  If you don't want any unauthorized content to be served from your bucket, then don't generate any download URLs.  You will have to force all access to the bucket through the provided client SDKs in conjunction with the Firebase Authentication SDK.</p>

Body:
Looking for instructions on how to setup Google Cloud Storage bucket with images that only authenticated users can access.

Our application uses Firstore and Cloud Storage. We store images in GCS buckets which we do not want publicly visible on the NET.
We have setup storage rules

allow read: if request.auth.uid != null;

We have also configured the bucket in our Firebase config settings.
We then use the storage API to getDownloadURL() for the target path.
This works and we are able to see the images. However, if we copy the Image URL from the page and go to another browser (that is not logged in) that browser is able to download the image.

Question: what is the correct (and most efficient) way to configure and access a GCS bucket such that only authenticated users authenticated using Firebase signInWithEmailAndPassword() can view the images.

Here is what we do currently (Angular and AngularFire)

// Assumes storage is an instance of the AngularFireStorage service
this.storage.getDownloadURL('/thumbs/imagename.jpg')
  .subscribe(path => {
     this.imgSrc = path;
});

As described above, the resulting path is public and the above process is very slow - images take a long time to appear on the screen.

I am guessing this is not the right approach?


问:
How to split each digit of a number into different rows
I want something like SELECT splitDigits(123456789) as digits to return:

 digits
-------
  1
  2
  3
  4
  5
  6
  7
  8
  9
```

What I really need

I'm trying to make this validation (Perú's RUC ID) in a stored procedure:

I'm trying to avoid loops so I'm stuck in the first step, which is to grab the first 10 digits and multiply each digit by a fixed scalar that depends on the position, then I have to sum all those multiplications.

It's basically vector multiplication, and I'm trying to construct a vector from the first 10 digit of an 11-digit-number.

答:
```<code>SELECT
    SUBSTR(3987654321, idx, 1) AS SplitDigits,
    3 * (SUBSTR(3987654321, idx, 1)) AS ConstTimesSplitDigits
   -- SUM(SUBSTR(2050364496, idx, 1) * (SUBSTR(5432765432, idx, 1))) AS Result
FROM (SELECT @cnt := 0) A
-- cross join any table has rows greater than or equal to your liking
CROSS JOIN (SELECT (@cnt := @cnt + 1) idx FROM INFORMATION_SCHEMA.TABLES LIMIT 10) B
;
</code>```

Body:
I want something like SELECT splitDigits(123456789) as digits to return:

 digits
-------
  1
  2
  3
  4
  5
  6
  7
  8
  9

What I really need

I'm trying to make this validation (Perú's RUC ID) in a stored procedure:

I'm trying to avoid loops so I'm stuck in the first step, which is to grab the first 10 digits and multiply each digit by a fixed scalar that depends on the position, then I have to sum all those multiplications.

It's basically vector multiplication, and I'm trying to construct a vector from the first 10 digit of an 11-digit-number.


问:
Is there a way to apply settings in MS Access without restarting the database?
In my project it is necessary to have some specific settings for "normal users" and the normal view for Admin users. But everytime a setting is done I will have to restart the database in order for them to be applied.

An example would be:

```<code>CurrentDb.Properties("ShowDocumentTabs").Value = False
</code>```

This turns off the document tabs - but only if I restart the database. Is there a way to do this without a reload?

答:
No, AFAIK.

Startup options are evaluated and applied when opening a database.

Body:
In my project it is necessary to have some specific settings for "normal users" and the normal view for Admin users. But everytime a setting is done I will have to restart the database in order for them to be applied.

An example would be:

CurrentDb.Properties("ShowDocumentTabs").Value = False

This turns off the document tabs - but only if I restart the database. Is there a way to do this without a reload?


问:
How to call ansible playbook in terraform code?
I have an ansible playbook which works well , now I have to call that playbook using terrform scripts. Currently I m using code which is shown below but it results in error during terraform init as:
Error: Unknown root level key: provisioner

I am using Terraform v0.11.7 and the error occurs only when I run this specific code.
Also my main.tf consists of only this code. The directory structure I have used is such as :

```<code>.
├── create-user.yml
├── library
│   └── mkpassword.py
├── main.tf
├── outputs.tf
├── roles
│   └── linux_user_creation
│       └── tasks
│           └── main.yml
└── variables.tf
</code>```

main.tf looks like :

```<code>  provisioner "remote-exec" {
  inline = ["sudo dnf -y install python"]

  connection {
    type        = "ssh"
    user        = "ubuntu"
    private_key = "${file(var.ssh_keyname)}"
  }
}

provisioner "remote-exec" {
  command = ["ansible-playbook -u root --private-key ${var.ssh_keyname} -i ${self.ipv4_address} create-user.yml -e 'email_id=${var.email_id}'"]
}
</code>```

I expect the playbook should be called from the terraform scripts and should display the results.

答:
The code snipped form main.tf is not complete. Could you post the full resource definitions in which you run the remote-exec provisioners please?

An what should the Ansible playbook do? Create a user on the remote host itself? Or is it just a host where your Ansible scripts are stored, and the user is actually created on another remote host from there?

As @ydaetskcoR mentioned, you need to run this code within a null_resource:

```<code>null_resource "provisioner" {
  connection {
    ... # set the connection parameters here
  }

  provisioner "remote-exec" {
    command = ["ansible-playbook -u root --private-key ${var.ssh_keyname} -i ${self.ipv4_address} create-user.yml -e 'email_id=${var.email_id}'"]
  }
}
</code>```

I'd however suggest to install the Ansible provisioner, as already mentioned in the comment above. This way you'd bundle the Ansible playbook directly with your Terraform code and won't not need to connect to some other instance.

Body:
I have an ansible playbook which works well , now I have to call that playbook using terrform scripts. Currently I m using code which is shown below but it results in error during terraform init as:
Error: Unknown root level key: provisioner

I am using Terraform v0.11.7 and the error occurs only when I run this specific code.
Also my main.tf consists of only this code. The directory structure I have used is such as :

.
├── create-user.yml
├── library
│   └── mkpassword.py
├── main.tf
├── outputs.tf
├── roles
│   └── linux_user_creation
│       └── tasks
│           └── main.yml
└── variables.tf

main.tf looks like :

  provisioner "remote-exec" {
  inline = ["sudo dnf -y install python"]

  connection {
    type        = "ssh"
    user        = "ubuntu"
    private_key = "${file(var.ssh_keyname)}"
  }
}

provisioner "remote-exec" {
  command = ["ansible-playbook -u root --private-key ${var.ssh_keyname} -i ${self.ipv4_address} create-user.yml -e 'email_id=${var.email_id}'"]
}

I expect the playbook should be called from the terraform scripts and should display the results.

Body:
The code snipped form main.tf is not complete. Could you post the full resource definitions in which you run the remote-exec provisioners please?

An what should the Ansible playbook do? Create a user on the remote host itself? Or is it just a host where your Ansible scripts are stored, and the user is actually created on another remote host from there?

As @ydaetskcoR mentioned, you need to run this code within a null_resource:

null_resource "provisioner" {
  connection {
    ... # set the connection parameters here
  }

  provisioner "remote-exec" {
    command = ["ansible-playbook -u root --private-key ${var.ssh_keyname} -i ${self.ipv4_address} create-user.yml -e 'email_id=${var.email_id}'"]
  }
}

I'd however suggest to install the Ansible provisioner, as already mentioned in the comment above. This way you'd bundle the Ansible playbook directly with your Terraform code and won't not need to connect to some other instance.


问:
Is it possible to measure accurate Milliseconds time between few code statements using python?
I am developing a python application using Python2.7.
That application is using pyserial library to read some data bytes from serial port.
Using while loop to read 1 byte of data in each iteration. In each iteration
I have to measure execution time between statements if it is less than 10 ms wait for it to reach 10ms before starting next iteration. there are two questions here as follows:

Time measurement

What would be the best way to measure time between python statements to the accuracy (1ms or 2ms difference acceptable) of milliseconds.

Time delay

How can i use that measured time for delay in order to wait till total time is 10ms (total time = 10ms = code execution time+delay)

I have tried time library but it does not give a good resolution when in millisecond some time it does not give anything when small time duration.
for example:

```<code>import time
while uart.is_open:
uart.read()
start = time.time()
#user code will go here

end = time.time()
execution_time=end - start
if execution_time< 10ms:
remaining_time = 10ms - execution_time
delay(remaining_time)
</code>```

答:
Solution:

I have managed to get upto 1ms resolution by doing two things.

Changed (increased) the baud rate to 115200 from 19200.

Used time.clock() rather than time.time() as it has more accuracy and resolution.

Body:
I am developing a python application using Python2.7.
That application is using pyserial library to read some data bytes from serial port.
Using while loop to read 1 byte of data in each iteration. In each iteration
I have to measure execution time between statements if it is less than 10 ms wait for it to reach 10ms before starting next iteration. there are two questions here as follows:

Time measurement

What would be the best way to measure time between python statements to the accuracy (1ms or 2ms difference acceptable) of milliseconds.

Time delay

How can i use that measured time for delay in order to wait till total time is 10ms (total time = 10ms = code execution time+delay)

I have tried time library but it does not give a good resolution when in millisecond some time it does not give anything when small time duration.
for example:

import time
while uart.is_open:
uart.read()
start = time.time()
#user code will go here

end = time.time()
execution_time=end - start
if execution_time< 10ms:
remaining_time = 10ms - execution_time
delay(remaining_time)


问:
didn't return an HttpResponse object. It returned None instead
When incorrectly registering a user to my site I get this following error:

ValueError at /accounts/register/ The view accounts.views.register
  didn't return an HttpResponse   object. It returned None instead.

views.py:

```<code>def register(request):
   if request.method == 'POST':
      form = RegistrationForm(request.POST)
      if form.is_valid():
          form.save()
          return redirect('/accounts')

   else:
      form = RegistrationForm()

      args = {'form': form}
      return render(request, 'accounts/reg_form.html', args)
</code>```

urls.py:

```<code>urlpatterns = [
  path('', views.home, name="home"),
  path('explore/', views.explore, name='explore'),
  path('login/', LoginView.as_view(template_name='accounts/login.html'), name='login'),
  path('logout/', LogoutView.as_view(template_name='accounts/logout.html'), name='logout'),
  path('register/', views.register, name='register'),
  path('profile/', views.view_profile, name='profile'),
  path('profile/edit/', views.edit_profile, name='profile-edit'),
  path('change-password/', views.change_password, name='change_password'),
  path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'),
     name='reset-password'),
  path('reset-password/done/', PasswordResetDoneView.as_view(), name='password_reset_done'),
  path('reset-password/confirm/<uidb64>/<token>/',
     PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
  path('reset-password/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]
</code>```

main/urls.py:

```<code>urlpatterns = [
   path('', views.login_redirect, name='login_redirect'),
   path('admin/', admin.site.urls),
   path('accounts/', include('accounts.urls')),

  ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

答:
You should move the last two lines back one level.</p>

```<code>else:
  form = RegistrationForm()

args = {'form': form}
return render(request, 'accounts/reg_form.html', args)
</code>```

Body:
When incorrectly registering a user to my site I get this following error:

ValueError at /accounts/register/ The view accounts.views.register
  didn't return an HttpResponse   object. It returned None instead.

views.py:

def register(request):
   if request.method == 'POST':
      form = RegistrationForm(request.POST)
      if form.is_valid():
          form.save()
          return redirect('/accounts')

   else:
      form = RegistrationForm()

      args = {'form': form}
      return render(request, 'accounts/reg_form.html', args)

urls.py:

urlpatterns = [
  path('', views.home, name="home"),
  path('explore/', views.explore, name='explore'),
  path('login/', LoginView.as_view(template_name='accounts/login.html'), name='login'),
  path('logout/', LogoutView.as_view(template_name='accounts/logout.html'), name='logout'),
  path('register/', views.register, name='register'),
  path('profile/', views.view_profile, name='profile'),
  path('profile/edit/', views.edit_profile, name='profile-edit'),
  path('change-password/', views.change_password, name='change_password'),
  path('reset-password/', PasswordResetView.as_view(template_name='accounts/reset_password.html'),
     name='reset-password'),
  path('reset-password/done/', PasswordResetDoneView.as_view(), name='password_reset_done'),
  path('reset-password/confirm/<uidb64>/<token>/',
     PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
  path('reset-password/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'),
]

main/urls.py:

urlpatterns = [
   path('', views.login_redirect, name='login_redirect'),
   path('admin/', admin.site.urls),
   path('accounts/', include('accounts.urls')),

  ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Body:
You should move the last two lines back one level.

else:
  form = RegistrationForm()

args = {'form': form}
return render(request, 'accounts/reg_form.html', args)


问:
SQL query MAX() function
```<code>select ProductID,ProductName,QuantityPerUnit
from Products
where Products.UnitPrice=Max(UnitPrice)
</code>```

What is wrong in this query?

I had tried 'having' in place of 'where' tag.

```<code>select ProductID,ProductName,QuantityPerUnit
from Products
having Products.UnitPrice=Max(UnitPrice)
</code>```

it must produce result with max unit price,

```<code>ProductID   ProductName     QuantityPerUnit
38          Côte de Blaye   12 - 75 cl bottles
</code>```

答:
If you want the product(s) with the maximum UnitPrice:

```<code>select ProductID,ProductName,QuantityPerUnit
from Products
where UnitPrice = (select Max(UnitPrice) from Products)
</code>```

This query:

```<code>select Max(UnitPrice) from Products
</code>```

returns the maximum UnitPrice.

If there are more than 1 products with that price, they will all be returned.

If you want just 1, you can use LIMIT 1 or TOP 1, depending on the rdbms you use.

Title: SQL query MAX() function

Body:
select ProductID,ProductName,QuantityPerUnit
from Products
where Products.UnitPrice=Max(UnitPrice)

What is wrong in this query?

I had tried 'having' in place of 'where' tag.

select ProductID,ProductName,QuantityPerUnit
from Products
having Products.UnitPrice=Max(UnitPrice)

it must produce result with max unit price,

ProductID   ProductName     QuantityPerUnit
38          Côte de Blaye   12 - 75 cl bottles

Body:
If you want the product(s) with the maximum UnitPrice:

select ProductID,ProductName,QuantityPerUnit
from Products
where UnitPrice = (select Max(UnitPrice) from Products)

This query:

select Max(UnitPrice) from Products

returns the maximum UnitPrice.

If there are more than 1 products with that price, they will all be returned.

If you want just 1, you can use LIMIT 1 or TOP 1, depending on the rdbms you use.


问:
decoding with jquery .serialize()
I all. I posted yesterday a question regarding dates not sent with jquery-ajax and found a solution with the .serialize() function.

Unfortunately the serialize() function decodes the date inputs and the result I get is this:

```<code>arrival= 13%2F04%2F2011 &departure= 28%2F04%2F2011 &ap_ID=2
</code>```

I know how use decodeURIComponent() for single fields post like this:

```<code> var arrivalVal = $('#arrival').val();

 arrivalVal = decodeURIComponent(arrival);
</code>```

but how do I use it for the long string made by the .serialize() function?

Sorry if this seems a pretty obvious question but can't get my way around it.

答:
try with that

```<code>var editserialize = $('form#edit').serialize();
editserialize = decodeURIComponent(editserialize.replace(/%2F/g, " "))
</code>```

...

ContentLicense: CC BY-SA 3.0

Title: decoding with jquery .serialize()

Body:
I all. I posted yesterday a question regarding dates not sent with jquery-ajax and found a solution with the .serialize() function.

Unfortunately the serialize() function decodes the date inputs and the result I get is this:

arrival= 13%2F04%2F2011 &departure= 28%2F04%2F2011 &ap_ID=2

I know how use decodeURIComponent() for single fields post like this:

 var arrivalVal = $('#arrival').val();

 arrivalVal = decodeURIComponent(arrival);

but how do I use it for the long string made by the .serialize() function?

Sorry if this seems a pretty obvious question but can't get my way around it.

Body:
try with that

var editserialize = $('form#edit').serialize();
editserialize = decodeURIComponent(editserialize.replace(/%2F/g, " "))

...


问:
Kotlin extension function with generic types dependant on the receiver type parameter (without specifying it explicitly)
Sometimes I want to have an extension function on a generic type, whose parameter or return value is a subtype of the given type parameter, but without having to specify that actual type parameter. (maybe, if it isn't clear, the code will clarify it better?)

Using the signature of this answer:

```<code>inline fun <reified U : T, T> Iterable<T>.partitionByType(): Pair<List<U>, List<T>>
</code>```

It forces me to use it as follows:

```<code>val list : List<SomeType>
list.partitionByType<InterestedType, SomeType>()
</code>```

However, what I rather want to write is the following:

```<code>list.partitionByType<InterestedType>()
</code>```

Where InterestedType is a subtype of the type parameter of the list, i.e. SomeType. Both solutions above should then give me Pair<List<InterestedType>, List<SomeType>> as a return value.

This however isn't really possible. The best that comes to my mind is a signature similar as to follows:

```<code> inline fun <reified U : Any> Iterable<Any>.partitionByType(): Pair<List<U>, List<Any>>
</code>```

But then we lose the actual type T/SomeType which was known otherwise. An unchecked cast is still possible on the caller side, but that's not what I am after.

So my question is: is this somehow possible? Having something like U : T in place, without specifying the T? Or is there anything planned in this regard (KEEP or Kotlin issue available)?

For me it sounds like a reasonable feature, at least as long as it is applied on an extension function only. If it's not, what would be the problems of this that I am probably just overlooking/ignoring at the moment?
What I am not really looking for is a workaround (like having an intermediate type), but it may be worth it to have it as answer as well.

The more I think of it. Wouldn't it be more correct, if extension functions on generic types would be declared as follows?

```<code>fun SomeType<T>.extended()
</code>```

instead of

```<code>fun <T> SomeType<T>.extended()
</code>```

Because: if I were under control of SomeType<T> and would add that function there, I wouldn't need any generic type information to declare it, e.g. the following would suffice then:

```<code>fun extended()
</code>```

Same regarding functions with own generic types, e.g.:

```<code>fun <U : T> extended2()
</code>```

Adding that as extension function now forces one to add that T-generic type, although the type on which we would like to apply it, is clearly SomeType<T>:

```<code>fun <T, U: T> SomeType<T>.extended2()
</code>```

答:
Another not nearly elegant solution, which may be considered even worse than passing a type<T>() as it isn't universal and requires boilerplate for each such a function, is to return a wrapper object (that is similarly meaningless).

However, with the use of inline classes, it can be implemented without any runtime overhead, so I'll post it here anyway:

```<code>fun main() {
    println(listOf<Number>(1, 2.0, 3f).doPartition.byType<Int>())
}

inline class PartitionByTypeWrapper<T>(val list: List<T>) {
    inline fun <reified U : T> byType(): Pair<List<U>, List<T>> {
        val (us, ts) = list.partition { it is U }
        @Suppress("UNCHECKED_CAST")
        return us as List<U> to ts
    }
}

inline val <T> List<T>.doPartition get() = PartitionByTypeWrapper(this)
</code>```

Body:
Sometimes I want to have an extension function on a generic type, whose parameter or return value is a subtype of the given type parameter, but without having to specify that actual type parameter. (maybe, if it isn't clear, the code will clarify it better?)

Using the signature of this answer:

inline fun <reified U : T, T> Iterable<T>.partitionByType(): Pair<List, List<T>>

It forces me to use it as follows:

val list : List<SomeType>
list.partitionByType<InterestedType, SomeType>()

However, what I rather want to write is the following:

list.partitionByType<InterestedType>()

Where InterestedType is a subtype of the type parameter of the list, i.e. SomeType. Both solutions above should then give me Pair<List<InterestedType>, List<SomeType>> as a return value.

This however isn't really possible. The best that comes to my mind is a signature similar as to follows:

 inline fun <reified U : Any> Iterable<Any>.partitionByType(): Pair<List, List<Any>>

But then we lose the actual type T/SomeType which was known otherwise. An unchecked cast is still possible on the caller side, but that's not what I am after.

So my question is: is this somehow possible? Having something like U : T in place, without specifying the T? Or is there anything planned in this regard (KEEP or Kotlin issue available)?

For me it sounds like a reasonable feature, at least as long as it is applied on an extension function only. If it's not, what would be the problems of this that I am probably just overlooking/ignoring at the moment?
What I am not really looking for is a workaround (like having an intermediate type), but it may be worth it to have it as answer as well.

The more I think of it. Wouldn't it be more correct, if extension functions on generic types would be declared as follows?

fun SomeType<T>.extended()

instead of

fun <T> SomeType<T>.extended()

Because: if I were under control of SomeType<T> and would add that function there, I wouldn't need any generic type information to declare it, e.g. the following would suffice then:

fun extended()

Same regarding functions with own generic types, e.g.:

fun  extended2()

Adding that as extension function now forces one to add that T-generic type, although the type on which we would like to apply it, is clearly SomeType<T>:

fun <T, U: T> SomeType<T>.extended2()

Body:
Another not nearly elegant solution, which may be considered even worse than passing a type<T>() as it isn't universal and requires boilerplate for each such a function, is to return a wrapper object (that is similarly meaningless).

However, with the use of inline classes, it can be implemented without any runtime overhead, so I'll post it here anyway:

fun main() {
    println(listOf<Number>(1, 2.0, 3f).doPartition.byType<Int>())
}

inline class PartitionByTypeWrapper<T>(val list: List<T>) {
    inline fun <reified U : T> byType(): Pair<List<U>, List<T>> {
        val (us, ts) = list.partition { it is U }
        @Suppress("UNCHECKED_CAST")
        return us as List<U> to ts
    }
}

inline val <T> List<T>.doPartition get() = PartitionByTypeWrapper(this)


问:
Graphing time-series data when date column doesn't exist
I have the following data:

```<code>set.seed(12)
df <- rnorm(1260, 0.06, 0.2)
</code>```

These are 5 years worth of daily returns (with 1 year = 252 working days) and what I would like to do is draw a line-chart with months on the x axis. Basically, I would have the sequence Jan:Dec repeated five times on the x-axis, with 21 days being one month.

What I did is the following:

Create a column with months jan-dec repeated 5 times

date <- c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
          "Jul", "Aug", "Sep", "Okt", "Nov", "Dez")
date <- rep(date, 5)
```

<ol start="2">
<li>Draw graph</li>
</ol>

<pre class="lang-r prettyprint-override"><code>df %>%
       ggplot(aes(x = date, y = return)) +
       geom_line() +
       labs(title = "Stock return Chart", y = "return", x = "date")
</code>```

Unfortunately I get the following error:

```<code> Error: Aesthetics must be either length 1 or the same as the data (1260): x
</code>```

答:
library(tidyverse)

df %>%
    as.data.frame() %>%
    rename(price = 1) %>%
    mutate(rnames = rownames(.)) %>%
    ggplot(aes(x = as.numeric(rnames), y = price,
                group = rep(1:5, times=1, each=252))) +
      geom_line() +
      labs(title = "Stock Price Chart", y = "Price", x = "date") +
      scale_x_continuous(breaks = seq(1, 1260, by = 21), labels = date)
```

Created on 2019-05-27 by the reprex package (v0.3.0)

Body:
I have the following data:

set.seed(12)
df <- rnorm(1260, 0.06, 0.2)

These are 5 years worth of daily returns (with 1 year = 252 working days) and what I would like to do is draw a line-chart with months on the x axis. Basically, I would have the sequence Jan:Dec repeated five times on the x-axis, with 21 days being one month.

What I did is the following:

Create a column with months jan-dec repeated 5 times

date <- c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
          "Jul", "Aug", "Sep", "Okt", "Nov", "Dez")
date <- rep(date, 5)

Draw graph

df %>%
       ggplot(aes(x = date, y = return)) +
       geom_line() +
       labs(title = "Stock return Chart", y = "return", x = "date")

Unfortunately I get the following error:

 Error: Aesthetics must be either length 1 or the same as the data (1260): x

Body:
library(tidyverse)

df %>%
    as.data.frame() %>%
    rename(price = 1) %>%
    mutate(rnames = rownames(.)) %>%
    ggplot(aes(x = as.numeric(rnames), y = price,
                group = rep(1:5, times=1, each=252))) +
      geom_line() +
      labs(title = "Stock Price Chart", y = "Price", x = "date") +
      scale_x_continuous(breaks = seq(1, 1260, by = 21), labels = date)

Created on 2019-05-27 by the reprex package (v0.3.0)


问:
Use pandas to plot highest correlations
I have been plotting correlations via heatmaps with the following code. However, there are too many variables. Is it possible to plot the highest correlations ( over .5 and -.5) on a graph?</p>

```<code>plt.rcParams['figure.figsize'] = [80,80]
corr3 = datasetcm.corr()

fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(corr3,cmap='coolwarm', vmin=-1, vmax=1)
fig.colorbar(cax)
ticks = np.arange(0,len(datasetcm.columns),1)
ax.set_xticks(ticks)
plt.xticks(rotation=90)
ax.set_yticks(ticks)
ax.set_xticklabels(datasetcm.columns)
ax.set_yticklabels(datasetcm.columns)
plt.show()
</code>```

答:
Filter your correlation matrix on the treshold of 0.5 before plotting. This will return 0 for the correlations lower than 0.5.

Then we can use color mapping to show the rows with 0 as not correlated

```<code>corr3 = datasetcm.corr()
corr3 = corr3 [corr3 > 0.5].fillna(0)

corr3.style.background_gradient(cmap='coolwarm', axis=None).set_precision(2)
</code>```

Title: Use pandas to plot highest correlations

Body:
I have been plotting correlations via heatmaps with the following code. However, there are too many variables. Is it possible to plot the highest correlations ( over .5 and -.5) on a graph?

plt.rcParams['figure.figsize'] = [80,80]
corr3 = datasetcm.corr()

fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(corr3,cmap='coolwarm', vmin=-1, vmax=1)
fig.colorbar(cax)
ticks = np.arange(0,len(datasetcm.columns),1)
ax.set_xticks(ticks)
plt.xticks(rotation=90)
ax.set_yticks(ticks)
ax.set_xticklabels(datasetcm.columns)
ax.set_yticklabels(datasetcm.columns)
plt.show()

Body:
Filter your correlation matrix on the treshold of 0.5 before plotting. This will return 0 for the correlations lower than 0.5.

Then we can use color mapping to show the rows with 0 as not correlated

corr3 = datasetcm.corr()
corr3 = corr3 [corr3 > 0.5].fillna(0)

corr3.style.background_gradient(cmap='coolwarm', axis=None).set_precision(2)


问:
Deploy different versions of web-application
In this hypothetical scenario I have a web-app running on his 1st version, having around 1,000 active users.

I've just finished the 2nd version and would like to test with some users only, what would be the most patterned way to deliver this new version to those clients and have the rest of them still using the 1st?

Considering an application built using Express (Node.js) and deployed to AWS.

答:
Depending on your architecture, the details will vary (single ec2 instance, mutli instances, multiple with load balancer, multiple containers etc), but the general term for what you are looking to do is referred to as a 'blue green' deployment. Google that and you will get lots of hits, and then narrow down the results to one that matches the setup that is close to yours.

Here is one article, for example:

Implementing Blue-Green Deployments with AWS


答:
Use sub query to find max price</p>

```<code>SELECT ProductID, ProductName, QuantityPerUnit
FROM Products
WHERE UnitPrice = (SELECT Max(UnitPrice) FROM Products)
</code>```

Title: SQL query MAX() function

Body:
Use sub query to find max price

SELECT ProductID, ProductName, QuantityPerUnit
FROM Products
WHERE UnitPrice = (SELECT Max(UnitPrice) FROM Products)


问:
How do I avoid time leakage in my KNN model?
I am building a KNN model to predict housing prices. I'll go through my data and my model and then my problem.

Data -

```<code># A tibble: 81,334 x 4
   latitude longitude close_date          close_price
      <dbl>     <dbl> <dttm>                    <dbl>
 1     36.4     -98.7 2014-08-05 06:34:00     147504.
 2     36.6     -97.9 2014-08-12 23:48:00     137401.
 3     36.6     -97.9 2014-08-09 04:00:40     239105.
</code>```

Model -

```<code>library(caret)
training.samples <- data$close_price %>%
  createDataPartition(p = 0.8, list = FALSE)
train.data  <- data[training.samples, ]
test.data <- data[-training.samples, ]

model <- train(
  close_price~ ., data = train.data, method = "knn",
  trControl = trainControl("cv", number = 10),
  preProcess = c("center", "scale"),
  tuneLength = 10
)
</code>```

My problem is time leakage. I am making predictions on a house using other houses that closed afterwards and in the real world I shouldn't have access to that information.

I want to apply a rule to the model that says, for each value y, only use houses that closed before the house for that y. I know I could split my test data and my train data on a certain date, but that doesn't quite do it.

Is it possible to prevent this time leakage, either in caret or other libraries for knn (like class and kknn)?

答:
In caret, createTimeSlices implements a variation of cross-validation adapted to time series (avoiding time leakage by rolling the forecasting origin).
Documentation is here.

In your case, depending on your precise needs, you could use something like this for a proper cross-validation:

```<code>your_data <- your_data %>% arrange(close_date)

tr_ctrl <- createTimeSlices(
  your_data$close_price,
  initialWindow  = 10,
  horizon = 1,
  fixedWindow = FALSE)

model <- train(
  close_price~ ., data = your_data, method = "knn",
  trControl = tr_ctrl,
  preProcess = c("center", "scale"),
  tuneLength = 10
)
</code>```

EDIT:
if you have ties in the dates and want to having deals closed on the same day in the test and train sets, you can fix tr_ctrl before using it in train:

```<code>filter_train <- function(i_tr, i_te) {
  d_tr <- as_date(your_data$close_date[i_tr]) #using package lubridate
  d_te <- as_date(your_data$close_date[i_te])
  tr_is_ok <- d_tr < min(d_te)

  i_tr[tr_is_ok]
}

tr_ctrl$train <- mapply(filter_train, tr_ctrl$train, tr_ctrl$test)
</code>```

Body:
I am building a KNN model to predict housing prices. I'll go through my data and my model and then my problem.

Data -

# A tibble: 81,334 x 4
   latitude longitude close_date          close_price
      <dbl>     <dbl> <dttm>                    <dbl>
 1     36.4     -98.7 2014-08-05 06:34:00     147504.
 2     36.6     -97.9 2014-08-12 23:48:00     137401.
 3     36.6     -97.9 2014-08-09 04:00:40     239105.

Model -

library(caret)
training.samples <- data$close_price %>%
  createDataPartition(p = 0.8, list = FALSE)
train.data  <- data[training.samples, ]
test.data <- data[-training.samples, ]

model <- train(
  close_price~ ., data = train.data, method = "knn",
  trControl = trainControl("cv", number = 10),
  preProcess = c("center", "scale"),
  tuneLength = 10
)

My problem is time leakage. I am making predictions on a house using other houses that closed afterwards and in the real world I shouldn't have access to that information.

I want to apply a rule to the model that says, for each value y, only use houses that closed before the house for that y. I know I could split my test data and my train data on a certain date, but that doesn't quite do it.

Is it possible to prevent this time leakage, either in caret or other libraries for knn (like class and kknn)?

Body:
In caret, createTimeSlices implements a variation of cross-validation adapted to time series (avoiding time leakage by rolling the forecasting origin).
Documentation is here.

In your case, depending on your precise needs, you could use something like this for a proper cross-validation:

your_data <- your_data %>% arrange(close_date)

tr_ctrl <- createTimeSlices(
  your_data$close_price,
  initialWindow  = 10,
  horizon = 1,
  fixedWindow = FALSE)

model <- train(
  close_price~ ., data = your_data, method = "knn",
  trControl = tr_ctrl,
  preProcess = c("center", "scale"),
  tuneLength = 10
)

EDIT:
if you have ties in the dates and want to having deals closed on the same day in the test and train sets, you can fix tr_ctrl before using it in train:

filter_train <- function(i_tr, i_te) {
  d_tr <- as_date(your_data$close_date[i_tr]) #using package lubridate
  d_te <- as_date(your_data$close_date[i_te])
  tr_is_ok <- d_tr < min(d_te)

  i_tr[tr_is_ok]
}

tr_ctrl$train <- mapply(filter_train, tr_ctrl$train, tr_ctrl$test)


问:
JavaScript startsWith using regex & offset
I'm doing some string parsing and would like to use regexes. I am iterating through strings and would like to apply something like "startsWith" using a regex and an offset, returning a match if its found or null if not. In pseudo-javascript :

```<code>function startsWith(string, regex, offset) {
    if (regex_matches_at_offset) {
        return match;
    } else {
        return null;
    }
}
</code>```

A simple and straightforward solution is to first apply substring and then match. But I want something like "startsWith" using a regex.

If it was a string instead of a regex, I'd go with startsWith

```<code>function startsWith(string, other_string, offset) {
    let starts_with=s.startsWith(other_string, offset); // startsWith from position offset onwards, as other_string has fixed length the "match" is also known
    if (starts_with) {
        return other_string; // other_string = match
    } else {
        return null;
    }
}
</code>```

But for regexes, my current solution (for testing purposes only) looks like :

```<code>function startsWith(string, regex, offset) {
    let end_part=s.substring(offset); // Substring, performance issue
    let match=end_part.match(regex); // Match it as we need the match
    if (match.length === 0) {
        return null;
    } else {
        match=match[0]; // Only care about 1st match
    }
    if (end_part.startsWith(match)) { // Check if match already starts at first position
        return match;
    } else {
        return null;
    }
}
</code>```

Which is not very satisfying as there are obvious problems (copying most of the string, performing the regex search twice...

Expected :

Find regex in string starting from given position, not only boolean but also match

High performance (do not copy entire string, for example)

Examples :

```<code>startsWith("Hello world !", /h/i, 0); // "H"
startsWith("Hello world !", /wor?/i, 6); // "wor"
startsWith("Hello world !", /wor?/i, 10); // null
startsWith("Hello world !", /z/i, 0); // null
</code>```

答:
One way is to build an regex based on offset and pattern passed as string

Here initial part of regex uses . to match any character upto offset

Second use passed pattern in captured group to return only desired match

let startsWith = (str, reg, offset) =>{
  let regex = `^.{${0,offset}}(${reg})`
  let final = new RegExp(regex,'i')
  let found = str.match(final)
  console.log(found ? found[1] : found)
}

startsWith("Hello world !", 'h', 0); // "H"
startsWith("Hello world !", 'wor?', 6); // "wor"
startsWith("Hello world !", 'wor?', 10); // null
startsWith("Hello world !", 'z', 0); // null```
</div>
</div>
</p>

<p>As mentioned by @mark we can use source property to if we want regex to be passed as argument to function</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let startsWith = (str, reg, offset) =>{
  let regex = `^.{${0,offset}}(${reg.source})`
  let final = new RegExp(regex,'i')
  let found = str.match(final)
  console.log(found ? found[1] : found)
}

startsWith("Hello world !", /h/i, 0); // "H"
startsWith("Hello world !", /wor?/i, 6); // "wor"
startsWith("Hello world !", /wor?/i, 10); // null
startsWith("Hello world !", /z/i, 0); // null</code>```

Body:
I'm doing some string parsing and would like to use regexes. I am iterating through strings and would like to apply something like "startsWith" using a regex and an offset, returning a match if its found or null if not. In pseudo-javascript :

function startsWith(string, regex, offset) {
    if (regex_matches_at_offset) {
        return match;
    } else {
        return null;
    }
}

A simple and straightforward solution is to first apply substring and then match. But I want something like "startsWith" using a regex.

If it was a string instead of a regex, I'd go with startsWith

function startsWith(string, other_string, offset) {
    let starts_with=s.startsWith(other_string, offset); // startsWith from position offset onwards, as other_string has fixed length the "match" is also known
    if (starts_with) {
        return other_string; // other_string = match
    } else {
        return null;
    }
}

But for regexes, my current solution (for testing purposes only) looks like :

function startsWith(string, regex, offset) {
    let end_part=s.substring(offset); // Substring, performance issue
    let match=end_part.match(regex); // Match it as we need the match
    if (match.length === 0) {
        return null;
    } else {
        match=match[0]; // Only care about 1st match
    }
    if (end_part.startsWith(match)) { // Check if match already starts at first position
        return match;
    } else {
        return null;
    }
}

Which is not very satisfying as there are obvious problems (copying most of the string, performing the regex search twice...

Expected :

Find regex in string starting from given position, not only boolean but also match

High performance (do not copy entire string, for example)

Examples :

startsWith("Hello world !", /h/i, 0); // "H"
startsWith("Hello world !", /wor?/i, 6); // "wor"
startsWith("Hello world !", /wor?/i, 10); // null
startsWith("Hello world !", /z/i, 0); // null

Body:
One way is to build an regex based on offset and pattern passed as string

Here initial part of regex uses . to match any character upto offset

Second use passed pattern in captured group to return only desired match

let startsWith = (str, reg, offset) =>{
  let regex = `^.{${0,offset}}(${reg})`
  let final = new RegExp(regex,'i')
  let found = str.match(final)
  console.log(found ? found[1] : found)
}

startsWith("Hello world !", 'h', 0); // "H"
startsWith("Hello world !", 'wor?', 6); // "wor"
startsWith("Hello world !", 'wor?', 10); // null
startsWith("Hello world !", 'z', 0); // null

As mentioned by @mark we can use source property to if we want regex to be passed as argument to function

let startsWith = (str, reg, offset) =>{
  let regex = `^.{${0,offset}}(${reg.source})`
  let final = new RegExp(regex,'i')
  let found = str.match(final)
  console.log(found ? found[1] : found)
}

startsWith("Hello world !", /h/i, 0); // "H"
startsWith("Hello world !", /wor?/i, 6); // "wor"
startsWith("Hello world !", /wor?/i, 10); // null
startsWith("Hello world !", /z/i, 0); // null


问:
Can Xtext be used for parsing general purpose programming languages?
I'm currently developing a general-purpose agent-based programming language (its syntaxt will be somewhat inspired by Java, and we are also using object in this language).

Since the beginning of the project we were doubtful about the fact of using ANTLR or Xtext. At that time we found out that Xtext was implementing a subset of the feature of ANTLR. So we decided to use ANLTR for our language losing the possibility to have a full-fledged Eclipse editor for free for our language (such a nice features provided by Xtext).

However, as the best of my knowledge, this summer the Xtext project has done a big step forward. Quoting from the link:

What are the limitations of Xtext?

Sven: You can implement almost any kind of programming language or DSL
  with Xtext. There is one exception, that is if you need to use so
  called  'Semantic Predicates' which is a rather complicated thing I
  don't think is worth being explained here. Very few languages really
  need this concept. However the prominent example is C/C++.  We want to
  look into that topic for the next release.

And that is also reinforced in the Xtext documentation:

What is Xtext? No matter if you want to create a small textual domain-specific language (DSL) or you want to implement a full-blown
  general purpose programming language. With Xtext you can create your
  very own languages in a snap. Also if you already have an existing
  language but it lacks decent tool support, you can use Xtext to create
  a sophisticated Eclipse-based development environment providing
  editing experience known from modern Java IDEs in a surprisingly short
  amount of time. We call Xtext a language development framework.

If Xtext has got rid of its past limitations why is it still not possible to find a complex Xtext grammar for the best known programming languages (Java, C#, etc.)?

On the ANTLR website you can find tons of such grammar examples, for what concerns Xtext instead the only sample I was able to find is the one reported in the documentation. So maybe Xtext is still not mature to be used for implementing a general purpose programming language? I'm a bit worried about this... I would not start to re-write the grammar in Xtext for then to recognize that it was not suited for that.

答:
I think nobody implemented Java or C++ because it is a lot of work (even with Xtext) and the existing tools and compilers are excellent.
However, you could have a look at Xbase and Xtend, which is the expression language we ship with Xtext. It is built with Xtext and is quite a good proof for what you can build with Xtext. We have done that in about 4 person months.

I did a couple of screencasts on Xtend:

http://blog.efftinge.de/2011/03/xtend-screencast-part-1-basics.html

http://blog.efftinge.de/2011/03/xtend-screencast-part-2-switch.html

http://blog.efftinge.de/2011/03/xtend-screencast-part-3-rich-strings-ie.html

Note, that you can simply embed Xbase expressions into your language.


问:
Activation Layer is stashing 2 attributes from the tensor

TensorFlow version: tf 1.13.1

  Keras version: 2.2.4

  Python version: 3.7

After debugging, I see that after adding activation layers at various segments of my model, layer drops 2 attributes _keras_history and _keras_shape.

Currently, the model isn't compiling as my architecture has an activation layer at the end applied after computing logits.

code:

```<code>x = keras.activations.relu(x)
ff_layer2 = keras.layers.DepthwiseConv2D(128, strides=(1, 1), depth_multiplier=1, padding='same')(x)
classifier = keras.activations.softmax(ff_layer2)

x = keras.activations.relu(x)
ff_layer2 = keras.layers.DepthwiseConv2D(128, strides=(1, 1), depth_multiplier=1, padding='same')(x)
classifier = keras.activations.softmax(ff_layer2)
</code>```

The error:

```<code>File "/home/perennial_qube/.conda/envs/fast-scnn/lib/python3.7/site-packages/keras/engine/network.py", line 188, in _init_graph_network
    'Found: ' + str(x))
ValueError: Output tensors to a Model must be the output of a Keras `Layer` (thus holding past layer metadata). Found: Tensor("truediv:0", shape=(?, 2048, 1024, 128), dtype=float32)
</code>```

答:
Functions in keras.activations.* are activation functions, and not Keras layers. The architecture of models in Keras should only be built with layers. So you need to use their equivalent activation layers:

```<code>from keras.layers import Softmax, ReLU

x = ReLU()(x)
# ...
classifier = Softmax()(ff_layer2)
</code>```

Alternatively, you can use the activation argument of layers and pass the name or activation function directly. For example:

```<code>... = DepthwiseConv2D(..., activation='softmax')
# or:
... = DepthwiseConv2D(..., activation=keras.activations.softmax)
</code>```

As another alternative you can use the Activation layer and pass the name of activation function:

```<code>from keras.layers import Activation

# ...
classifier = Activation('softmax')(ff_layer2)
</code>```

The first solution, compared to the two other solutions, has this advantage that you can easily modify the behavior of the activation function by providing custom arguments. For example, by default the softmax activation is computed over the last axis, but if needed you can change this as follow:

```<code>from keras.layers import Softmax

classifier = Softmax(axis=my_desired_axis)(ff_layer2)
</code>```

Body:
TensorFlow version: tf 1.13.1

  Keras version: 2.2.4

  Python version: 3.7

After debugging, I see that after adding activation layers at various segments of my model, layer drops 2 attributes _keras_history and _keras_shape.

Currently, the model isn't compiling as my architecture has an activation layer at the end applied after computing logits.

code:

x = keras.activations.relu(x)
ff_layer2 = keras.layers.DepthwiseConv2D(128, strides=(1, 1), depth_multiplier=1, padding='same')(x)
classifier = keras.activations.softmax(ff_layer2)

x = keras.activations.relu(x)
ff_layer2 = keras.layers.DepthwiseConv2D(128, strides=(1, 1), depth_multiplier=1, padding='same')(x)
classifier = keras.activations.softmax(ff_layer2)

The error:

File "/home/perennial_qube/.conda/envs/fast-scnn/lib/python3.7/site-packages/keras/engine/network.py", line 188, in _init_graph_network
    'Found: ' + str(x))
ValueError: Output tensors to a Model must be the output of a Keras `Layer` (thus holding past layer metadata). Found: Tensor("truediv:0", shape=(?, 2048, 1024, 128), dtype=float32)

Body:
Functions in keras.activations.* are activation functions, and not Keras layers. The architecture of models in Keras should only be built with layers. So you need to use their equivalent activation layers:

from keras.layers import Softmax, ReLU

x = ReLU()(x)
# ...
classifier = Softmax()(ff_layer2)

Alternatively, you can use the activation argument of layers and pass the name or activation function directly. For example:

... = DepthwiseConv2D(..., activation='softmax')
# or:
... = DepthwiseConv2D(..., activation=keras.activations.softmax)

As another alternative you can use the Activation layer and pass the name of activation function:

from keras.layers import Activation

# ...
classifier = Activation('softmax')(ff_layer2)

The first solution, compared to the two other solutions, has this advantage that you can easily modify the behavior of the activation function by providing custom arguments. For example, by default the softmax activation is computed over the last axis, but if needed you can change this as follow:

from keras.layers import Softmax

classifier = Softmax(axis=my_desired_axis)(ff_layer2)


问:
How can I set a price for custom text?
Is there a way to add price if the client add the custom text (the one inside the Options section when you add the product) in a product? or have I to add it by product combinations (adding a lot of combinations)?

With the input radio I can't control what the user will do and I can't set it as "required" because it must be a free choice.

```<code> {block name='product_customization_form'}
    <form method="post" action="{$product.url}" enctype="multipart/form-data">
      <ul class="clearfix">
        {foreach from=$customizations.fields item="field"}
          <li class="product-customization-item">
            <label> {$field.label}</label>
            {if $field.type == 'text'}
              <textarea placeholder="{l s='Your message here' d='Shop.Forms.Help'}" class="product-message" maxlength="250" {if $field.required} required {/if} name="{$field.input_name}"></textarea>
              <small class="float-xs-right">{l s='250 char. max' d='Shop.Forms.Help'}</small>
              {if $field.text !== ''}
                  <h6 class="customization-message">{l s='Your customization:' d='Shop.Theme.Catalog'}
                      <label>{$field.text}</label>
                  </h6>
              {/if}

          </li>
        {/foreach}
      </ul>
      <div class="clearfix">
        <button class="btn btn-primary float-xs-right" type="submit" name="submitCustomizedData">{l s='Save Customization' d='Shop.Theme.Actions'}</button>
      </div>
    </form>
  {/block}
</code>```

答:
The best way to achieve this would be to have two product combinations:

With custom text (+$0)

Without custom text (+$1.00)

Next, add some custom Javascript code to your product page (the proper way would be via a module) that would do the following:

Check if the customization textarea element is present on the page

Check if it is empty or not

If not, force the combination ID to the right ID (the "with customization" version)

That's it.

That way, the buyer won't have to select any option, they just have to fill a custom text if they would like to and the price will adjust automatically in their shopping cart.

I hope this helps!

Title: How can I set a price for custom text?

Body:
Is there a way to add price if the client add the custom text (the one inside the Options section when you add the product) in a product? or have I to add it by product combinations (adding a lot of combinations)?

With the input radio I can't control what the user will do and I can't set it as "required" because it must be a free choice.

 {block name='product_customization_form'}
    <form method="post" action="{$product.url}" enctype="multipart/form-data">

        {foreach from=$customizations.fields item="field"}

             {$field.label}
            {if $field.type == 'text'}
              <textarea placeholder="{l s='Your message here' d='Shop.Forms.Help'}" class="product-message" maxlength="250" {if $field.required} required {/if} name="{$field.input_name}"></textarea>
              {l s='250 char. max' d='Shop.Forms.Help'}
              {if $field.text !== ''}

{l s='Your customization:' d='Shop.Theme.Catalog'}
                      {$field.text}

              {/if}

        {/foreach}

        <button class="btn btn-primary float-xs-right" type="submit" name="submitCustomizedData">{l s='Save Customization' d='Shop.Theme.Actions'}</button>

    </form>
  {/block}


问:
How to extract string from a long string
I'm struggling to extract strings from a long string which is a row of a csv file with python or R. The long string is  </p>

```<code>"Zhao, Sihai@Univ Penn::Cai, T. Tony@Univ Penn::Li, Hongzhe@Univ Penn"
</code>```

<p>And the results should be  </p>

```<code>"Zhao, Sihai" "Cai, T. Tony" "Li, Hongzhe"
</code>```

答:
Python:

```<code>tmp_str = "Zhao, Sihai@Univ Penn::Cai, T. Tony@Univ Penn::Li, Hongzhe@Univ Penn"
names = [s.split("@")[0] for s in tmp_str.split("::")]
print(names)
</code>```

And the output is
['Zhao, Sihai', 'Cai, T. Tony', 'Li, Hongzhe']

Body:
I'm struggling to extract strings from a long string which is a row of a csv file with python or R. The long string is

"Zhao, Sihai@Univ Penn::Cai, T. Tony@Univ Penn::Li, Hongzhe@Univ Penn"

And the results should be

"Zhao, Sihai" "Cai, T. Tony" "Li, Hongzhe"

Body:
Python:

tmp_str = "Zhao, Sihai@Univ Penn::Cai, T. Tony@Univ Penn::Li, Hongzhe@Univ Penn"
names = [s.split("@")[0] for s in tmp_str.split("::")]
print(names)

And the output is
['Zhao, Sihai', 'Cai, T. Tony', 'Li, Hongzhe']


问:
How to enumerate a range of numbers starting at 1
I am using Python 2.5, I want an enumeration like so (starting at 1 instead of 0):

```<code>[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]
</code>```

I know in Python 2.6 you can do: h = enumerate(range(2000, 2005), 1) to give the above result but in python2.5 you cannot...

Using Python 2.5:

```<code>>>> h = enumerate(range(2000, 2005))
>>> [x for x in h]
[(0, 2000), (1, 2001), (2, 2002), (3, 2003), (4, 2004)]
</code>```

Does anyone know a way to get that desired result in Python 2.5?

答:
I don't know how these posts could possibly be made more complicated then the following:</p>

```<code># Just pass the start argument to enumerate ...
for i,word in enumerate(allWords, 1):
    word2idx[word]=i
    idx2word[i]=word
</code>```

Body:
I am using Python 2.5, I want an enumeration like so (starting at 1 instead of 0):

[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

I know in Python 2.6 you can do: h = enumerate(range(2000, 2005), 1) to give the above result but in python2.5 you cannot...

Using Python 2.5:

>>> h = enumerate(range(2000, 2005))
>>> [x for x in h]
[(0, 2000), (1, 2001), (2, 2002), (3, 2003), (4, 2004)]

Does anyone know a way to get that desired result in Python 2.5?

Body:
I don't know how these posts could possibly be made more complicated then the following:

# Just pass the start argument to enumerate ...
for i,word in enumerate(allWords, 1):
    word2idx[word]=i
    idx2word[i]=word


答:
Does it enough for you ?

Input:

```<code>str = "Zhao, Sihai@Univ Penn::Cai, T. Tony@Univ Penn::Li, Hongzhe@Univ Penn"
parsed = x.replace('@Univ Penn','').split("::")
print(parsed)
</code>```

Output:

```<code>['Zhao, Sihai', 'Cai, T. Tony', 'Li, Hongzhe']
</code>```

Title: How to extract string from a long string

Body:
Does it enough for you ?

Input:

str = "Zhao, Sihai@Univ Penn::Cai, T. Tony@Univ Penn::Li, Hongzhe@Univ Penn"
parsed = x.replace('@Univ Penn','').split("::")
print(parsed)

Output:

['Zhao, Sihai', 'Cai, T. Tony', 'Li, Hongzhe']


问:
Why is heap slower than sort for K Closest Points to Origin?
The coding task is here

The heap solution:

```<code>import heapq
class Solution:
    def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
        return heapq.nsmallest(K, points, key = lambda P: P[0]**2 + P[1]**2)
</code>```

The sort solution:

```<code>class Solution(object):
    def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
        points.sort(key = lambda P: P[0]**2 + P[1]**2)
        return points[:K]
</code>```

According to the explanation here, Python's heapq.nsmallest is O(n  log(t)), and Python List.sort() is O(n log(n)). However, my submission results show that sort is faster than heapq. How did this happen? Theoretically, it's the contrary, isn't it?

答:
Let's pick the definition of Big-O notation from the Wikipedia:

Big O notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity.

...

In computer science, big O notation is used to classify algorithms according to how their running time or space requirements grow as the input size grows.

So Big-O is similar to:

So when you are comparing two algorithms on the small ranges/numbers, you can't strongly rely on Big-O. Let's analyze the example:

We have two algorithms: the first is O(1) and works for exactly 10000 ticks and the second is O(n^2). So in the range 1~100 the second will be faster than the first (100^2 == 10000 so (x<100)^2 < 10000). But from the 100 the second algorithm will be slower than the first.

The similar behaviour is in your functions. I timed them with various input lengths and constructed timing plots. Here is timings for your functions on big numbers (yellow is sort, blue is heap):

You can see that sort is consuming more time than heap, and the time is raising faster than heap's. But if we will look closer on lower range:

We will see that on small range sort is faster than heap! Looks like heap has "default" time consumation. So it is not wrong that algorithm with worse Big-O works faster than algorithm with better Big-O. It just means that their range usage is too small for better algorithm to be faster than the worse.

Here is the timing code for the first plot:

```<code>import timeit
import matplotlib.pyplot as plt

s = """
import heapq
def k_heap(points, K):
    return heapq.nsmallest(K, points, key = lambda P: P[0]**2 + P[1]**2)

def k_sort(points, K):
    points.sort(key = lambda P: P[0]**2 + P[1]**2)
    return points[:K]
"""

random.seed(1)
points = [(random.random(), random.random()) for _ in range(1000000)]
r = list(range(11, 500000, 50000))
heap_times = []
sort_times = []
for i in r:
    heap_times.append(timeit.timeit('k_heap({}, 10)'.format(points[:i]), setup=s, number=1))
    sort_times.append(timeit.timeit('k_sort({}, 10)'.format(points[:i]), setup=s, number=1))

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
#plt.plot(left, 0, marker='.')
plt.plot(r, heap_times, marker='o')
plt.plot(r, sort_times, marker='D')
plt.show()
</code>```

For second plot, replace:

```<code>r = list(range(11, 500000, 50000))  -> r = list(range(11, 200))
plt.plot(r, heap_times, marker='o') -> plt.plot(r, heap_times)
plt.plot(r, sort_times, marker='D') -> plt.plot(r, sort_times)
</code>```

Body:
The coding task is here

The heap solution:

import heapq
class Solution:
    def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
        return heapq.nsmallest(K, points, key = lambda P: P[0]**2 + P[1]**2)

The sort solution:

class Solution(object):
    def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
        points.sort(key = lambda P: P[0]**2 + P[1]**2)
        return points[:K]

According to the explanation here, Python's heapq.nsmallest is O(n  log(t)), and Python List.sort() is O(n log(n)). However, my submission results show that sort is faster than heapq. How did this happen? Theoretically, it's the contrary, isn't it?

Body:
Let's pick the definition of Big-O notation from the Wikipedia:

Big O notation is a mathematical notation that describes the limiting behavior of a function when the argument tends towards a particular value or infinity.

...

In computer science, big O notation is used to classify algorithms according to how their running time or space requirements grow as the input size grows.

So Big-O is similar to:

So when you are comparing two algorithms on the small ranges/numbers, you can't strongly rely on Big-O. Let's analyze the example:

We have two algorithms: the first is O(1) and works for exactly 10000 ticks and the second is O(n^2). So in the range 1~100 the second will be faster than the first (100^2 == 10000 so (x<100)^2 < 10000). But from the 100 the second algorithm will be slower than the first.

The similar behaviour is in your functions. I timed them with various input lengths and constructed timing plots. Here is timings for your functions on big numbers (yellow is sort, blue is heap):

You can see that sort is consuming more time than heap, and the time is raising faster than heap's. But if we will look closer on lower range:

We will see that on small range sort is faster than heap! Looks like heap has "default" time consumation. So it is not wrong that algorithm with worse Big-O works faster than algorithm with better Big-O. It just means that their range usage is too small for better algorithm to be faster than the worse.

Here is the timing code for the first plot:

import timeit
import matplotlib.pyplot as plt

s = """
import heapq
def k_heap(points, K):
    return heapq.nsmallest(K, points, key = lambda P: P[0]**2 + P[1]**2)

def k_sort(points, K):
    points.sort(key = lambda P: P[0]**2 + P[1]**2)
    return points[:K]
"""

random.seed(1)
points = [(random.random(), random.random()) for _ in range(1000000)]
r = list(range(11, 500000, 50000))
heap_times = []
sort_times = []
for i in r:
    heap_times.append(timeit.timeit('k_heap({}, 10)'.format(points[:i]), setup=s, number=1))
    sort_times.append(timeit.timeit('k_sort({}, 10)'.format(points[:i]), setup=s, number=1))

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
#plt.plot(left, 0, marker='.')
plt.plot(r, heap_times, marker='o')
plt.plot(r, sort_times, marker='D')
plt.show()

For second plot, replace:

r = list(range(11, 500000, 50000))  -> r = list(range(11, 200))
plt.plot(r, heap_times, marker='o') -> plt.plot(r, heap_times)
plt.plot(r, sort_times, marker='D') -> plt.plot(r, sort_times)


问:
POST API response blocked by CORS policy - React and Django Rest Framwork
I have created a backend server in Django with Django Rest Framework, and a React frontend. My front retrieves data from the back through APIs. Each app is on a different subdomain of the same domain. I use
Cloudflare to manage DNS and for SSL / security.

I have had no problem with GET calls. For POST calls, I send the POST data to the server through a form, and I know it works as there is a change to the database (record created in this instance). However, I have implemented a 'retry until' function using axios and polly-js. This method waits until it receives a 201 CREATED response, otherwise retries.

My problem is that when I submit the form on React, the POST is indeed received and processed by my backend server, but the response is blocked. So after 10-15 seconds, I receive an error message through the console and my 'retry until' method sends another POST request. The response of this second one is not blocked by Chrome, and I receive the 201 status. But the overall effect is that I have now 2 identical records in the database because the first call did not 'receive' the response and retried.

The error in the console I get is:

```<code>Access to XMLHttpRequest at 'https://subdomain.domain.io/' from origin 'https://api.domain.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

What I have already done and has not worked:

I don' think it's a backend problem as the POST goes through and the record created. But I have whitelisted all CORS origins in Django

I have added the header 'Access-Control-Allow-Origin': '*' to my POST request through axios

I have manually added the same 'Access-Control-Allow-Origin': '*' header from my Django DRF response.

Both request that I send (first one through form submission, second one through automatic retry) are identical (seen through Chrome network tab):

```<code>Accept: application/json, text/plain, */*
Content-Type: application/json;charset=UTF-8
Origin: https://subdomain.domain.io
Referer: https://subdomain.domain.io/path
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
</code>```

My POST and retry method:

```<code>const postData = (url, data, headers) => {

    headers['Access-Control-Allow-Origin'] = "*"

    return polly()
      .waitAndRetry([100, 200, 400, 1000])
      .executeForPromise(async () => {
        const rsp = await axios.post(url, data, headers);

        if (rsp.status < 210) {

          return rsp.data;

        }

        return Promise.reject(rsp);
      });
  };
</code>```

The response I get when the second try succeeds:

```<code>access-control-allow-origin: *
allow: GET, POST, HEAD, OPTIONS
cf-ray: 4dd7cbccce256948-CDG
content-length: 364
content-type: application/json
date: Mon, 27 May 2019 11:54:47 GMT
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
status: 201
strict-transport-security: max-age=2592000; includeSubDomains; preload
vary: Accept, Origin
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
</code>```

For reference, the CORS settings in Django

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django_otp.middleware.OTPMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True

CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'access-control-allow-origin'
)
```

<p><strong>EDIT</strong> </p>

<p>Firefox shows me the response for the 504 GATEWAY TIMEOUT of the first POST request: </p>

```cf-ray: 4dd82ac15f42cd97-CDG
content-type: text/html; charset=UTF-8
date: Mon, 27 May 2019 13:00:36 GMT
expect-ct: max-age=604800, report-uri="ht….com/cdn-cgi/beacon/expect-ct"
expires: Thu, 01 Jan 1970 00:00:01 GMT
pragma: no-cache
server: cloudflare
set-cookie: __cfduid=d0a3a9ee872171ada14cb…n=.wisly.io; HttpOnly; Secure
set-cookie: cf_use_ob=0; path=/; expires=Mon, 27-May-19 13:01:06 GMT
strict-transport-security: max-age=2592000; includeSubDomains; preload
x-content-type-options: nosniff
X-Firefox-Spdy: h2
```

The Access-Control-Allow-Origin is missing, but it is part of my backend code. Could anything be happening with Cloudflare?

The expected result would be that, when I POST through the form, receive the 201 back (which would be accepted and read by Chrome) so that I can

Show the user the form has been correctly saved to the database

Not retry the POST, resulting in dual entry.

Thank you!

答: Check out this lib. https://pypi.org/project/django-cors-headers. It helped me to solve the same problem with React.</p>

Body:
I have created a backend server in Django with Django Rest Framework, and a React frontend. My front retrieves data from the back through APIs. Each app is on a different subdomain of the same domain. I use
Cloudflare to manage DNS and for SSL / security.

I have had no problem with GET calls. For POST calls, I send the POST data to the server through a form, and I know it works as there is a change to the database (record created in this instance). However, I have implemented a 'retry until' function using axios and polly-js. This method waits until it receives a 201 CREATED response, otherwise retries.

My problem is that when I submit the form on React, the POST is indeed received and processed by my backend server, but the response is blocked. So after 10-15 seconds, I receive an error message through the console and my 'retry until' method sends another POST request. The response of this second one is not blocked by Chrome, and I receive the 201 status. But the overall effect is that I have now 2 identical records in the database because the first call did not 'receive' the response and retried.

The error in the console I get is:

Access to XMLHttpRequest at 'https://subdomain.domain.io/' from origin 'https://api.domain.io' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

What I have already done and has not worked:

I don' think it's a backend problem as the POST goes through and the record created. But I have whitelisted all CORS origins in Django

I have added the header 'Access-Control-Allow-Origin': '*' to my POST request through axios

I have manually added the same 'Access-Control-Allow-Origin': '*' header from my Django DRF response.

Both request that I send (first one through form submission, second one through automatic retry) are identical (seen through Chrome network tab):

Accept: application/json, text/plain, */*
Content-Type: application/json;charset=UTF-8
Origin: https://subdomain.domain.io
Referer: https://subdomain.domain.io/path
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36

My POST and retry method:

const postData = (url, data, headers) => {

    headers['Access-Control-Allow-Origin'] = "*"

    return polly()
      .waitAndRetry([100, 200, 400, 1000])
      .executeForPromise(async () => {
        const rsp = await axios.post(url, data, headers);

        if (rsp.status < 210) {

          return rsp.data;

        }

        return Promise.reject(rsp);
      });
  };

The response I get when the second try succeeds:

access-control-allow-origin: *
allow: GET, POST, HEAD, OPTIONS
cf-ray: 4dd7cbccce256948-CDG
content-length: 364
content-type: application/json
date: Mon, 27 May 2019 11:54:47 GMT
expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
server: cloudflare
status: 201
strict-transport-security: max-age=2592000; includeSubDomains; preload
vary: Accept, Origin
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN

For reference, the CORS settings in Django

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django_otp.middleware.OTPMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True

CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'access-control-allow-origin'
)

EDIT

Firefox shows me the response for the 504 GATEWAY TIMEOUT of the first POST request:

cf-ray: 4dd82ac15f42cd97-CDG
content-type: text/html; charset=UTF-8
date: Mon, 27 May 2019 13:00:36 GMT
expect-ct: max-age=604800, report-uri="ht….com/cdn-cgi/beacon/expect-ct"
expires: Thu, 01 Jan 1970 00:00:01 GMT
pragma: no-cache
server: cloudflare
set-cookie: __cfduid=d0a3a9ee872171ada14cb…n=.wisly.io; HttpOnly; Secure
set-cookie: cf_use_ob=0; path=/; expires=Mon, 27-May-19 13:01:06 GMT
strict-transport-security: max-age=2592000; includeSubDomains; preload
x-content-type-options: nosniff
X-Firefox-Spdy: h2

The Access-Control-Allow-Origin is missing, but it is part of my backend code. Could anything be happening with Cloudflare?

The expected result would be that, when I POST through the form, receive the 201 back (which would be accepted and read by Chrome) so that I can

Show the user the form has been correctly saved to the database

Not retry the POST, resulting in dual entry.

Thank you!


问:
How to use nested JSON in schema
Trying to setup a nested schema as follows. I want be able to reject the schema if bb.c is present when aa.a is present.

I've tried without as well as xor

```<code>{
  Joi.object().keys({
    aa: Joi.object().keys({
      a: Joi.string(),
      b: Joi.string()
    }).unknown(true).with("a", "b"),
    bb: Joi.object().keys({
      c: Joi.string()
    }).unknown(true)
  }).xor( "aa.a" , ["bb.c"])
}
</code>```

With the below object xor fails with ValidationError: "value" must contain at least one of [aa.a, bb.c] yet aa.a exists in the supplied values

```<code>{
  "aa": {
       "a": "fg",
       "b": "fg"
 },
  "bb": {
        "c": "l"
   }
}
</code>```

If I try

```<code>.without( "aa.a" , ["bb.c"])
</code>```

then the schema passes although in my mind it should not pass as without should fail when bb.c is present along with aa.a

Is it because the two things are nested in other objects perhaps?

Can we not specify deeply linked stuff like this?

Thanks in advance

答:
You can to use Joi.when() and create a schema like this:

```<code>Joi.object({
    aa: Joi.object().keys({
        a: Joi.string(),
        b: Joi.string()
    }).unknown(true).with('a', 'b'),
    bb: Joi.object().keys({
        c: Joi.string()
    }).unknown(true)
        .when('aa.a', {
            is: Joi.exist(),
            then: Joi.object({ c: Joi.forbidden() })
        })
});
</code>```

Basically what this does is that if aa.a is present then the bb.c is not allowed and the schema will fail it's validation. With this schema your example will fail as you expect.

Title: How to use nested JSON in schema

Body:
Trying to setup a nested schema as follows. I want be able to reject the schema if bb.c is present when aa.a is present.

I've tried without as well as xor

{
  Joi.object().keys({
    aa: Joi.object().keys({
      a: Joi.string(),
      b: Joi.string()
    }).unknown(true).with("a", "b"),
    bb: Joi.object().keys({
      c: Joi.string()
    }).unknown(true)
  }).xor( "aa.a" , ["bb.c"])
}

With the below object xor fails with ValidationError: "value" must contain at least one of [aa.a, bb.c] yet aa.a exists in the supplied values

{
  "aa": {
       "a": "fg",
       "b": "fg"
 },
  "bb": {
        "c": "l"
   }
}

If I try

.without( "aa.a" , ["bb.c"])

then the schema passes although in my mind it should not pass as without should fail when bb.c is present along with aa.a

Is it because the two things are nested in other objects perhaps?

Can we not specify deeply linked stuff like this?

Thanks in advance

Body:
You can to use Joi.when() and create a schema like this:

Joi.object({
    aa: Joi.object().keys({
        a: Joi.string(),
        b: Joi.string()
    }).unknown(true).with('a', 'b'),
    bb: Joi.object().keys({
        c: Joi.string()
    }).unknown(true)
        .when('aa.a', {
            is: Joi.exist(),
            then: Joi.object({ c: Joi.forbidden() })
        })
});

Basically what this does is that if aa.a is present then the bb.c is not allowed and the schema will fail it's validation. With this schema your example will fail as you expect.


问:
Closure and nested lambdas in C++0x
Using C++0x, how do I capture a variable when I have a lambda within a lambda?  For example:</p>

```<code>std::vector<int> c1;
int v = 10; <--- I want to capture this variable

std::for_each(
    c1.begin(),
    c1.end(),
    [v](int num) <--- This is fine...
    {
        std::vector<int> c2;

        std::for_each(
            c2.begin(),
            c2.end(),
            [v](int num) <--- error on this line, how do I recapture v?
            {
                // Do something
            });
    });
</code>```

答:
In the inner lambda you should have(assuming you want to pass the variable by reference):</p>

```<code>[&v](int num)->void{

  int a =v;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Closure and nested lambdas in C++0x

Body:
Using C++0x, how do I capture a variable when I have a lambda within a lambda?  For example:

std::vector<int> c1;
int v = 10; <--- I want to capture this variable

std::for_each(
    c1.begin(),
    c1.end(),
    [v](int num) <--- This is fine...
    {
        std::vector<int> c2;

        std::for_each(
            c2.begin(),
            c2.end(),
            [v](int num) <--- error on this line, how do I recapture v?
            {
                // Do something
            });
    });

Body:
In the inner lambda you should have(assuming you want to pass the variable by reference):

[&v](int num)->void{

  int a =v;
}


问:
What is the benefit of classes in a short program like this
I'm trying to understand the purpose of classes. I've made a single program were i have two employees and i want to print all information about those two employes. However i wanted to do that using classes but i dont know if i should do that because my program is too short. Is there any benefit of creating classes using a simple program like the one i did? And if there are benefits what should be the structure of a given class for that program?

```<code>class employee:
  pass

emp1=employee()
emp2=employee()

#information for employee 1

emp1.firstname='Luís'
emp1.lastname='Lopes'
emp1.height='176' #mesured in cm
emp1.weight='80' #mesured in kg
emp1.email='luislopes28@hotmail.com'
emp1.feupgrade=12 # in a scale from 0 to 20

#information for employee2
emp2.firstname='Daniel'
emp2.lastname='Pinhel'
emp2.height='166' #mesured in cm
emp2.weight='63' #mesured in kg
emp2.email='danielpinhell@gmail.com'
emp2.feupgrade=13 # in a scale from 0 to 20

print(emp1.firstname,emp1.lastname,emp1.height,emp1.weight,emp1.email,emp1.feupgrade)

print(emp2.firstname,emp2.lastname,emp2.height,emp2.weight,emp2.email,emp2.feupgrade)
</code>```

I expect to have a code much more simple and easier to understand by using classes definitions

答:
Generally we use class when we have too much objects to create; in this case we can use dictionary for exemple    </p>

```<code>d={ "emp1":['Luís','Lopes','176','80','luislopes28@hotmail.com',12 ],"emp2":['Daniel','Pinhel','166','63','danielpinhell@gmail.com',13]}
</code>```

<p>but here you should put the attributes in order and you can't call them by name as you do with class </p>

Body:
I'm trying to understand the purpose of classes. I've made a single program were i have two employees and i want to print all information about those two employes. However i wanted to do that using classes but i dont know if i should do that because my program is too short. Is there any benefit of creating classes using a simple program like the one i did? And if there are benefits what should be the structure of a given class for that program?

class employee:
  pass

emp1=employee()
emp2=employee()

#information for employee 1

emp1.firstname='Luís'
emp1.lastname='Lopes'
emp1.height='176' #mesured in cm
emp1.weight='80' #mesured in kg
emp1.email='luislopes28@hotmail.com'
emp1.feupgrade=12 # in a scale from 0 to 20

#information for employee2
emp2.firstname='Daniel'
emp2.lastname='Pinhel'
emp2.height='166' #mesured in cm
emp2.weight='63' #mesured in kg
emp2.email='danielpinhell@gmail.com'
emp2.feupgrade=13 # in a scale from 0 to 20

print(emp1.firstname,emp1.lastname,emp1.height,emp1.weight,emp1.email,emp1.feupgrade)

print(emp2.firstname,emp2.lastname,emp2.height,emp2.weight,emp2.email,emp2.feupgrade)

I expect to have a code much more simple and easier to understand by using classes definitions

Body:
Generally we use class when we have too much objects to create; in this case we can use dictionary for exemple

d={ "emp1":['Luís','Lopes','176','80','luislopes28@hotmail.com',12 ],"emp2":['Daniel','Pinhel','166','63','danielpinhell@gmail.com',13]}

but here you should put the attributes in order and you can't call them by name as you do with class


问:
Send a json on a post request with HttpClient and C#
I have a problem with this code, my goal is to send a modification via an API so I'm doing a request over HttpClient.

```<code>using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

public class patchticket
{
   public string patch(string ticketid)
   {

       using (var httpClient = new HttpClient())
       {
           using (var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://desk.zoho.com/api/v1/tickets/"+ticketid))
           {
               request.Headers.TryAddWithoutValidation("Authorization", "6af7d2d213a3ba5e9bc64b80e02b000");
               request.Headers.TryAddWithoutValidation("OrgId", "671437200");

               request.Content = new StringContent("{\"priority\" : \"High\"}", Encoding.UTF8, "application/x-www-form-urlencoded");

               var response =  httpClient.SendAsync(request);
           return response

           }
       }

   }
}
</code>```

The result is that I don't have any error, but changes doesn't take effect.

The credentials are okay, I have tested it with curl with the same parameters and it works great.

答:
It looks like you want to post a json in the request. Try to define the right content-type that is application/json. For sample:

```<code>request.Content = new StringContent("{\"priority\" : \"High\"}",
                                    Encoding.UTF8,
                                    "application/json");
</code>```

Since your method returns a string it can be a a non-async method. The method SendAsync is async and you have to wait the request finished. You could try to call Result after the request. For sample:

```<code>var response =  httpClient.SendAsync(request).Result;
return response.Content; // string content
</code>```

And you will get an object of HttpResponseMessage. There are a lot of useful information about the response on it.

Body:
I have a problem with this code, my goal is to send a modification via an API so I'm doing a request over HttpClient.

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;

public class patchticket
{
   public string patch(string ticketid)
   {

       using (var httpClient = new HttpClient())
       {
           using (var request = new HttpRequestMessage(new HttpMethod("PATCH"), "https://desk.zoho.com/api/v1/tickets/"+ticketid))
           {
               request.Headers.TryAddWithoutValidation("Authorization", "6af7d2d213a3ba5e9bc64b80e02b000");
               request.Headers.TryAddWithoutValidation("OrgId", "671437200");

               request.Content = new StringContent("{\"priority\" : \"High\"}", Encoding.UTF8, "application/x-www-form-urlencoded");

               var response =  httpClient.SendAsync(request);
           return response

           }
       }

   }
}

The result is that I don't have any error, but changes doesn't take effect.

The credentials are okay, I have tested it with curl with the same parameters and it works great.

Body:
It looks like you want to post a json in the request. Try to define the right content-type that is application/json. For sample:

request.Content = new StringContent("{\"priority\" : \"High\"}",
                                    Encoding.UTF8,
                                    "application/json");

Since your method returns a string it can be a a non-async method. The method SendAsync is async and you have to wait the request finished. You could try to call Result after the request. For sample:

var response =  httpClient.SendAsync(request).Result;
return response.Content; // string content

And you will get an object of HttpResponseMessage. There are a lot of useful information about the response on it.


问:
Display IP address on page with HTML
I am just starting HTML so the mistake I am currently making is probably something really obvious. I found this code that should display the user's IP address on the page, but it doesn't work. Why is this?</p>

```<code><html>
<head>
    <title>Palpable Coral</title>
</head>
<body>
Your IP address is: <? echo $_SERVER["REMOTE_ADDR"]; ?>
</body>
</html>
</code>```

答:
i think this link will help you
Get the client IP address using PHP

or use php like this

< ? php echo $_SERVER['REMOTE_ADDR'] ? >

Title: Display IP address on page with HTML

Body:
I am just starting HTML so the mistake I am currently making is probably something really obvious. I found this code that should display the user's IP address on the page, but it doesn't work. Why is this?

    <title>Palpable Coral</title>

Your IP address is: <? echo $_SERVER["REMOTE_ADDR"]; ?>


问:
Deploy a GPU intensive Cloud Run service on GKE
I have a application which is GPU intensive. I have tried deploying this on GKE cluster which is GPU enabled and that went well. Now I want to run my application as a Cloud run service on GKE, I did not find any option for specifying GPU's while creating a Cloud run service. Can anyone please help me out. TIA

I was following this article
https://cloud.google.com/run/docs/gke/setup

答: Cloud Run on Kubernetes does not support GPUs.</p>


问:
How to use ngFor with two variables?
Here is my HTML code:

```<code><ng-containte *ngFor="let item of array"; let j = item>

<ng-containte *ngFor="let item of array"; let i = index>

<input (ngModelChange) = "fun(value,2,item)" >
</code>```

with following javascript:

```<code>fun(value:string, index:number, item:number){
 do something...
}
</code>```

How to use one ngFor to control "i" and "j"
so that it won't loop 2 times?

答:
Just use nested ng-container:

```<code><ng-container *ngFor="let item of array"; let j = index>
  <ng-container *ngFor="let item of array"; let i = index>
    <input (ngModelChange) = "fun(value,i,j)" >
  </ng-container>
</ng-container>
</code>```

If you really want to use item and it's not a typo in your post, no need for a duplication:

```<code><ng-container *ngFor="let item of array">
  <ng-container *ngFor="let item2 of array"; let i = index>
    <input (ngModelChange) = "fun(value,i,item)" >
  </ng-container>
</ng-container>
</code>```

Title: How to use ngFor with two variables?

Body:
Here is my HTML code:

<ng-containte *ngFor="let item of array"; let j = item>

<ng-containte *ngFor="let item of array"; let i = index>

<input (ngModelChange) = "fun(value,2,item)" >

with following javascript:

fun(value:string, index:number, item:number){
 do something...
}

How to use one ngFor to control "i" and "j"
so that it won't loop 2 times?

Body:
Just use nested ng-container:

<ng-container *ngFor="let item of array"; let j = index>
  <ng-container *ngFor="let item of array"; let i = index>
    <input (ngModelChange) = "fun(value,i,j)" >
  </ng-container>
</ng-container>

If you really want to use item and it's not a typo in your post, no need for a duplication:

<ng-container *ngFor="let item of array">
  <ng-container *ngFor="let item2 of array"; let i = index>
    <input (ngModelChange) = "fun(value,i,item)" >
  </ng-container>
</ng-container>


问:
react-ga: Before executing "ReactGA.pageview" or "ReactGA.event", every time do I need to run "ReactGA.initialize"
Software Stack: React

I am trying to get my website analytics, for this, I am using react-ga library. I set up the code, but I have confusion, do I need to run ReactGA.initialize every time before executing the command ReactGA.pageview or ReactGA.event.
Problem is, I am not getting the google analytics data.

Currently, I am setting ReactGA.initialize only at the initialize of my application. For my pages and buttonClick events, I am only using the ReactGA.pageview (inside componentDidMount) and ReactGA.event (inside event function call)

答: You need to initialize only once, no need to initialize multiple times. If you are not able to see the analytics data one of the reasons could be you are using normal google analytics account which may take some time to update the analytics in your account.</p>