问:
C# DateTime to UTC Time without changing the time
How would I convert a preexisting datetime to UTC time without changing the actual time.

Example:

```<code>DateTime dateTime = GetSomeDateTime(); // dateTime here is 3pm
dateTime.ToUtcDateTime() // datetime should still be 3pm
</code>```

答:
```<code>6/1/2011 4:08:40 PM Local
6/1/2011 4:08:40 PM Utc
</code>```

from

```<code>DateTime dt = DateTime.Now;
Console.WriteLine("{0} {1}", dt, dt.Kind);
DateTime ut = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
Console.WriteLine("{0} {1}", ut, ut.Kind);
</code>```

Body:
How would I convert a preexisting datetime to UTC time without changing the actual time.

Example:

DateTime dateTime = GetSomeDateTime(); // dateTime here is 3pm
dateTime.ToUtcDateTime() // datetime should still be 3pm

Body:
6/1/2011 4:08:40 PM Local
6/1/2011 4:08:40 PM Utc

from

DateTime dt = DateTime.Now;
Console.WriteLine("{0} {1}", dt, dt.Kind);
DateTime ut = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
Console.WriteLine("{0} {1}", ut, ut.Kind);


来源: stackexchange

问:
Post HttpClient returns either body was null or body was object
Trying to use HttpClient to post data I get two different errors:

With booking being an object I get Backend returned code 400, body was: [object Object].

Using JSON.stringify(booking) I get Backend returned code 415, body was: null.

How so?

```<code>public addBooking(booking): Observable<any[]> {
  return this.http.post<any[]>(`${this.url}bookings`, booking)
    .pipe(
      catchError(this.handleError)
    );
}
</code>```

Object:
Using the following as a test object in swagger works.

```<code>{
  "firstDate": "2020-05-29",
  "secondDate": "2020-05-29",
  "productId": 0,
  "userId": 0
}
</code>```

答:
Either the problem is because you have no set the 'Content-Type' in headers as 'application/json'. Otherwise, the problem might be because 'booking' is not actually JSON which contains the mentioned data.

Note: Please mention the data which you are sending to the API (along with the response)

ContentLicense: CC BY-SA 4.0

Body:
Trying to use HttpClient to post data I get two different errors:

With booking being an object I get Backend returned code 400, body was: [object Object].

Using JSON.stringify(booking) I get Backend returned code 415, body was: null.

How so?

public addBooking(booking): Observable<any[]> {
  return this.http.post<any[]>(`${this.url}bookings`, booking)
    .pipe(
      catchError(this.handleError)
    );
}

Object:
Using the following as a test object in swagger works.

{
  "firstDate": "2020-05-29",
  "secondDate": "2020-05-29",
  "productId": 0,
  "userId": 0
}


问:
Remove characters from url hash
Wanting to remove characters from a hash in a url

side bar create url with anchor

e.g

html/g_later_life_lett.html#3.-what-is-important?everything!

```<code>var test = window.location.hash;
$(test).replace('?', '')
</code>```

so when page loads it looks af any ? and ! in hash and removes them.

thanks for help

Updated: thanks add this works fine now

```<code>var currentHash = window.location.hash;
var cleanHash = currentHash.replace(/[?!]/g, "");
window.location.hash = cleanHash;
</code>```

答:
this will remove all the ? and ! in a string:

let str = "html/g_later_life_lett.html#3.-what-is-important?everything!"

console.log(str.replace(/[?!]/g,''));```

Title: Remove characters from url hash

Body:
Wanting to remove characters from a hash in a url

side bar create url with anchor

e.g

html/g_later_life_lett.html#3.-what-is-important?everything!

var test = window.location.hash;
$(test).replace('?', '')

so when page loads it looks af any ? and ! in hash and removes them.

thanks for help

Updated: thanks add this works fine now

var currentHash = window.location.hash;
var cleanHash = currentHash.replace(/[?!]/g, "");
window.location.hash = cleanHash;


问:
Running an operation periodically when the length of operation is not known
I need to execute an operation that needs to be executed relatively fast (let's say 10 times per second.  It should be fast enough, but I can sacrifice speed if there are issues.) This is an ajax request, so potentially I do not know how much time it takes - it could even take seconds if network is bad.

The usual:

```<code>setInterval(() => operation(), 100);
</code>```

Will not work here, because if the network is bad and my operation takes more than 100 ms, It might be scheduled one after another, occupying JS engine time (please correct me if I'm wrong)

The other possible solution is to recursively run it:

```<code>function execute() {
   operation();
   setTimeout(execute, 100);
}
</code>```

This means that there will be 100 ms between the calls to operation(), which is OK for me. The problem with this is that I'm afraid that it will fail at some point because of stack overflow. Consider this code:

```<code>i = 0;
function test() { if (i % 1000 == 0) console.log(i); i++; test(); }
</code>```

If I run it my console, this fails in around 12000 calls. if I add setTimeout in the end, this would mean 12000 / 10 / 60 = 20 minutes, potentially ruining the user experience.

Are there any simple ways how to do this and be sure it can run for days?

答:
There's no "recursion" in asynchronous JavaScript. The synchronous code (the test function) fails because each call occupies some space in the call stack, and when it reaches the maximum size, further function calls throw an error.

However, asynchrony goes beyond the stack: when you call setTimeout, for example, it queues its callback in the event loop and returns immediately. Then, the code, that called it can return as well, and so on until the call stack is empty. setTimeout fires only after that.

The code queued by setTimeout then repeats the process, so no calls accumulate in the call stack.

Therefore, "recursive" setTimeout is a good solution to your problem.

Check this example (I recommend you to open it in fullscreen mode or watch it in the browser console):

Synchronous example:

function synchronousRecursion(i){
  if(i % 5000 === 0) console.log('synchronous', i)
  synchronousRecursion(i+1);
  //The function cannot continue or return, waiting for the recursive call
  //Further code won't be executed because of the error
  console.log('This will never be evaluated')
}

try{
  synchronousRecursion(1)
}catch(e){
  console.error('Note that the stack accumuates (contains the function many times)', e.stack)
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Just to make console fill the available space */
.as-console-wrapper{max-height: 100% !important;}</code>```

Asynchronous example:

function asynchronousRecursion(i){
  console.log('asynchronous',i)
  console.log('Note that the stack does not accumuate (always contains a single item)', new Error('Stack trace:').stack)
  setTimeout(asynchronousRecursion, 100, i+1);
  //setTimeout returns immediately, so code may continue
  console.log('This will be evaluated before the timeout fires')
  //<-- asynchronusRecursion can return here
}

asynchronousRecursion(1)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Just to make console fill the available space */
.as-console-wrapper{max-height: 100% !important;}</code>```

Body:
I need to execute an operation that needs to be executed relatively fast (let's say 10 times per second.  It should be fast enough, but I can sacrifice speed if there are issues.) This is an ajax request, so potentially I do not know how much time it takes - it could even take seconds if network is bad.

The usual:

setInterval(() => operation(), 100);

Will not work here, because if the network is bad and my operation takes more than 100 ms, It might be scheduled one after another, occupying JS engine time (please correct me if I'm wrong)

The other possible solution is to recursively run it:

function execute() {
   operation();
   setTimeout(execute, 100);
}

This means that there will be 100 ms between the calls to operation(), which is OK for me. The problem with this is that I'm afraid that it will fail at some point because of stack overflow. Consider this code:

i = 0;
function test() { if (i % 1000 == 0) console.log(i); i++; test(); }

If I run it my console, this fails in around 12000 calls. if I add setTimeout in the end, this would mean 12000 / 10 / 60 = 20 minutes, potentially ruining the user experience.

Are there any simple ways how to do this and be sure it can run for days?

Body:
There's no "recursion" in asynchronous JavaScript. The synchronous code (the test function) fails because each call occupies some space in the call stack, and when it reaches the maximum size, further function calls throw an error.

However, asynchrony goes beyond the stack: when you call setTimeout, for example, it queues its callback in the event loop and returns immediately. Then, the code, that called it can return as well, and so on until the call stack is empty. setTimeout fires only after that.

The code queued by setTimeout then repeats the process, so no calls accumulate in the call stack.

Therefore, "recursive" setTimeout is a good solution to your problem.

Check this example (I recommend you to open it in fullscreen mode or watch it in the browser console):

Synchronous example:

function synchronousRecursion(i){
  if(i % 5000 === 0) console.log('synchronous', i)
  synchronousRecursion(i+1);
  //The function cannot continue or return, waiting for the recursive call
  //Further code won't be executed because of the error
  console.log('This will never be evaluated')
}

try{
  synchronousRecursion(1)
}catch(e){
  console.error('Note that the stack accumuates (contains the function many times)', e.stack)
}

/* Just to make console fill the available space */
.as-console-wrapper{max-height: 100% !important;}

Asynchronous example:

function asynchronousRecursion(i){
  console.log('asynchronous',i)
  console.log('Note that the stack does not accumuate (always contains a single item)', new Error('Stack trace:').stack)
  setTimeout(asynchronousRecursion, 100, i+1);
  //setTimeout returns immediately, so code may continue
  console.log('This will be evaluated before the timeout fires')
  //<-- asynchronusRecursion can return here
}

asynchronousRecursion(1)

/* Just to make console fill the available space */
.as-console-wrapper{max-height: 100% !important;}


问:
Spring LockRegistry Issue with INT_LOCK
I am using JDBC lock registry but getting INT_LOCK table not being present issue:

```<code>@Bean
    DefaultLockRepository defaultLockRepository(BasicDataSource dataSource) {
        DefaultLockRepository repository = new DefaultLockRepository(dataSource);
        repository.setRegion(this.region);
        repository.setTimeToLive(60 * 5000);
        return repository;
    }

    @Bean
    JdbcLockRegistry jdbcLockRegistry(LockRepository lockRepository) {
        return new JdbcLockRegistry(lockRepository);
    }
</code>```

Error Log:

Caused by: org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [DELETE FROM INT_LOCK WHERE REGION=? AND LOCK_KEY=? AND CREATED_DATE

```<code>at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231) ~[spring-jdbc-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73) ~[spring-jdbc-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:599) ~[spring-jdbc-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:816) ~[spring-jdbc-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:877) ~[spring-jdbc-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:887) ~[spring-jdbc-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.integration.jdbc.lock.DefaultLockRepository.deleteExpired(DefaultLockRepository.java:158) ~[spring-integration-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.integration.jdbc.lock.DefaultLockRepository.acquire(DefaultLockRepository.java:138) ~[spring-integration-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_40]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_40]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_40]
at java.lang.reflect.Method.invoke(Method.java:497) ~[?:1.8.0_40]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) ~[spring-aop-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-5.0.0.M5.jar:5.0.0.M5]
at com.sun.proxy.$Proxy129.acquire(Unknown Source) ~[?:?]
at org.springframework.integration.jdbc.lock.JdbcLockRegistry$JdbcLock.doLock(JdbcLockRegistry.java:224) ~[spring-integration-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.integration.jdbc.lock.JdbcLockRegistry$JdbcLock.tryLock(JdbcLockRegistry.java:202) ~[spring-integration-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
... 87 more
</code>```

Caused by: java.sql.SQLSyntaxErrorException: ORA-00942: table or vie

答:
You need to add the table(s) to the database to use the lock registry. The schemas for various SI components are in the spring-integration-jdbc jar.

You can also see them on GitHub here - make sure you use the version corresponding to your jar.

Title: Spring LockRegistry Issue with INT_LOCK

Body:
I am using JDBC lock registry but getting INT_LOCK table not being present issue:

@Bean
    DefaultLockRepository defaultLockRepository(BasicDataSource dataSource) {
        DefaultLockRepository repository = new DefaultLockRepository(dataSource);
        repository.setRegion(this.region);
        repository.setTimeToLive(60 * 5000);
        return repository;
    }

    @Bean
    JdbcLockRegistry jdbcLockRegistry(LockRepository lockRepository) {
        return new JdbcLockRegistry(lockRepository);
    }

Error Log:

Caused by: org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [DELETE FROM INT_LOCK WHERE REGION=? AND LOCK_KEY=? AND CREATED_DATE

at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231) ~[spring-jdbc-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73) ~[spring-jdbc-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:599) ~[spring-jdbc-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:816) ~[spring-jdbc-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:877) ~[spring-jdbc-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:887) ~[spring-jdbc-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.integration.jdbc.lock.DefaultLockRepository.deleteExpired(DefaultLockRepository.java:158) ~[spring-integration-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.integration.jdbc.lock.DefaultLockRepository.acquire(DefaultLockRepository.java:138) ~[spring-integration-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_40]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_40]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_40]
at java.lang.reflect.Method.invoke(Method.java:497) ~[?:1.8.0_40]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) ~[spring-aop-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-5.0.0.M5.jar:5.0.0.M5]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-5.0.0.M5.jar:5.0.0.M5]
at com.sun.proxy.$Proxy129.acquire(Unknown Source) ~[?:?]
at org.springframework.integration.jdbc.lock.JdbcLockRegistry$JdbcLock.doLock(JdbcLockRegistry.java:224) ~[spring-integration-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
at org.springframework.integration.jdbc.lock.JdbcLockRegistry$JdbcLock.tryLock(JdbcLockRegistry.java:202) ~[spring-integration-jdbc-4.3.9.RELEASE.jar:4.3.9.RELEASE]
... 87 more

Caused by: java.sql.SQLSyntaxErrorException: ORA-00942: table or vie


问:
Django: 'UtilisateurUpdateView' object has no attribute 'object'
I develop a Django project with inlineformset nested using FormView.

I first develop my form using CreateView/UpdateView and it works but when I use FormView I got an error

'UtilisateurUpdateView' object has no attribute 'object'

Why I can get access 'object' when I use UpdateView but not with FormView ?

I have read that it could come from override method but here doesn't seems to be the case ?

forms.py

```<code>NAME = Thesaurus.options_list(2,'fr')
ACCESS = Thesaurus.options_list(3,'fr')
ApplicationFormset = inlineformset_factory(
    UtilisateurProjet, Application, #Utilisateur, Application,
    fields=('app_app_nom','app_dro'),
    widgets={
        'app_app_nom': forms.Select(choices=NAME),
        'app_dro': forms.Select(choices=ACCESS)
    },
    extra=3,
    can_delete=True,
)

class UtilisateurProjetUpdateForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super(UtilisateurProjetUpdateForm, self).__init__(*args, **kwargs)

        self.fields["pro_ide"] = forms.ModelChoiceField(queryset = PROJETS, label = "Nom projet", widget = forms.HiddenInput(), initial = Projet.objects.get(pro_ide=self.request['projet']))
        self.fields["uti_ide"] = forms.ModelChoiceField(queryset = UTILISATEURS, label = "Nom, prénom de l'utilisateur", widget = forms.Select, initial = Utilisateur.objects.get(uti_ide=self.request['utilisateur']))

    class Meta:
        model = UtilisateurProjet
        fields = ('pro_ide','uti_ide',)
</code>```

views.py

```<code>class UtilisateurUpdateView(FormView):
    template_name = 'project/utilisateurprojet_form.html'
    form_class = UtilisateurProjetUpdateForm

    def get_form_kwargs(self):
        kwargs = super(UtilisateurUpdateView, self).get_form_kwargs()
        kwargs['request'] = dict(utilisateur = self.kwargs['pk'], projet = self.kwargs['projet'])
        # kwargs['request'] = self.request
        # print('projet',self.kwargs['projet'])
        # print('utilisateur',self.kwargs['pk'])
        return kwargs

    def get_context_data(self, **kwargs):
        data = super(UtilisateurUpdateView,self).get_context_data(**kwargs)
        # print('projet',self.kwargs['projet'])
        # print('utilisateur',self.kwargs['pk'])
        instance = UtilisateurProjet.objects.get(pro_ide=self.kwargs['projet'],uti_ide=self.kwargs['pk'])
        data['projet'] = Projet.objects.get(pro_ide=self.kwargs['projet'])
        data['utilisateur_app'] = Utilisateur.objects.get(uti_ide=self.kwargs['pk'])
        if self.request.POST:
            data["utilisateur"] = self.request.user.username
            data["user_profil"] = self.request.session.get('user_profil')
            data["application"] = ApplicationFormset(self.request.POST, instance=instance)
        else:
            data["application"] = ApplicationFormset(instance=instance)
        return data

    def form_valid(self, form):
        # Setting commit to False will return the object without saving it to the Database.
        self.object = form.save(commit=False)
        context = self.get_context_data()
        application = context["application"]
        user_profil = context["user_profil"]
        if user_profil == 'Investigateur':
            self.object.uti_val = 0 # demande modifiée par investigateur -> repasse à non validée + envoie de mail
        elif user_profil == 'Moniteur':
            self.object.uti_val = 1 # demande validée par moniteur -> validée + envoie de mail
            self.object.uti_val_dat = timezone.now()
        else:
            self.object.uti_val = 0
        # After doing our own changes to the object, we can save it.
        self.object.save()

        if application.is_valid():
            # Not sure what is happening here, but this statement does nothing by itself.
            # form.instance = self.object
            application.save()

        return super().form_valid(form)

    def get_success_url(self):
        return reverse("project:index")
</code>```

答:
FormView and DetailView are different classes from different packages: django.views.generic.edit.FormView and django.views.generic.detail.DetailView respectively.

From the docs of DetailView:

While this view is executing, self.object will contain the object that
  the view is operating upon.

FormView doesn't have an object property, because it doesn't necessarily work with an object.

However, since you're using ModelForms, you should be able to access the Form's object after calling form.save():

```<code>def form_valid(self, form):
        # Setting commit to False will return the object without saving it to the Database.
        self.object = form.save(commit=False)
        context = self.get_context_data()
        application = context["application"]
        user_profil = context["user_profil"]
        self.object.uti_val = 1
        self.object.uti_val_dat = timezone.now()
        else:
            self.object.uti_val = 0
        # After doing our own changes to the object, we can save it.
        self.object.save()

        if application.is_valid():
            # Not sure what is happening here, but this statement does nothing by itself.
            form.instance = self.object
            application.save()

        return super().form_valid(form)
</code>```

Body:
I develop a Django project with inlineformset nested using FormView.

I first develop my form using CreateView/UpdateView and it works but when I use FormView I got an error

'UtilisateurUpdateView' object has no attribute 'object'

Why I can get access 'object' when I use UpdateView but not with FormView ?

I have read that it could come from override method but here doesn't seems to be the case ?

forms.py

NAME = Thesaurus.options_list(2,'fr')
ACCESS = Thesaurus.options_list(3,'fr')
ApplicationFormset = inlineformset_factory(
    UtilisateurProjet, Application, #Utilisateur, Application,
    fields=('app_app_nom','app_dro'),
    widgets={
        'app_app_nom': forms.Select(choices=NAME),
        'app_dro': forms.Select(choices=ACCESS)
    },
    extra=3,
    can_delete=True,
)

class UtilisateurProjetUpdateForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super(UtilisateurProjetUpdateForm, self).__init__(*args, **kwargs)

        self.fields["pro_ide"] = forms.ModelChoiceField(queryset = PROJETS, label = "Nom projet", widget = forms.HiddenInput(), initial = Projet.objects.get(pro_ide=self.request['projet']))
        self.fields["uti_ide"] = forms.ModelChoiceField(queryset = UTILISATEURS, label = "Nom, prénom de l'utilisateur", widget = forms.Select, initial = Utilisateur.objects.get(uti_ide=self.request['utilisateur']))

    class Meta:
        model = UtilisateurProjet
        fields = ('pro_ide','uti_ide',)

views.py

class UtilisateurUpdateView(FormView):
    template_name = 'project/utilisateurprojet_form.html'
    form_class = UtilisateurProjetUpdateForm

    def get_form_kwargs(self):
        kwargs = super(UtilisateurUpdateView, self).get_form_kwargs()
        kwargs['request'] = dict(utilisateur = self.kwargs['pk'], projet = self.kwargs['projet'])
        # kwargs['request'] = self.request
        # print('projet',self.kwargs['projet'])
        # print('utilisateur',self.kwargs['pk'])
        return kwargs

    def get_context_data(self, **kwargs):
        data = super(UtilisateurUpdateView,self).get_context_data(**kwargs)
        # print('projet',self.kwargs['projet'])
        # print('utilisateur',self.kwargs['pk'])
        instance = UtilisateurProjet.objects.get(pro_ide=self.kwargs['projet'],uti_ide=self.kwargs['pk'])
        data['projet'] = Projet.objects.get(pro_ide=self.kwargs['projet'])
        data['utilisateur_app'] = Utilisateur.objects.get(uti_ide=self.kwargs['pk'])
        if self.request.POST:
            data["utilisateur"] = self.request.user.username
            data["user_profil"] = self.request.session.get('user_profil')
            data["application"] = ApplicationFormset(self.request.POST, instance=instance)
        else:
            data["application"] = ApplicationFormset(instance=instance)
        return data

    def form_valid(self, form):
        # Setting commit to False will return the object without saving it to the Database.
        self.object = form.save(commit=False)
        context = self.get_context_data()
        application = context["application"]
        user_profil = context["user_profil"]
        if user_profil == 'Investigateur':
            self.object.uti_val = 0 # demande modifiée par investigateur -> repasse à non validée + envoie de mail
        elif user_profil == 'Moniteur':
            self.object.uti_val = 1 # demande validée par moniteur -> validée + envoie de mail
            self.object.uti_val_dat = timezone.now()
        else:
            self.object.uti_val = 0
        # After doing our own changes to the object, we can save it.
        self.object.save()

        if application.is_valid():
            # Not sure what is happening here, but this statement does nothing by itself.
            # form.instance = self.object
            application.save()

        return super().form_valid(form)

    def get_success_url(self):
        return reverse("project:index")

Body:
FormView and DetailView are different classes from different packages: django.views.generic.edit.FormView and django.views.generic.detail.DetailView respectively.

From the docs of DetailView:

While this view is executing, self.object will contain the object that
  the view is operating upon.

FormView doesn't have an object property, because it doesn't necessarily work with an object.

However, since you're using ModelForms, you should be able to access the Form's object after calling form.save():

def form_valid(self, form):
        # Setting commit to False will return the object without saving it to the Database.
        self.object = form.save(commit=False)
        context = self.get_context_data()
        application = context["application"]
        user_profil = context["user_profil"]
        self.object.uti_val = 1
        self.object.uti_val_dat = timezone.now()
        else:
            self.object.uti_val = 0
        # After doing our own changes to the object, we can save it.
        self.object.save()

        if application.is_valid():
            # Not sure what is happening here, but this statement does nothing by itself.
            form.instance = self.object
            application.save()

        return super().form_valid(form)


问:
Building Doxygen on MSYS2
Currently I'm facing a problem, compiling Doxygen on MSYS2 using either MinGW32 or Mingw-w64 on Windows 10.

I did:

git clone https://github.com/doxygen/doxygen.git

cd doxygen && mkdir build && cd build

cmake -G "Unix Makefiles" ..

make

When using MinGW32 I get the following errors:

```<code>In file included from C:/msys64/home/dglaser/GIT/doxygen/src/layout.cpp:36:0:
C:/msys64/home/dglaser/GIT/doxygen/build/generated_src/layout_default.xml.h:1:1: warning: missing terminating " character
  \n"doxygenlayout version=\"1.0\">
  ^
[...]
</code>```

When using Mingw-w64 (after deleting build and do above steps again), everything compiles fine and I get errors during linkage:

```<code>C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: ../lib/libdoxymain.a(doxygen.cpp.obj):doxygen.cpp:(.text+0x36dd6): undefined reference to `QFileInfo::absFilePath() const'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: ../lib/libdoxymain.a(doxygen.cpp.obj):doxygen.cpp:(.text+0x36e84): undefined reference to `QFileInfo::isFile() const'
[...]
</code>```

How can one of those be solved?

答:
MSYS2 was somehow broken or outdated. Updating crashed the environment, so I deleted folder C:\msys64 and reinstalled it.

After installing all dependencies correctly (GCC, CMake, Make, Python, libiconv, Bison, and bisonc++), it compiled and executed correctly.

Title: Building Doxygen on MSYS2

Body:
Currently I'm facing a problem, compiling Doxygen on MSYS2 using either MinGW32 or Mingw-w64 on Windows 10.

I did:

git clone https://github.com/doxygen/doxygen.git

cd doxygen && mkdir build && cd build

cmake -G "Unix Makefiles" ..

make

When using MinGW32 I get the following errors:

In file included from C:/msys64/home/dglaser/GIT/doxygen/src/layout.cpp:36:0:
C:/msys64/home/dglaser/GIT/doxygen/build/generated_src/layout_default.xml.h:1:1: warning: missing terminating " character
  \n"doxygenlayout version=\"1.0\">
  ^
[...]

When using Mingw-w64 (after deleting build and do above steps again), everything compiles fine and I get errors during linkage:

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: ../lib/libdoxymain.a(doxygen.cpp.obj):doxygen.cpp:(.text+0x36dd6): undefined reference to `QFileInfo::absFilePath() const'
C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: ../lib/libdoxymain.a(doxygen.cpp.obj):doxygen.cpp:(.text+0x36e84): undefined reference to `QFileInfo::isFile() const'
[...]

How can one of those be solved?


问:
Why are double-quotes urlencoded as %22?
As far as I know, URL encoding exists because URLs only support ASCII encoding. But since " is already in the ASCII table, why should it be encoded as %22 in URL encoding?

答:
The " character falls under section 2.2 (URL Character Encoding Issues) of RFC 1738  (Uniform Resource Locators), under the "Unsafe" section. The reason for the inclusion is:

The quote mark (""") is used to delimit URLs in some systems.

One case of this that I can think of is an HTML attribute. For example, if you have an  tag with an href attribute, you will likely enclose the URL between double quotes. If the " character is not quoted, then the tag becomes invalid:

...
```

The RFC also proceeds to say:

All unsafe characters must always be encoded within a URL.

Some examples of other unsafe characters:

The characters "<" and ">" are unsafe because they are used as the delimiters around URLs in free text.

The character "%" is unsafe because it is used for encodings of other characters.

The character "#" is unsafe and should always be encoded because it is used in World Wide Web and in other systems to delimit a URL from a fragment/anchor identifier that might follow it.

Body:
The " character falls under section 2.2 (URL Character Encoding Issues) of RFC 1738  (Uniform Resource Locators), under the "Unsafe" section. The reason for the inclusion is:

The quote mark (""") is used to delimit URLs in some systems.

One case of this that I can think of is an HTML attribute. For example, if you have an <a> tag with an href attribute, you will likely enclose the URL between double quotes. If the " character is not quoted, then the tag becomes invalid:

<a href="https://example.com/this"should-be-quoted">...</a>

The RFC also proceeds to say:

All unsafe characters must always be encoded within a URL.

Some examples of other unsafe characters:

The characters "<" and ">" are unsafe because they are used as the delimiters around URLs in free text.

The character "%" is unsafe because it is used for encodings of other characters.

The character "#" is unsafe and should always be encoded because it is used in World Wide Web and in other systems to delimit a URL from a fragment/anchor identifier that might follow it.


问:
How to change for Angular in mat-tab-group the transition effect?
The Angular mat-tab-group has for each mat-tab an animation effect already included. The given animation effect is quite annoying and therefore I want to use a different one. I have already one for fadein and fadeout from somebody else.

```<code>export const fadeAnimation = trigger('fadeAnimation', [
  // The '* => *' will trigger the animation to change between any two states
  transition('* => *', [
    // The query function has three params.
    // First is the event, so this will apply on entering or when the element is added to the DOM.
    // Second is a list of styles or animations to apply.
    // Third we add a config object with optional set to true, this is to signal
    // angular that the animation may not apply as it may or may not be in the DOM.
    query(
      ':enter',
      [style({ opacity: 0 })],
      { optional: true }
    ),
    query(
      ':leave',
      // here we apply a style and use the animate function to apply the style over 0.3 seconds
      [style({ opacity: 1 }), animate('0.3s', style({ opacity: 0 }))],
      { optional: true }
    ),
    query(
      ':enter',
      [style({ opacity: 0 }), animate('0.3s', style({ opacity: 1 }))],
      { optional: true }
    )
  ])
]);
</code>```

Trying to apply it like

```<code><mat-tab-group animationDuration="0ms">
  <mat-tab label="First">
      <div [@fadeAnimation]="'enter'">
           Content 1
      </div>
  </mat-tab>
  <mat-tab label="Second"> Content 2 </mat-tab>
  <mat-tab label="Third"> Content 3 </mat-tab>
</mat-tab-group>
</code>```

fails. Any hints how to apply it properly?

Updated the sample according to the suggestion of @ysf.

答:
Considering your code I guess you try to fade in a new tab while fading out a previous one.

Using Eldon's answer I suggest some minor changes:

```<code>.mat-tab-body {
    animation: fade-out 0.5s;
    opacity: 0;
}
.mat-tab-body.mat-tab-body-active {
    animation: fade-in 0.5s;
    opacity: 1;
}

@keyframes fade-in {
    0% {
        opacity: 0;
    }
    50% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

@keyframes fade-out {
    0% {
        opacity: 1;
    }
    50% {
        opacity: 0;
    }
    100% {
        opacity: 0;
    }
}
</code>```

Body:
The Angular mat-tab-group has for each mat-tab an animation effect already included. The given animation effect is quite annoying and therefore I want to use a different one. I have already one for fadein and fadeout from somebody else.

export const fadeAnimation = trigger('fadeAnimation', [
  // The '* => *' will trigger the animation to change between any two states
  transition('* => *', [
    // The query function has three params.
    // First is the event, so this will apply on entering or when the element is added to the DOM.
    // Second is a list of styles or animations to apply.
    // Third we add a config object with optional set to true, this is to signal
    // angular that the animation may not apply as it may or may not be in the DOM.
    query(
      ':enter',
      [style({ opacity: 0 })],
      { optional: true }
    ),
    query(
      ':leave',
      // here we apply a style and use the animate function to apply the style over 0.3 seconds
      [style({ opacity: 1 }), animate('0.3s', style({ opacity: 0 }))],
      { optional: true }
    ),
    query(
      ':enter',
      [style({ opacity: 0 }), animate('0.3s', style({ opacity: 1 }))],
      { optional: true }
    )
  ])
]);

Trying to apply it like

<mat-tab-group animationDuration="0ms">
  <mat-tab label="First">

           Content 1

  </mat-tab>
  <mat-tab label="Second"> Content 2 </mat-tab>
  <mat-tab label="Third"> Content 3 </mat-tab>
</mat-tab-group>

fails. Any hints how to apply it properly?

Updated the sample according to the suggestion of @ysf.

Body:
Considering your code I guess you try to fade in a new tab while fading out a previous one.

Using Eldon's answer I suggest some minor changes:

.mat-tab-body {
    animation: fade-out 0.5s;
    opacity: 0;
}
.mat-tab-body.mat-tab-body-active {
    animation: fade-in 0.5s;
    opacity: 1;
}

@keyframes fade-in {
    0% {
        opacity: 0;
    }
    50% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}

@keyframes fade-out {
    0% {
        opacity: 1;
    }
    50% {
        opacity: 0;
    }
    100% {
        opacity: 0;
    }
}


问:
Authorization Bearer token not being sent in request using Swagger in Asp.Net Core
I am using Swagger to test my APIs in the Asp.Net Core application. I am sending the request using by entering the token like this Authorization: Bearer {token}. but the Authorization header is not being sent in requests.

Asp.Net Core version 3.1 and Swashbuckle.AspNetCore 5.4.1

Startup.cs Code:

```<code>public class Startup
{
    private const string _apiVersion = "v1";
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ClockSkew = TimeSpan.FromMinutes(0),
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    ValidAudience = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });

        services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "MyProject API",
                Description = "MyProject"
            });
            options.DocInclusionPredicate((docName, description) => true);

            // Define the BearerAuth scheme that's in use
            options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
            {
                Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey
            });
        });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseAuthentication();
        loggerFactory.AddLog4Net();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        // Enable middleware to serve generated Swagger as a JSON endpoint
        app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; });

        // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
        app.UseSwaggerUI(options =>
        {
            // specifying the Swagger JSON endpoint.
            options.SwaggerEndpoint($"/swagger/{_apiVersion}/swagger.json", $"MyProject API {_apiVersion}");
            //options.IndexStream = () => Assembly.GetExecutingAssembly()
            //    .GetManifestResourceStream("MyProject.Web.Host.wwwroot.swagger.ui.index.html");
            options.DisplayRequestDuration(); // Controls the display of the request duration (in milliseconds) for "Try it out" requests.
        }); // URL: /swagger
    }
}
</code>```

答:
You need to manually add Authorisation header in Swagger UI. The API config needs to include the BearerAuth schema for the endpoints as described in the specification https://swagger.io/docs/specification/authentication/.

OpenAPI uses the term security scheme for authentication and
  authorization schemes. OpenAPI 3.0 lets you describe APIs protected
  using the following security schemes: HTTP authentication schemes (they use the
  Authorization header), API keys in headers, query string or cookies Cookie
  authentication, OAuth 2, OpenID Connect Discovery

This is done with AddSecurityDefinition, but you are missing AddSecurityRequirement which says it's a requirement for the endpoints and it renders in the UI as it's described in this answer. Also here is an option to automatically add the header.

Body:
I am using Swagger to test my APIs in the Asp.Net Core application. I am sending the request using by entering the token like this Authorization: Bearer {token}. but the Authorization header is not being sent in requests.

Asp.Net Core version 3.1 and Swashbuckle.AspNetCore 5.4.1

Startup.cs Code:

public class Startup
{
    private const string _apiVersion = "v1";
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ClockSkew = TimeSpan.FromMinutes(0),
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    ValidAudience = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });

        services.AddSwaggerGen(options =>
        {
            options.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "MyProject API",
                Description = "MyProject"
            });
            options.DocInclusionPredicate((docName, description) => true);

            // Define the BearerAuth scheme that's in use
            options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
            {
                Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey
            });
        });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseAuthentication();
        loggerFactory.AddLog4Net();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        // Enable middleware to serve generated Swagger as a JSON endpoint
        app.UseSwagger(c => { c.RouteTemplate = "swagger/{documentName}/swagger.json"; });

        // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
        app.UseSwaggerUI(options =>
        {
            // specifying the Swagger JSON endpoint.
            options.SwaggerEndpoint($"/swagger/{_apiVersion}/swagger.json", $"MyProject API {_apiVersion}");
            //options.IndexStream = () => Assembly.GetExecutingAssembly()
            //    .GetManifestResourceStream("MyProject.Web.Host.wwwroot.swagger.ui.index.html");
            options.DisplayRequestDuration(); // Controls the display of the request duration (in milliseconds) for "Try it out" requests.
        }); // URL: /swagger
    }
}


问:
ETA of Cosmos DB Autopilot being available for existing database/ARM template
When will autopilot available for existing database and containers?
When will autopilot available to be configured by ARM template?
Is there ETA for these features? We need to decide whether to wait for the official autopilot or implement it by ourselves if it takes long time before GA.</p>

答:
I still get 'Error updating offer for resource dbs/... {"code":500,"body":{"code":"InternalServerError","message":"Message: {\"Errors\":[\"An unknown error occurred while processing this request. If the issue persists, please contact Azure Support:

Existing container, UK South


答:
Use the DateTime.SpecifyKind static method.

Creates a new DateTime object that has the same number of ticks as the specified DateTime, but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.

Example:

```<code>DateTime dateTime = DateTime.Now;
DateTime other = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);

Console.WriteLine(dateTime + " " + dateTime.Kind); // 6/1/2011 4:14:54 PM Local
Console.WriteLine(other + " " + other.Kind);       // 6/1/2011 4:14:54 PM Utc
</code>```

ContentLicense: CC BY-SA 3.0

Title: C# DateTime to UTC Time without changing the time

Body:
Use the DateTime.SpecifyKind static method.

Creates a new DateTime object that has the same number of ticks as the specified DateTime, but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.

Example:

DateTime dateTime = DateTime.Now;
DateTime other = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);

Console.WriteLine(dateTime + " " + dateTime.Kind); // 6/1/2011 4:14:54 PM Local
Console.WriteLine(other + " " + other.Kind);       // 6/1/2011 4:14:54 PM Utc


问:
NGINX proxy_pass http://localhost:9999/ Not Found
I run my webapp on NGINX with the following configuration:

```<code># Based on https://www.nginx.com/resources/wiki/start/topics/examples/full/#nginx-conf
# user              www www;  ## Default: nobody

worker_processes  auto;
error_log         "/opt/bitnami/nginx/logs/error.log";
pid               "/opt/bitnami/nginx/tmp/nginx.pid";

events {
  worker_connections  1024;
}

http {
  include       mime.types;
  default_type  application/octet-stream;
  log_format    main '$remote_addr - $remote_user [$time_local] '
  '"$request" $status  $body_bytes_sent "$http_referer" '
  '"$http_user_agent" "$http_x_forwarded_for"';
  access_log    "/opt/bitnami/nginx/logs/access.log";
  add_header    X-Frame-Options SAMEORIGIN;

  client_body_temp_path  "/opt/bitnami/nginx/tmp/client_body" 1 2;
  proxy_temp_path        "/opt/bitnami/nginx/tmp/proxy" 1 2;
  fastcgi_temp_path      "/opt/bitnami/nginx/tmp/fastcgi" 1 2;
  scgi_temp_path         "/opt/bitnami/nginx/tmp/scgi" 1 2;
  uwsgi_temp_path        "/opt/bitnami/nginx/tmp/uwsgi" 1 2;

  sendfile           on;
  tcp_nopush         on;
  tcp_nodelay        off;
  gzip               on;
  gzip_http_version  1.0;
  gzip_comp_level    2;
  gzip_proxied       any;
  gzip_types         text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
  keepalive_timeout  65;
  ssl_protocols      TLSv1 TLSv1.1 TLSv1.2;
  client_max_body_size 80M;
  server_tokens off;
  include  "/opt/bitnami/nginx/conf/server_blocks/*.conf";

  # HTTP Server
  server {
    # port to listen on. Can also be set to an IP:PORT
    listen  8080;

    location /api/* {
      proxy_set_header X-Forwarded-Host $host:$server_port;
      proxy_set_header X-Forwarded-Server $host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_pass http://localhost:9999;

    }

    location /status {
      stub_status on;
      access_log   off;
      allow 127.0.0.1;
      deny all;
    }
  }
}
</code>```

and the way that I do the call:

```<code>methods: {
  load_user(event) {

    console.log(this.$kc)

    const config = {
      headers: {Authorization: `Bearer ${this.$kc.token}`}
    };

    this.$axios.get('/api/hello/sali', config)
      .then((response) => {
        console.log(response)
      })
      .catch(() => {
        console.log("errro")
      })
  },
</code>```

Then it shows the following message:

However, it should return:

What am I doing wrong?

答:
You're listening on port 8080, not 8090, have you tried that?</p>

```<code>localhost:8080
</code>```

Body:
I run my webapp on NGINX with the following configuration:

# Based on https://www.nginx.com/resources/wiki/start/topics/examples/full/#nginx-conf
# user              www www;  ## Default: nobody

worker_processes  auto;
error_log         "/opt/bitnami/nginx/logs/error.log";
pid               "/opt/bitnami/nginx/tmp/nginx.pid";

events {
  worker_connections  1024;
}

http {
  include       mime.types;
  default_type  application/octet-stream;
  log_format    main '$remote_addr - $remote_user [$time_local] '
  '"$request" $status  $body_bytes_sent "$http_referer" '
  '"$http_user_agent" "$http_x_forwarded_for"';
  access_log    "/opt/bitnami/nginx/logs/access.log";
  add_header    X-Frame-Options SAMEORIGIN;

  client_body_temp_path  "/opt/bitnami/nginx/tmp/client_body" 1 2;
  proxy_temp_path        "/opt/bitnami/nginx/tmp/proxy" 1 2;
  fastcgi_temp_path      "/opt/bitnami/nginx/tmp/fastcgi" 1 2;
  scgi_temp_path         "/opt/bitnami/nginx/tmp/scgi" 1 2;
  uwsgi_temp_path        "/opt/bitnami/nginx/tmp/uwsgi" 1 2;

  sendfile           on;
  tcp_nopush         on;
  tcp_nodelay        off;
  gzip               on;
  gzip_http_version  1.0;
  gzip_comp_level    2;
  gzip_proxied       any;
  gzip_types         text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
  keepalive_timeout  65;
  ssl_protocols      TLSv1 TLSv1.1 TLSv1.2;
  client_max_body_size 80M;
  server_tokens off;
  include  "/opt/bitnami/nginx/conf/server_blocks/*.conf";

  # HTTP Server
  server {
    # port to listen on. Can also be set to an IP:PORT
    listen  8080;

    location /api/* {
      proxy_set_header X-Forwarded-Host $host:$server_port;
      proxy_set_header X-Forwarded-Server $host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_pass http://localhost:9999;

    }

    location /status {
      stub_status on;
      access_log   off;
      allow 127.0.0.1;
      deny all;
    }
  }
}

and the way that I do the call:

methods: {
  load_user(event) {

    console.log(this.$kc)

    const config = {
      headers: {Authorization: `Bearer ${this.$kc.token}`}
    };

    this.$axios.get('/api/hello/sali', config)
      .then((response) => {
        console.log(response)
      })
      .catch(() => {
        console.log("errro")
      })
  },

Then it shows the following message:

However, it should return:

What am I doing wrong?

Body:
You're listening on port 8080, not 8090, have you tried that?

localhost:8080


问:
Insert image into SQL Server database tables column
so I created a Menu Table like this

```<code>create table Menu(
MenuID char(5) primary key check(menuID LIKE 'MN[0-9][0-9][0-9]'),
MenuName varchar (50) not null,
MenuPrice int not null,
MenuImage varbinary(max) not null,
CategoryID char(5) references Category(CategoryID) ON UPDATE CASCADE ON DELETE SET NULL
)
</code>```

and I wanted to insert values into Menu but it isn't working.

```<code>insert into Menu values
('MN001','Mac & Cheese',60000,(SELECT * FROM OPENROWSET(BULK 'C:\Users\Kristina\Documents\FOODS\maccheese.jpg', SINGLE_BLOB) as T1),'CA001'),
('MN002','Grilled Veggies',60000,(SELECT * FROM OPENROWSET(BULK 'C:\Users\Kristina\Documents\FOODS\grilled.jpg', SINGLE_BLOB) as T2),'CA001')
</code>```

It kept giving me: Incorrect syntax near ','. I'm using SQL Server Management Studio 18.
I'm very new to this. Please help me, thanks!

答:
Works fine for me</p>

```<code>create table Menu(
MenuID char(5) primary key check(menuID LIKE 'MN[0-9][0-9][0-9]'),
MenuName varchar (50) not null,
MenuPrice int not null,
MenuImage varbinary(max) not null,
CategoryID char(5) --references Category(CategoryID) ON UPDATE CASCADE ON DELETE SET NULL
)

insert into Menu values
('MN001','Mac & Cheese',60000,(SELECT * FROM OPENROWSET(BULK 'C:\temp\t.txt', SINGLE_BLOB) as T1),'CA001'),
('MN002','Grilled Veggies',60000,(SELECT * FROM OPENROWSET(BULK 'C:\temp\t.txt', SINGLE_BLOB) as T2),'CA001')
</code>```

Body:
so I created a Menu Table like this

create table Menu(
MenuID char(5) primary key check(menuID LIKE 'MN[0-9][0-9][0-9]'),
MenuName varchar (50) not null,
MenuPrice int not null,
MenuImage varbinary(max) not null,
CategoryID char(5) references Category(CategoryID) ON UPDATE CASCADE ON DELETE SET NULL
)

and I wanted to insert values into Menu but it isn't working.

insert into Menu values
('MN001','Mac & Cheese',60000,(SELECT * FROM OPENROWSET(BULK 'C:\Users\Kristina\Documents\FOODS\maccheese.jpg', SINGLE_BLOB) as T1),'CA001'),
('MN002','Grilled Veggies',60000,(SELECT * FROM OPENROWSET(BULK 'C:\Users\Kristina\Documents\FOODS\grilled.jpg', SINGLE_BLOB) as T2),'CA001')

It kept giving me: Incorrect syntax near ','. I'm using SQL Server Management Studio 18.
I'm very new to this. Please help me, thanks!

Body:
Works fine for me

create table Menu(
MenuID char(5) primary key check(menuID LIKE 'MN[0-9][0-9][0-9]'),
MenuName varchar (50) not null,
MenuPrice int not null,
MenuImage varbinary(max) not null,
CategoryID char(5) --references Category(CategoryID) ON UPDATE CASCADE ON DELETE SET NULL
)

insert into Menu values
('MN001','Mac & Cheese',60000,(SELECT * FROM OPENROWSET(BULK 'C:\temp\t.txt', SINGLE_BLOB) as T1),'CA001'),
('MN002','Grilled Veggies',60000,(SELECT * FROM OPENROWSET(BULK 'C:\temp\t.txt', SINGLE_BLOB) as T2),'CA001')


问:
Communication between Gmail Addon and external site
I'm building a Gmail Add-on where user needs to authenticate to a service to use it. To do that, we have a site that act as a proxy for multiple service (for example, Dropbox and Box). The way that it works, user selects a service to authenticate, it is redirected to their oauth page, and when callback is received, token is generated on our own service and send back our token, not theirs.

So flow would be...

```<code>1. User clicks login on Gmail Add-on
2. Opens own site (third party) that contains multiple login options.
3. Selects one that redirects user inside it on a new oAuth service.
4. Our service (inside the open window) receives oAuth token and creates a new token.
5. This new token is sent back to add-on.
</code>```

What I wonder is how can I get/send/proceed with this last step, once we got our token, is there a way to send it back to the gmail add-on? On other platforms, we could read redirections, send sockets, but I don't get how it can be achieved on google apps script.

Any ideas?

答:
What I was asking can be achieved using the class ScriptApp. Basically, external site can use the usercallback script to return the token so the flow would be:

Generate a callback state.

Send the redirect_uri with state token.

You can do whatever you want on this step (on external site).

Send back in url param the information (in my case, token) that you need.

Callback response can be get on your callback action.

Body:
I'm building a Gmail Add-on where user needs to authenticate to a service to use it. To do that, we have a site that act as a proxy for multiple service (for example, Dropbox and Box). The way that it works, user selects a service to authenticate, it is redirected to their oauth page, and when callback is received, token is generated on our own service and send back our token, not theirs.

So flow would be...

1. User clicks login on Gmail Add-on
2. Opens own site (third party) that contains multiple login options.
3. Selects one that redirects user inside it on a new oAuth service.
4. Our service (inside the open window) receives oAuth token and creates a new token.
5. This new token is sent back to add-on.

What I wonder is how can I get/send/proceed with this last step, once we got our token, is there a way to send it back to the gmail add-on? On other platforms, we could read redirections, send sockets, but I don't get how it can be achieved on google apps script.

Any ideas?


问:
kubectl get -o yaml: is it possible to hide metadata.managedFields?
Using kubectl version 1.18, on microk8s 1.18.3

When getting a resource definition in yaml format. Example  kubectl get pod/mypod-6f855c5fff-j8mrw -o yaml. The output contains a section related to metadata.managedFields

Is there a way to hide that metadata.managedFields to shorten the console output?

Below is an example of output to better illustrate the question.

```<code>apiVersion: v1
kind: Service
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"labels":{"app":"productpage","service":"productpage"},"name":"productpage","namespace":"bookinfo"},"spec":{"ports":[{"name":"http","port":9080}],"selector":{"app":"productpage"}}}
  creationTimestamp: "2020-05-28T05:22:41Z"
  labels:
    app: productpage
    service: productpage
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:metadata:
        f:annotations:
          .: {}
          f:kubectl.kubernetes.io/last-applied-configuration: {}
        f:labels:
          .: {}
          f:app: {}
          f:service: {}
      f:spec:
        f:ports:
          .: {}
          k:{"port":9080,"protocol":"TCP"}:
            .: {}
            f:name: {}
            f:port: {}
            f:protocol: {}
            f:targetPort: {}
        f:selector:
          .: {}
          f:app: {}
        f:sessionAffinity: {}
        f:type: {}
    manager: kubectl
    operation: Update
    time: "2020-05-28T05:22:41Z"
  name: productpage
  namespace: bookinfo
  resourceVersion: "121804"
  selfLink: /api/v1/namespaces/bookinfo/services/productpage
  uid: feb5a62b-8784-41d2-b104-bf6ebc4a2763
spec:
  clusterIP: 10.152.183.9
  ports:
  - name: http
    port: 9080
    protocol: TCP
    targetPort: 9080
  selector:
    app: productpage
  sessionAffinity: None
  type: ClusterIP
status:
  loadBalancer: {}
</code>```

答:
First thing what came to my mind was to just use stream editor like sed to just skip this part beggining form managedFields: to another specific pattern.

It's bit hardcoded as you would need to specify 2 patterns like managedFields: and ending pattern like name: productpage but will work for this scenario. If this won't fit you, pleas add more details, how you would like to achieve this.

sed command would look like:

```<code>sed -n '/(Pattern1)/{p; :a; N; /(Pattern2)/!ba; s/.*\n//}; p'
</code>```

For example Ive used Nginx pod:

```<code>$ kubectl get po nginx -o yaml
apiVersion: v1
kind: Pod
metadata:
  annotations:
    kubernetes.io/limit-ranger: 'LimitRanger plugin set: cpu request for container
      nginx'
  creationTimestamp: "2020-05-29T10:54:18Z"
...
spec:
  containers:
  - image: nginx
    imagePullPolicy: Always
    name: nginx
   ...
status:
  conditions:
...
        startedAt: "2020-05-29T10:54:19Z"
  hostIP: 10.154.0.29
  phase: Running
  podIP: 10.52.1.6
  podIPs:
  - ip: 10.52.1.6
  qosClass: Burstable
  startTime: "2020-05-29T10:54:18Z"
</code>```

After using sed

```<code>$ kubectl get po nginx -o yaml | sed -n '/annotations:/{p; :a; N; /hostIP: 10.154.0.29/!ba; s/.*\n//}; p'
apiVersion: v1
kind: Pod
metadata:
  annotations:
  hostIP: 10.154.0.29
  phase: Running
  podIP: 10.52.1.6
  podIPs:
  - ip: 10.52.1.6
  qosClass: Burstable
  startTime: "2020-05-29T10:54:18Z"
</code>```

In your case command like:

```<code>$ kubectl get pod/mypod-6f855c5fff-j8mrw -o yaml | sed -n '/managedFields:/{p; :a; N; /name: productpage/!ba; s/.*\n//}; p'
</code>```

Should give output like:

```<code>apiVersion: v1
kind: Service
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"labels":{"app":"productpage","service":"productpage"},"name":"productpage","namespace":"bookinfo"},"spec":{"ports":[{"name":"http","port":9080}],"selector":{"app":"productpage"}}}
  creationTimestamp: "2020-05-28T05:22:41Z"
  labels:
    app: productpage
    service: productpage
  managedFields:
  name: productpage
  namespace: bookinfo
  resourceVersion: "121804"
  selfLink: /api/v1/namespaces/bookinfo/services/productpage
  uid: feb5a62b-8784-41d2-b104-bf6ebc4a2763
spec:
  clusterIP: 10.152.183.9
  ports:
  - name: http
    port: 9080
    protocol: TCP
    targetPort: 9080
  selector:
    app: productpage
  sessionAffinity: None
  type: ClusterIP
status:
  loadBalancer: {}
</code>```

Body:
Using kubectl version 1.18, on microk8s 1.18.3

When getting a resource definition in yaml format. Example  kubectl get pod/mypod-6f855c5fff-j8mrw -o yaml. The output contains a section related to metadata.managedFields

Is there a way to hide that metadata.managedFields to shorten the console output?

Below is an example of output to better illustrate the question.

apiVersion: v1
kind: Service
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"labels":{"app":"productpage","service":"productpage"},"name":"productpage","namespace":"bookinfo"},"spec":{"ports":[{"name":"http","port":9080}],"selector":{"app":"productpage"}}}
  creationTimestamp: "2020-05-28T05:22:41Z"
  labels:
    app: productpage
    service: productpage
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:metadata:
        f:annotations:
          .: {}
          f:kubectl.kubernetes.io/last-applied-configuration: {}
        f:labels:
          .: {}
          f:app: {}
          f:service: {}
      f:spec:
        f:ports:
          .: {}
          k:{"port":9080,"protocol":"TCP"}:
            .: {}
            f:name: {}
            f:port: {}
            f:protocol: {}
            f:targetPort: {}
        f:selector:
          .: {}
          f:app: {}
        f:sessionAffinity: {}
        f:type: {}
    manager: kubectl
    operation: Update
    time: "2020-05-28T05:22:41Z"
  name: productpage
  namespace: bookinfo
  resourceVersion: "121804"
  selfLink: /api/v1/namespaces/bookinfo/services/productpage
  uid: feb5a62b-8784-41d2-b104-bf6ebc4a2763
spec:
  clusterIP: 10.152.183.9
  ports:
  - name: http
    port: 9080
    protocol: TCP
    targetPort: 9080
  selector:
    app: productpage
  sessionAffinity: None
  type: ClusterIP
status:
  loadBalancer: {}

Body:
First thing what came to my mind was to just use stream editor like sed to just skip this part beggining form managedFields: to another specific pattern.

It's bit hardcoded as you would need to specify 2 patterns like managedFields: and ending pattern like name: productpage but will work for this scenario. If this won't fit you, pleas add more details, how you would like to achieve this.

sed command would look like:

sed -n '/(Pattern1)/{p; :a; N; /(Pattern2)/!ba; s/.*\n//}; p'

For example Ive used Nginx pod:

$ kubectl get po nginx -o yaml
apiVersion: v1
kind: Pod
metadata:
  annotations:
    kubernetes.io/limit-ranger: 'LimitRanger plugin set: cpu request for container
      nginx'
  creationTimestamp: "2020-05-29T10:54:18Z"
...
spec:
  containers:
  - image: nginx
    imagePullPolicy: Always
    name: nginx
   ...
status:
  conditions:
...
        startedAt: "2020-05-29T10:54:19Z"
  hostIP: 10.154.0.29
  phase: Running
  podIP: 10.52.1.6
  podIPs:
  - ip: 10.52.1.6
  qosClass: Burstable
  startTime: "2020-05-29T10:54:18Z"

After using sed

$ kubectl get po nginx -o yaml | sed -n '/annotations:/{p; :a; N; /hostIP: 10.154.0.29/!ba; s/.*\n//}; p'
apiVersion: v1
kind: Pod
metadata:
  annotations:
  hostIP: 10.154.0.29
  phase: Running
  podIP: 10.52.1.6
  podIPs:
  - ip: 10.52.1.6
  qosClass: Burstable
  startTime: "2020-05-29T10:54:18Z"

In your case command like:

$ kubectl get pod/mypod-6f855c5fff-j8mrw -o yaml | sed -n '/managedFields:/{p; :a; N; /name: productpage/!ba; s/.*\n//}; p'

Should give output like:

apiVersion: v1
kind: Service
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"labels":{"app":"productpage","service":"productpage"},"name":"productpage","namespace":"bookinfo"},"spec":{"ports":[{"name":"http","port":9080}],"selector":{"app":"productpage"}}}
  creationTimestamp: "2020-05-28T05:22:41Z"
  labels:
    app: productpage
    service: productpage
  managedFields:
  name: productpage
  namespace: bookinfo
  resourceVersion: "121804"
  selfLink: /api/v1/namespaces/bookinfo/services/productpage
  uid: feb5a62b-8784-41d2-b104-bf6ebc4a2763
spec:
  clusterIP: 10.152.183.9
  ports:
  - name: http
    port: 9080
    protocol: TCP
    targetPort: 9080
  selector:
    app: productpage
  sessionAffinity: None
  type: ClusterIP
status:
  loadBalancer: {}


问:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I am getting error Expecting value: line 1 column 1 (char 0) when trying to decode JSON.

The URL I use for the API call works fine in the browser, but gives this error when done through a curl request. The following is the code I use for the curl request.

The error happens at return simplejson.loads(response_json)

```<code>response_json = self.web_fetch(url)
response_json = response_json.decode('utf-8')
return json.loads(response_json)

def web_fetch(self, url):
    buffer = StringIO()
    curl = pycurl.Curl()
    curl.setopt(curl.URL, url)
    curl.setopt(curl.TIMEOUT, self.timeout)
    curl.setopt(curl.WRITEFUNCTION, buffer.write)
    curl.perform()
    curl.close()
    response = buffer.getvalue().strip()
    return response
</code>```

Traceback:

```<code>File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Users/nab/Desktop/pricestore/pricemodels/views.py" in view_category
  620.     apicall=api.API().search_parts(category_id= str(categoryofpart.api_id), manufacturer = manufacturer, filter = filters, start=(catpage-1)*20, limit=20, sort_by='[["mpn","asc"]]')
File "/Users/nab/Desktop/pricestore/pricemodels/api.py" in search_parts
  176.         return simplejson.loads(response_json)
File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/simplejson/__init__.py" in loads
  455.         return _default_decoder.decode(s)
File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/simplejson/decoder.py" in decode
  374.         obj, end = self.raw_decode(s)
File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/simplejson/decoder.py" in raw_decode
  393.         return self.scan_once(s, idx=_w(s, idx).end())

Exception Type: JSONDecodeError at /pricemodels/2/dir/
Exception Value: Expecting value: line 1 column 1 (char 0)
</code>```

答:
Just check if the request has a status code 200. So for example:</p>

```<code>if status != 200:
    print("An error has occured. [Status code", status, "]")
else:
    data = response.json() #Only convert to Json when status is OK.
    if not data["elements"]:
        print("Empty JSON")
    else:
        "You can extract data here"
</code>```

Body:
I am getting error Expecting value: line 1 column 1 (char 0) when trying to decode JSON.

The URL I use for the API call works fine in the browser, but gives this error when done through a curl request. The following is the code I use for the curl request.

The error happens at return simplejson.loads(response_json)

response_json = self.web_fetch(url)
response_json = response_json.decode('utf-8')
return json.loads(response_json)

def web_fetch(self, url):
    buffer = StringIO()
    curl = pycurl.Curl()
    curl.setopt(curl.URL, url)
    curl.setopt(curl.TIMEOUT, self.timeout)
    curl.setopt(curl.WRITEFUNCTION, buffer.write)
    curl.perform()
    curl.close()
    response = buffer.getvalue().strip()
    return response

Traceback:

File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Users/nab/Desktop/pricestore/pricemodels/views.py" in view_category
  620.     apicall=api.API().search_parts(category_id= str(categoryofpart.api_id), manufacturer = manufacturer, filter = filters, start=(catpage-1)*20, limit=20, sort_by='[["mpn","asc"]]')
File "/Users/nab/Desktop/pricestore/pricemodels/api.py" in search_parts
  176.         return simplejson.loads(response_json)
File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/simplejson/__init__.py" in loads
  455.         return _default_decoder.decode(s)
File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/simplejson/decoder.py" in decode
  374.         obj, end = self.raw_decode(s)
File "/Users/nab/Desktop/myenv2/lib/python2.7/site-packages/simplejson/decoder.py" in raw_decode
  393.         return self.scan_once(s, idx=_w(s, idx).end())

Exception Type: JSONDecodeError at /pricemodels/2/dir/
Exception Value: Expecting value: line 1 column 1 (char 0)

Body:
Just check if the request has a status code 200. So for example:

if status != 200:
    print("An error has occured. [Status code", status, "]")
else:
    data = response.json() #Only convert to Json when status is OK.
    if not data["elements"]:
        print("Empty JSON")
    else:
        "You can extract data here"


问:
Authzforce ABAC - Fail to Enable a Result Postprocessor extension on a domain
I follow the instructions on link

1- Created the extension jar package from 'TestCombinedDecisionXacmlJaxbResultPostprocessor' class by replacing the type to 'urn:ow2:authzforce:feature:pdp:result-postproc:xacml-json:default'

2- Placed the jar under /opt/authzforce-ce-server/webapp/WEB-INF/lib directory

3- Tried to enable the extension with:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<pdpPropertiesUpdate xmlns="http://authzforce.github.io/rest-api-model/xmlns/authz/5">
 <feature
 type="urn:ow2:authzforce:feature-type:pdp:result-postproc"
 enabled="true">urn:ow2:authzforce:feature:pdp:result-postproc:xacml-json:default</feature>
 <rootPolicyRefExpression>root</rootPolicyRefExpression>
</pdpPropertiesUpdate>
</code>```

and got response:

```<code><!doctype html><html lang="en"><head><title>HTTP Status 405 – Method Not Allowed</title><style type="text/css">body {font-family:Tahoma,Arial,sans-serif;
} h1, h2, h3, b {color:white;background-color:#525D76;
} h1 {font-size: 22px;
} h2 {font-size: 16px;
} h3 {font-size: 14px;
} p {font-size: 12px;
} a {color:black;
} .line {height: 1px;background-color:#525D76;border:none;
}</style></head><body><h1>HTTP Status 405 – Method Not Allowed</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Description</b> The method received in the request-line is known by the origin server but not supported by the target resource.</p><hr class="line" /><h3>Apache Tomcat/8.5.54 (Debian)</h3></body></html>
</code>```

After this, I receive HTTP-404 for all the requests on domain.
Can you suggest what I am missing? What is the rootcause for that issue?

Sharing the source code for the extension package:

```<code>public class PostprocessorLoader extends BaseXacmlJaxbResultPostprocessor  {
    private static final Set<String> FEATURES = ImmutableSet.of(DecisionResultPostprocessor.Features.XACML_MULTIPLE_DECISION_PROFILE_COMBINED_DECISION);
    private static final Response SIMPLE_INDETERMINATE_RESPONSE = new Response(
            Collections.singletonList(new Result(DecisionType.INDETERMINATE, new StatusHelper(XacmlStatusCode.PROCESSING_ERROR.value(), Optional.<String>empty()), null, null, null, null)));
    // private static final List<Result> INDETERMINATE_RESULT_SINGLETON_LIST_BECAUSE_NO_INDIVIDUAL = Collections.singletonList(new Result(DecisionType.INDETERMINATE, new StatusHelper(
    // StatusHelper.STATUS_PROCESSING_ERROR, "No <Result> to combine!"), null, null, null, null));
    private static final Response SIMPLE_PERMIT_RESPONSE = new Response(Collections.singletonList(new Result(DecisionType.PERMIT, StatusHelper.OK, null, null, null, null)));
    private static final Response SIMPLE_DENY_RESPONSE = new Response(Collections.singletonList(new Result(DecisionType.DENY, StatusHelper.OK, null, null, null, null)));
    private static final Response SIMPLE_NOT_APPLICABLE_RESPONSE = new Response(Collections.singletonList(new Result(DecisionType.NOT_APPLICABLE, StatusHelper.OK, null, null, null, null)));

    private PostprocessorLoader(final int clientRequestErrorVerbosityLevel) throws IllegalArgumentException {
        super(clientRequestErrorVerbosityLevel);
    }

    @Override
    public Set<String> getFeatures()
    {
        return FEATURES;
    }

    @Override
    public Response process(final Collection<Map.Entry<IndividualXacmlJaxbRequest, ? extends DecisionResult>> resultsByRequest)
    {
        System.out.println("#####################Inside process");
        if (resultsByRequest!=null){
            System.out.println(resultsByRequest.size());
        }else{
            System.out.println("#####################resultsByRequest is null!");
        }
        DecisionType combinedDecision = DecisionType.INDETERMINATE;
        for (final Map.Entry<? extends IndividualXacmlJaxbRequest, ? extends DecisionResult> resultEntry : resultsByRequest)
        {
            System.out.println("#####################resultEntry:"+resultEntry.getValue());
            final DecisionResult result = resultEntry.getValue();
            System.out.println("#####################getDecision:"+result.getDecision());
            if (result.getDecision() == DecisionType.INDETERMINATE)
            {
                // either all result must be indeterminate or we return Indeterminate as final result anyway
                return SIMPLE_INDETERMINATE_RESPONSE;
            }

            final ImmutableList<PepAction> pepActions = result.getPepActions();
            assert pepActions != null;

            if (!pepActions.isEmpty())
            {
                return SIMPLE_INDETERMINATE_RESPONSE;
            }

            final DecisionType individualDecision = result.getDecision();
            // if combinedDecision not initialized yet (indeterminate), set it to the result's decision
            if (combinedDecision == DecisionType.INDETERMINATE)
            {
                combinedDecision = individualDecision;
            } else
                // combinedDecision != Indeterminate
                if (individualDecision != combinedDecision)
                {
                    return SIMPLE_INDETERMINATE_RESPONSE;
                }
        }
        System.out.println("#####################Before CombinedDecision switch");
        try {
            System.out.printf("#####################process method!");
            //System.out.println(documentService.getIndividualHealthRoleByName("").toString());
        }catch(Exception ex){
            System.out.println("#####################process method err:"+ex.getCause());
        }

        switch (combinedDecision)
        {
            case PERMIT:
                return SIMPLE_PERMIT_RESPONSE;
            case DENY:
                return SIMPLE_DENY_RESPONSE;
            case NOT_APPLICABLE:
                return SIMPLE_NOT_APPLICABLE_RESPONSE;
            default:
                return SIMPLE_INDETERMINATE_RESPONSE;
        }
    }

    /**
     *
     * Factory for this type of result postprocessor filter that allows duplicate <Attribute> with same meta-data in the same <Attributes> element of a Request (complying with XACML 3.0
     * core spec, §7.3.3).
     *
     */
    public static final class Factory extends BaseXacmlJaxbResultPostprocessor.Factory
    {
        /**
         * ID of this {@link PdpExtension}
         */
        public static final String ID = "urn:ow2:authzforce:feature:pdp:result-postproc:xacml-json:default";

        /**
         * Constructor
         */
        public Factory()
        {
            super(ID);
        }

        @Override
        public DecisionResultPostprocessor<IndividualXacmlJaxbRequest, Response> getInstance(final int clientRequestErrorVerbosityLevel)
        {
            return new PostprocessorLoader(clientRequestErrorVerbosityLevel);
        }

    }
}
</code>```

NOTE: Same thing happened when I placed jar file from maven artifactId=authzforce-ce-core-pdp-testutils to lib folder and tried to enable with recommended request body in above-mentioned link.

答:
You are trying to enable the postprocessor with ID urn:ow2:authzforce:feature:pdp:result-postproc:xacml-json:default which is already reserved and provided by AuthzForce (for processing JSON response according to JSON Profile of XACML). Therefore, you can't use the same ID for your own implementation!

So change the ID in your code (just an example here, choose your own):

```<code>/**
  * ID of this {@link PdpExtension}
  */
public static final String ID = "my-own-postproc-id";
</code>```

FYI, if all you need is the CombinedDecision feature for XACML/XML, as it seems so (but I may be wrong about what you are trying to achieve), this is already implemented by the class TestCombinedDecisionXacmlJaxbResultPostprocessor. You just have to deploy the authzforce-ce-core-pdp-testutils JAR in WEB-INF/lib (in same version as the authzforce-ce-core-pdp-engine JAR there), restart, and enable it like you did in step 3 but with the feature ID urn:ow2:authzforce:feature:pdp:result-postproc:xacml-xml:multiple:test-combined-decision.

Body:
I follow the instructions on link

1- Created the extension jar package from 'TestCombinedDecisionXacmlJaxbResultPostprocessor' class by replacing the type to 'urn:ow2:authzforce:feature:pdp:result-postproc:xacml-json:default'

2- Placed the jar under /opt/authzforce-ce-server/webapp/WEB-INF/lib directory

3- Tried to enable the extension with:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<pdpPropertiesUpdate xmlns="http://authzforce.github.io/rest-api-model/xmlns/authz/5">
 <feature
 type="urn:ow2:authzforce:feature-type:pdp:result-postproc"
 enabled="true">urn:ow2:authzforce:feature:pdp:result-postproc:xacml-json:default</feature>
 <rootPolicyRefExpression>root</rootPolicyRefExpression>
</pdpPropertiesUpdate>

and got response:

<!doctype html><title>HTTP Status 405 – Method Not Allowed</title>
HTTP Status 405 – Method Not Allowed

Type Status Report

Description The method received in the request-line is known by the origin server but not supported by the target resource.

Apache Tomcat/8.5.54 (Debian)

After this, I receive HTTP-404 for all the requests on domain.
Can you suggest what I am missing? What is the rootcause for that issue?

Sharing the source code for the extension package:

public class PostprocessorLoader extends BaseXacmlJaxbResultPostprocessor  {
    private static final Set<String> FEATURES = ImmutableSet.of(DecisionResultPostprocessor.Features.XACML_MULTIPLE_DECISION_PROFILE_COMBINED_DECISION);
    private static final Response SIMPLE_INDETERMINATE_RESPONSE = new Response(
            Collections.singletonList(new Result(DecisionType.INDETERMINATE, new StatusHelper(XacmlStatusCode.PROCESSING_ERROR.value(), Optional.<String>empty()), null, null, null, null)));
    // private static final List<Result> INDETERMINATE_RESULT_SINGLETON_LIST_BECAUSE_NO_INDIVIDUAL = Collections.singletonList(new Result(DecisionType.INDETERMINATE, new StatusHelper(
    // StatusHelper.STATUS_PROCESSING_ERROR, "No <Result> to combine!"), null, null, null, null));
    private static final Response SIMPLE_PERMIT_RESPONSE = new Response(Collections.singletonList(new Result(DecisionType.PERMIT, StatusHelper.OK, null, null, null, null)));
    private static final Response SIMPLE_DENY_RESPONSE = new Response(Collections.singletonList(new Result(DecisionType.DENY, StatusHelper.OK, null, null, null, null)));
    private static final Response SIMPLE_NOT_APPLICABLE_RESPONSE = new Response(Collections.singletonList(new Result(DecisionType.NOT_APPLICABLE, StatusHelper.OK, null, null, null, null)));

    private PostprocessorLoader(final int clientRequestErrorVerbosityLevel) throws IllegalArgumentException {
        super(clientRequestErrorVerbosityLevel);
    }

    @Override
    public Set<String> getFeatures()
    {
        return FEATURES;
    }

    @Override
    public Response process(final Collection<Map.Entry<IndividualXacmlJaxbRequest, ? extends DecisionResult>> resultsByRequest)
    {
        System.out.println("#####################Inside process");
        if (resultsByRequest!=null){
            System.out.println(resultsByRequest.size());
        }else{
            System.out.println("#####################resultsByRequest is null!");
        }
        DecisionType combinedDecision = DecisionType.INDETERMINATE;
        for (final Map.Entry<? extends IndividualXacmlJaxbRequest, ? extends DecisionResult> resultEntry : resultsByRequest)
        {
            System.out.println("#####################resultEntry:"+resultEntry.getValue());
            final DecisionResult result = resultEntry.getValue();
            System.out.println("#####################getDecision:"+result.getDecision());
            if (result.getDecision() == DecisionType.INDETERMINATE)
            {
                // either all result must be indeterminate or we return Indeterminate as final result anyway
                return SIMPLE_INDETERMINATE_RESPONSE;
            }

            final ImmutableList<PepAction> pepActions = result.getPepActions();
            assert pepActions != null;

            if (!pepActions.isEmpty())
            {
                return SIMPLE_INDETERMINATE_RESPONSE;
            }

            final DecisionType individualDecision = result.getDecision();
            // if combinedDecision not initialized yet (indeterminate), set it to the result's decision
            if (combinedDecision == DecisionType.INDETERMINATE)
            {
                combinedDecision = individualDecision;
            } else
                // combinedDecision != Indeterminate
                if (individualDecision != combinedDecision)
                {
                    return SIMPLE_INDETERMINATE_RESPONSE;
                }
        }
        System.out.println("#####################Before CombinedDecision switch");
        try {
            System.out.printf("#####################process method!");
            //System.out.println(documentService.getIndividualHealthRoleByName("").toString());
        }catch(Exception ex){
            System.out.println("#####################process method err:"+ex.getCause());
        }

        switch (combinedDecision)
        {
            case PERMIT:
                return SIMPLE_PERMIT_RESPONSE;
            case DENY:
                return SIMPLE_DENY_RESPONSE;
            case NOT_APPLICABLE:
                return SIMPLE_NOT_APPLICABLE_RESPONSE;
            default:
                return SIMPLE_INDETERMINATE_RESPONSE;
        }
    }

    /**
     *
     * Factory for this type of result postprocessor filter that allows duplicate <Attribute> with same meta-data in the same <Attributes> element of a Request (complying with XACML 3.0
     * core spec, §7.3.3).
     *
     */
    public static final class Factory extends BaseXacmlJaxbResultPostprocessor.Factory
    {
        /**
         * ID of this {@link PdpExtension}
         */
        public static final String ID = "urn:ow2:authzforce:feature:pdp:result-postproc:xacml-json:default";

        /**
         * Constructor
         */
        public Factory()
        {
            super(ID);
        }

        @Override
        public DecisionResultPostprocessor<IndividualXacmlJaxbRequest, Response> getInstance(final int clientRequestErrorVerbosityLevel)
        {
            return new PostprocessorLoader(clientRequestErrorVerbosityLevel);
        }

    }
}

NOTE: Same thing happened when I placed jar file from maven artifactId=authzforce-ce-core-pdp-testutils to lib folder and tried to enable with recommended request body in above-mentioned link.

Body:
You are trying to enable the postprocessor with ID urn:ow2:authzforce:feature:pdp:result-postproc:xacml-json:default which is already reserved and provided by AuthzForce (for processing JSON response according to JSON Profile of XACML). Therefore, you can't use the same ID for your own implementation!

So change the ID in your code (just an example here, choose your own):

/**
  * ID of this {@link PdpExtension}
  */
public static final String ID = "my-own-postproc-id";

FYI, if all you need is the CombinedDecision feature for XACML/XML, as it seems so (but I may be wrong about what you are trying to achieve), this is already implemented by the class TestCombinedDecisionXacmlJaxbResultPostprocessor. You just have to deploy the authzforce-ce-core-pdp-testutils JAR in WEB-INF/lib (in same version as the authzforce-ce-core-pdp-engine JAR there), restart, and enable it like you did in step 3 but with the feature ID urn:ow2:authzforce:feature:pdp:result-postproc:xacml-xml:multiple:test-combined-decision.


问:
Insert React component into a String variable with html content
I need to insert a React component into a String variable that contains html content.
This variable will be render with dangerouslySetInnerHTML.

I replace my placeholder "!#ShareButton" with the content of my React component, but it renders [object Object] instead of the component itself

React component:

```<code>const ShareThis = ({ text }) => {
  return (
    <div class="one-line">{text}</div>
)}

export default ShareThis
</code>```

var content (string variable with html content)

```<code><p>Text 1</p>
!#ShareButton
<p>Text 2</p>
</code>```

Page:

```<code>const htmlcontent = content.replace(/!#ShareThis/g,
  <ShareThis
    text="Hello"
  />)

return (
  <div dangerouslySetInnerHTML={{ __html: htmlcontent }} />
)
</code>```

Result:

```<code>Text 1
[object Object]
Text 2
</code>```

Do you know how to insert a React component into a String variable with html content?

答:
Another possible alternative would be to use the utility React HTML Parser which can convert HTML strings into react components (JSX).

Building on the example provided by Dennis:

```<code>import React from "react";
import ReactHtmlParser from "react-html-parser";

const ShareThis = ({ text }) => {
  return `<div class="one-line">${text}</div>`;
};

const content = `
<p>Text 1</p>
!#ShareButton
<p>Text 2</p>
`;

const htmlcontent = content.replace(
  /!#ShareButton/g,
  ShareThis({ text: "Hello" })
);

export default function App() {
  return <div>{ReactHtmlParser(htmlcontent)}</div>;
}

</code>```

Working example

Body:
I need to insert a React component into a String variable that contains html content.
This variable will be render with dangerouslySetInnerHTML.

I replace my placeholder "!#ShareButton" with the content of my React component, but it renders [object Object] instead of the component itself

React component:

const ShareThis = ({ text }) => {
  return (

{text}

)}

export default ShareThis

var content (string variable with html content)

Text 1

!#ShareButton

Text 2

Page:

const htmlcontent = content.replace(/!#ShareThis/g,
  <ShareThis
    text="Hello"
  />)

return (

)

Result:

Text 1
[object Object]
Text 2

Do you know how to insert a React component into a String variable with html content?

Body:
Another possible alternative would be to use the utility React HTML Parser which can convert HTML strings into react components (JSX).

Building on the example provided by Dennis:

import React from "react";
import ReactHtmlParser from "react-html-parser";

const ShareThis = ({ text }) => {
  return `<div class="one-line">${text}</div>`;
};

const content = `
<p>Text 1</p>
!#ShareButton
<p>Text 2</p>
`;

const htmlcontent = content.replace(
  /!#ShareButton/g,
  ShareThis({ text: "Hello" })
);

export default function App() {
  return <div>{ReactHtmlParser(htmlcontent)}</div>;
}

Working example


问:
Create a joined Key-Value in LinqToSql
I have a GridView binded to LinqToSql-DataSource. The DataSource is Multiple-Join. I need unique Key-Values for the Grid. But all PrimaryKeys from the Tables could exist double or not because of left joins.

I have solved the problem in a pure sql-statement. There i create a ID for the TableRows by joining two PrimaryKeys an connecting with a "-". I need one of the IDs for later working with TableRows, the other could be null.

So I do in SQL-Statement:

```<code>select CAST(mitgliedschaft.id as varchar(MAX)) + '-' + CAST(ISNULL(funktion.id, '') as varchar(MAX)) as id from ...... inner join ...... etc
</code>```

I need the CASTS for not producing Calculating with the "-" and the ISNULL-Function because the second ID could be Null.

Now I have to transfer this part of the scenario into Linq-Statement. I tried like this:

...
...
select new
       {
           ...
           id = mitgliedschaft.id.ToString() + "-" + (funktion.id == null ? 0 : funktion.id).ToString()
           ...

       });```

But didn't get it running in that way. Can someone help me concatenating an ID with "-" and an ID that can be NULL? If it is NULL it should be an empty String or Null-Digit or whatever.

答:
got it now:

select new
{
  id = (mitgliedschaft.id.ToString() + "-") + (funktion.id.ToString() ?? "0")
}```

Title: Create a joined Key-Value in LinqToSql

Body:
I have a GridView binded to LinqToSql-DataSource. The DataSource is Multiple-Join. I need unique Key-Values for the Grid. But all PrimaryKeys from the Tables could exist double or not because of left joins.

I have solved the problem in a pure sql-statement. There i create a ID for the TableRows by joining two PrimaryKeys an connecting with a "-". I need one of the IDs for later working with TableRows, the other could be null.

So I do in SQL-Statement:

select CAST(mitgliedschaft.id as varchar(MAX)) + '-' + CAST(ISNULL(funktion.id, '') as varchar(MAX)) as id from ...... inner join ...... etc

I need the CASTS for not producing Calculating with the "-" and the ISNULL-Function because the second ID could be Null.

Now I have to transfer this part of the scenario into Linq-Statement. I tried like this:

...
...
select new
       {
           ...
           id = mitgliedschaft.id.ToString() + "-" + (funktion.id == null ? 0 : funktion.id).ToString()
           ...

       });

But didn't get it running in that way. Can someone help me concatenating an ID with "-" and an ID that can be NULL? If it is NULL it should be an empty String or Null-Digit or whatever.


问:
Julia: counting total number of elements in an array-of-arrays
Is there a single function in Julia that will give you the total number of elements in an array-of-arrays (or 'jagged array')?

Here's what I mean:

```<code>my_array_of_arrays = [ [1, 5], [6], [10, 10, 11] ]
</code>```

I'm looking for a function such that
desired_function(my_array_of_arrays) will return 6

And if not, what's the quickest way to do this in Julia?

Thanks in advance!

答:
One way to do it without additional dependencies would be to use sum:

```<code>julia> my_array_of_arrays = [ [1, 5], [6], [10, 10, 11] ]
3-element Array{Array{Int64,1},1}:
 [1, 5]
 [6]
 [10, 10, 11]

julia> sum(length, my_array_of_arrays)
6
</code>```

However, if you want to work more intensively with ragged arrays, you might be better off using specialized packages, such as ArraysOfArrays.jl.

Body:
Is there a single function in Julia that will give you the total number of elements in an array-of-arrays (or 'jagged array')?

Here's what I mean:

my_array_of_arrays = [ [1, 5], [6], [10, 10, 11] ]

I'm looking for a function such that
desired_function(my_array_of_arrays) will return 6

And if not, what's the quickest way to do this in Julia?

Thanks in advance!

Body:
One way to do it without additional dependencies would be to use sum:

julia> my_array_of_arrays = [ [1, 5], [6], [10, 10, 11] ]
3-element Array{Array{Int64,1},1}:
 [1, 5]
 [6]
 [10, 10, 11]

julia> sum(length, my_array_of_arrays)
6

However, if you want to work more intensively with ragged arrays, you might be better off using specialized packages, such as ArraysOfArrays.jl.


问:
how to send post type request without parameter using python requests
I have method on swagger "Login" that accept this json:

```<code>{ "login": "string", "password": "string", "supplierId": 0 }
</code>```

I need to send request using request module in Python:

1) First without login attribute

```<code>{"login": , "password": "user_password", "supplierId": "user_supplierId"}
</code>```

2) With login attribute but without brackets

```<code>{"login": asd, "password": "user_password", "supplierId": "user_supplierId"}
</code>```

can someone help me ?

答:
Since you have the method that accepts json as: { "login": "string", "password": "string", "supplierId": 0 }.

You will probably have to send a string as a value to login variable. You can try passing an empty string "" if you don't want to send a login value.

Body:
I have method on swagger "Login" that accept this json:

{ "login": "string", "password": "string", "supplierId": 0 }

I need to send request using request module in Python:

1) First without login attribute

{"login": , "password": "user_password", "supplierId": "user_supplierId"}

2) With login attribute but without brackets

{"login": asd, "password": "user_password", "supplierId": "user_supplierId"}

can someone help me ?


问:
Handling file access locks while file is being built
I have a [SQL 2008] SSIS package that takes a CSV text file and moves it to a separate folder.  Once it is in this folder, I import the data to SQL.  The text file is being automatically generated by an outside program on a periodic schedule.  The file is also pretty large, so it takes a while (~10 minutes) for it to be generated.

If I attempt to move this file (using a File System Task) WHILE the file is still being built, I get this error message:

"The process cannot access the file because it is being used by another process."

Which makes sense, since it can't move a file that is being accessed elsewhere.  Back in DTS I wrote some custom script to check for a period of XX seconds to see if the file size had increased, but I was wondering how to handle this properly in SSIS.  Surely there is a better way to determine if a file has locks on it before doing file operations.

I would greatly appreciate any suggestions or comments!  Thank you.

答:
Probably, you have found an answer to your question by now. This is for others who might stumble upon this question.

To achieve the functionality that you have described in your question, you can use the File Watcher Task that is available for free download from the website SQLIS.com.Click the link to visit File Watcher Task download page.

Hope that helps.

ContentLicense: CC BY-SA 2.5