问:
Refresh header component after login
My application uses identity server and I'm storing the user's name in a session variable once redirected back.

The name is not displaying, it will only if I refresh the page. How can correct this?

```<code>import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { environment } from '../../environments/environment';

@Component({
  selector: "app-header",
  templateUrl: "./header.component.html",
  styleUrls: ["./header.component.css"]
})
export class HeaderComponent implements OnInit {
  navLinks: any[];
  activeLinkIndex = -1;
  displayName: string;
  logoutUrl: string;

  constructor(private router: Router) {
    this.navLinks = [
      {
        label: "Projects",
        link: "project-list",
        index: 0
      }
    ];
  }
  ngOnInit(): void {
    this.router.events.subscribe(res => {
      this.activeLinkIndex = this.navLinks.indexOf(
        this.navLinks.find(tab => tab.link === "." + this.router.url)
      );
    });

    this.displayName = sessionStorage.getItem("displayName");
    this.logoutUrl = environment.oidc_post_logout_redirect_uri;
  }
}

<button mat-button [matMenuTriggerFor]="menu">{{ displayName }}</button>
</code>```

答:
You haven't said how you are performing the login, so for the purposes of this answer I'm going to assume you're making a call in a service called loginService.

You could create a subject in your login service that emits a value every time the authentication status changes. Every time the user logs in or out, the login service would emit a new value informing subscribers of the new status.

All interested components, such as the header component, can subscribe to that subject to receive updates about the login status.

login service

```<code>// I am using a replay subject here to ensure new subscribers get the current status
private loggedIn: Subject<boolean> = new ReplaySubject<boolean>(1);

login(): Observable<boolean> {
  // TODO: set up http request
  return this.http.post(loginUrl, body).pipe(
    tap(() => this.loggedIn.next(true)
  );
}

logout(): Observable<boolean> {
  return this.http.post(loginUrl, body).pipe(
    tap(() => this.loggedIn.next(false)
  );
}

loginStatusChange(): Observable<boolean> {
  return this.loggedIn.asObservable();
}
</code>```

header component

```<code>ngOnInit(): void {
  this.loginService.loginStatusChange().subscribe(loggedIn => {
    // TODO: apply logic based on logged in status
  });
}
</code>```

This is very simplistic, and only focusses on the aspect of the design pattern. I have ignored the kind of implementation detail that you would normally add, such as error handling and unsubscribing from the subject.

Title: Refresh header component after login

Body:
My application uses identity server and I'm storing the user's name in a session variable once redirected back.

The name is not displaying, it will only if I refresh the page. How can correct this?

import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { environment } from '../../environments/environment';

@Component({
  selector: "app-header",
  templateUrl: "./header.component.html",
  styleUrls: ["./header.component.css"]
})
export class HeaderComponent implements OnInit {
  navLinks: any[];
  activeLinkIndex = -1;
  displayName: string;
  logoutUrl: string;

  constructor(private router: Router) {
    this.navLinks = [
      {
        label: "Projects",
        link: "project-list",
        index: 0
      }
    ];
  }
  ngOnInit(): void {
    this.router.events.subscribe(res => {
      this.activeLinkIndex = this.navLinks.indexOf(
        this.navLinks.find(tab => tab.link === "." + this.router.url)
      );
    });

    this.displayName = sessionStorage.getItem("displayName");
    this.logoutUrl = environment.oidc_post_logout_redirect_uri;
  }
}

<button mat-button [matMenuTriggerFor]="menu">{{ displayName }}</button>

Body:
You haven't said how you are performing the login, so for the purposes of this answer I'm going to assume you're making a call in a service called loginService.

You could create a subject in your login service that emits a value every time the authentication status changes. Every time the user logs in or out, the login service would emit a new value informing subscribers of the new status.

All interested components, such as the header component, can subscribe to that subject to receive updates about the login status.

login service

// I am using a replay subject here to ensure new subscribers get the current status
private loggedIn: Subject<boolean> = new ReplaySubject<boolean>(1);

login(): Observable<boolean> {
  // TODO: set up http request
  return this.http.post(loginUrl, body).pipe(
    tap(() => this.loggedIn.next(true)
  );
}

logout(): Observable<boolean> {
  return this.http.post(loginUrl, body).pipe(
    tap(() => this.loggedIn.next(false)
  );
}

loginStatusChange(): Observable<boolean> {
  return this.loggedIn.asObservable();
}

header component

ngOnInit(): void {
  this.loginService.loginStatusChange().subscribe(loggedIn => {
    // TODO: apply logic based on logged in status
  });
}

This is very simplistic, and only focusses on the aspect of the design pattern. I have ignored the kind of implementation detail that you would normally add, such as error handling and unsubscribing from the subject.


来源: stackexchange

问:
Understand combination of array with math formula Variable
I am new to JavaScript arrays and using formulas with components of an array hence I am finding it difficult to understand this code that I should apply in a web application.
The last line of code specifically at arrayNames[(Math.round(formulae))]  is where I don't have a clue of what it means. Please help me devs.

```<code><script>
let formulae = ( ((century/4) -2*century-1) + ((5*year/4)) + ((26*(month+1)/10))+day ) % 7;
let arrayNames =["Akosua","Adwoa","Abenaa","Akua","Yaa","Afua","Ama"];
let newArrayNames = arrayNames[(Math.round(formulae))] ;
</script>
</code>```

答:
Firstly you compute some number, which is depends on the centure, year, month and day. They all stored in the variables centure, year, month and day. This number will be the index of your future array.

let formulae = ( ((century/4) -2*century-1) + ((5*year/4)) + ((26*(month+1)/10))+day ) % 7;

Then you create this array:

let arrayNames =["Akosua","Adwoa","Abenaa","Akua","Yaa","Afua","Ama"];

Finally, you just get element from the array. As you remember formulae is index of the needle element. So now, I hope, this string is obvious:

let newArrayNames = arrayNames[(Math.round(formulae))] ;

ContentLicense: CC BY-SA 4.0


问:
Forbidden 403 You don't have permission to access this resource. (mod_wsgi, wamp, apache2.4, django) on windows
i have installed everything properly and gone through all solutions related to this subject but still error remains, I'm new to Django and i would really appreciate your help

I get this error in my error log file:

[Fri Feb 14 21:52:16.916422 2020] [authz_core:error] [pid 4288:tid 1252] [client ::1:51391] AH01630: client denied by server configuration: E:/AppSource/eCommerce/src/ecommerce/wsgi_windows.py

and when i try to reach 127.0.0.1:80 i get: Forbidden 403

and this is my wsgi_windows.py configuration:

```<code>activate_this = 'CE:/AppSource/eCommerce/Scripts/activate_this.py'
exec(open(activate_this).read(),dict(__file__=activate_this))
import os
import sys
import site
from django.core.wsgi import get_wsgi_application
site.addsitedir("C:/Python37/Lib/site-packages")
sys.path.append('E:/AppSource/eCommerce')
sys.path.append('E:/AppSource/eCommerce/src')
sys.path.append('E:/AppSource/eCommerce/src/ecommerce')
os.environ['DJANGO_SETTINGS_MODULE'] = 'ecommerce.settings'
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ecommerce.settings")
application = get_wsgi_application()
</code>```

and this is hhtpd-vhosts.conf configuration:

```<code><VirtualHost *:80>
    ServerName localhost
    WSGIPassAuthorization On
    ErrorLog "E:/appSource/eCommerce/eCommerce.error.log"
    CustomLog "E:/appSource/eCommerce/eCommerce.access.log" combined
    WSGIScriptAlias /  "E:/appSource/eCommerce/src/ecommerce/wsgi_windows.py"
    <Directory "E:/appSource/eCommerc/src/ecommerce/">
        <Files wsgi_windows.py>
            Require all granted
        </Files>
    </Directory>
 Alias /static "E:/appSource/eCommerce/static_cdn/static_root"

    <Directory "E:/appSource/eCommerce/static_cdn/static_root">
        Require all granted
    </Directory>

    Alias /media "E:/appSource/eCommerce/static_cdn/media_root"
    <Directory "E:/appSource/eCommerce/static_cdn/media_root">
        Require all granted
    </Directory>
</VirtualHost>
</code>```

i have tried everything that i know
Please help to solve this
Thanks

答: I think the easiest way to achieve your goal is to change the port number of apache and start the apache again.</p>

Body:
i have installed everything properly and gone through all solutions related to this subject but still error remains, I'm new to Django and i would really appreciate your help

I get this error in my error log file:

[Fri Feb 14 21:52:16.916422 2020] [authz_core:error] [pid 4288:tid 1252] [client ::1:51391] AH01630: client denied by server configuration: E:/AppSource/eCommerce/src/ecommerce/wsgi_windows.py

and when i try to reach 127.0.0.1:80 i get: Forbidden 403

and this is my wsgi_windows.py configuration:

activate_this = 'CE:/AppSource/eCommerce/Scripts/activate_this.py'
exec(open(activate_this).read(),dict(__file__=activate_this))
import os
import sys
import site
from django.core.wsgi import get_wsgi_application
site.addsitedir("C:/Python37/Lib/site-packages")
sys.path.append('E:/AppSource/eCommerce')
sys.path.append('E:/AppSource/eCommerce/src')
sys.path.append('E:/AppSource/eCommerce/src/ecommerce')
os.environ['DJANGO_SETTINGS_MODULE'] = 'ecommerce.settings'
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ecommerce.settings")
application = get_wsgi_application()

and this is hhtpd-vhosts.conf configuration:

<VirtualHost *:80>
    ServerName localhost
    WSGIPassAuthorization On
    ErrorLog "E:/appSource/eCommerce/eCommerce.error.log"
    CustomLog "E:/appSource/eCommerce/eCommerce.access.log" combined
    WSGIScriptAlias /  "E:/appSource/eCommerce/src/ecommerce/wsgi_windows.py"
    <Directory "E:/appSource/eCommerc/src/ecommerce/">
        <Files wsgi_windows.py>
            Require all granted
        </Files>
    </Directory>
 Alias /static "E:/appSource/eCommerce/static_cdn/static_root"

    <Directory "E:/appSource/eCommerce/static_cdn/static_root">
        Require all granted
    </Directory>

    Alias /media "E:/appSource/eCommerce/static_cdn/media_root"
    <Directory "E:/appSource/eCommerce/static_cdn/media_root">
        Require all granted
    </Directory>
</VirtualHost>

i have tried everything that i know
Please help to solve this
Thanks


问:
How to automatically include some where conditions in rails model?
I have several models with office_id, fiscal_year_id attributes. I want these field to automatically set before querying. So, I don't have to care about data overlapping from one office to another and one fiscal year to another.

答:
ActiveSuppport::CurrentAttributes provides what you need.

See docs here.


问:
Differential AJAX updates for HTML table?
I have a game that's based on a 25x20 HTML table (the game board). Every 3 seconds the user can "move," which sends an AJAX request to the server, at which time the server rerenders the entire HTML table and sends it to the user.

This was easy to write, but it wastes a lot of bandwidth. Are there any libraries, client (preferably jquery) or server-side, that help send differential instead of full updates for large tables? Usually only 5-10 tiles change on a given reload, so I feel like I could cut bandwidth use by an order of magnitude by sending just those tiles instead of all 500 every 3 seconds.

I'm also open to "you idiot, why are you using HTML tables"-type comments if you can suggest a better alternative. For example are there any CSS/DOM manipulation techniques I should be considering instead of using an HTML table? Should I use a table but give each td coordinates for an id (like "12x08") and then use jquery to replace cells by id?

A clarification: the tiles are text, not images.

答:
If you known the state between refreshes on the server side (see comment on question), you an send the data using JSON like so (not sure about exact syntax):

```<code>[
    { x: 3, y: 5, class: "asdf", content: "1234" },
    { x: 6, y: 5, class: "asdf", content: "8156" },
    { x: 2, y: 2, class: "qwer", content: "1337" }
]
</code>```

Compact that (remove extra whitespace, etc.), gzip it, and send it to your Javascript.  Surprisingly, the Javascript code to read this isn't that complicated (simply DOM manipulations).

OwnerDisplayName: Brandon

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Brandon

Body:
If you known the state between refreshes on the server side (see comment on question), you an send the data using JSON like so (not sure about exact syntax):

[
    { x: 3, y: 5, class: "asdf", content: "1234" },
    { x: 6, y: 5, class: "asdf", content: "8156" },
    { x: 2, y: 2, class: "qwer", content: "1337" }
]

Compact that (remove extra whitespace, etc.), gzip it, and send it to your Javascript.  Surprisingly, the Javascript code to read this isn't that complicated (simply DOM manipulations).

OwnerDisplayName: strager

ContentLicense: CC BY-SA 2.5


问:
How to download 300k log lines from my application?
I am running a job on my Heroku app that generates about 300k lines of log within 5 minutes. I need to extract all of them into a file. How can I do this?

The Heroku UI only shows logs in real time, since the moment it was opened, and only keeps 10k lines.

I attached a LogDNA Add-on as a drain, but their export also only allows 10k lines export. To even have the option of export, I need to apply a search filter (I typed 2020 because all the lines start with a date, but still...). I can scroll through all the logs to see them, but as I scroll up the bottom gets truncated, so I can't even copy-paste them myself.

I then attached Sumo Logic as a drain, which is better, because the export limit is 100k. However I still need to filter the logs in 30s to 60s intervals and download separately. Also it exports to CSV file and in reverse order (newest first, not what I want) so I have to still work on the file after its downloaded.

Is there no option to get actual raw log files in full?

答:
Speaking solely from the Sumo Logic point of view, since that’s the only one I’m familiar with here, you could do this with its Search Job API: https://help.sumologic.com/APIs/Search-Job-API/About-the-Search-Job-API

The Search Job API lets you kick off a search, poll it for status, and then when complete, page through the results (up to 1M records, I believe) and do whatever you want with them, such as dumping them into a CSV file.

But this is only available to trial and Enterprise accounts.

I just looked at Heroku’s docs and it does not look like they have a native way to retrieve more than 1500 and you do have to forward those logs via syslog to a separate server / service.

I think your best solution is going to depend, however, on your use-case, such as why specifically you need these logs in a CSV.


问:
Removing help_text from Django UserCreateForm
Probably a poor question, but I'm using Django's UserCreationForm (slightly modified to include email), and I would like to remove the help_text that Django automatically displays on the HTML page.

On the Register portion of my HTML page, it has the Username, Email, Password1 & Password 2 fields. But underneath Username is "Required. 30 characters or fewer. Letters, digits, and @... only." And under Password Confirmation (Password 2), it says "Enter the same password as above for verification."

How do I remove these?

```<code>#models.py
class UserCreateForm(UserCreationForm):
    email = forms.EmailField(required=True)

    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        if commit:
            user.save()
        return user

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")
        exclude = ('username.help_text')

#views.py
def index(request):
    r = Movie.objects.all().order_by('-pub_date')
    form = UserCreateForm()
    return render_to_response('qanda/index.html', {'latest_movie_list': r, 'form':form},     context_instance = RequestContext(request))

#index.html
<form action = "/home/register/" method = "post" id = "register">{% csrf_token %}
    <h6> Create an account </h6>
    {{ form.as_p }}
    <input type = "submit" value = "Create!">
    <input type = "hidden" name = "next" value = "{{ next|escape }}" />
</form>
</code>```

答:
Just go to UserCreationForm and make the required changes.

very simple hold control button on your keyboard and ckick on UserCreationForm you will get the UserCreationForm make the required changes as per your need and save it. as i did it for me in the below example i commented the Help Content.

```<code>  error_messages = {
    'password_mismatch': _("The two password fields didn't match."),
}
password1 = forms.CharField(
    label=_("Password"),
    strip=False,
    widget=forms.PasswordInput,
    # help_text=password_validation.password_validators_help_text_html(),
)
password2 = forms.CharField(
    label=_("Password confirmation"),
    widget=forms.PasswordInput,
    strip=False,
    help_text=_("Enter the same password as before, for verification."),
)
</code>```

Body:
Probably a poor question, but I'm using Django's UserCreationForm (slightly modified to include email), and I would like to remove the help_text that Django automatically displays on the HTML page.

On the Register portion of my HTML page, it has the Username, Email, Password1 & Password 2 fields. But underneath Username is "Required. 30 characters or fewer. Letters, digits, and @... only." And under Password Confirmation (Password 2), it says "Enter the same password as above for verification."

How do I remove these?

#models.py
class UserCreateForm(UserCreationForm):
    email = forms.EmailField(required=True)

    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        if commit:
            user.save()
        return user

    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")
        exclude = ('username.help_text')

#views.py
def index(request):
    r = Movie.objects.all().order_by('-pub_date')
    form = UserCreateForm()
    return render_to_response('qanda/index.html', {'latest_movie_list': r, 'form':form},     context_instance = RequestContext(request))

#index.html
<form action = "/home/register/" method = "post" id = "register">{% csrf_token %}

 Create an account

    {{ form.as_p }}
    <input type = "submit" value = "Create!">
    <input type = "hidden" name = "next" value = "{{ next|escape }}" />
</form>

Body:
Just go to UserCreationForm and make the required changes.

very simple hold control button on your keyboard and ckick on UserCreationForm you will get the UserCreationForm make the required changes as per your need and save it. as i did it for me in the below example i commented the Help Content.

  error_messages = {
    'password_mismatch': _("The two password fields didn't match."),
}
password1 = forms.CharField(
    label=_("Password"),
    strip=False,
    widget=forms.PasswordInput,
    # help_text=password_validation.password_validators_help_text_html(),
)
password2 = forms.CharField(
    label=_("Password confirmation"),
    widget=forms.PasswordInput,
    strip=False,
    help_text=_("Enter the same password as before, for verification."),
)


问:
Add 0 padding to a pointer address
Basically I have a hard coded address in decimal value, and I would like to convert that to a pointer, I have been following this link

But I am not getting it to run as I believe my address is being truncated i.e. the 0's in the address are being removed.

Is there any how I can maintain the 0's or is there a way where I can type cast my address stored in buff to a pointer?

```<code>#include <stdio.h>
#include <stdint.h>

int main(int argc, char *argv[]) {
    int address = 200000000;
    char buff[80];
    sprintf(buff, "0x%012x", address);
    printf("%s\n", buff);

    uint32_t * const Value = (uint32_t *)(uintptr_t)buff;
    // *Value = 10;

    printf("%p\n", Value); // Value is now storing the value of the variable buff, I dont want this

    uint32_t *const Value2 = (uint32_t *)(uintptr_t)0x00000bebc200;

    printf("%p\n", Value2); // my address gets truncated, dont want the address to be truncated
}
</code>```

答:
It is not necessary to prevent the truncation of your pointer.

When compiling for 64bit, your pointer will be 64 bit big.
This means it holds a number like 0x0123456789ABCDEF.

However, the output formatter %p will drop any leading 0, as they do not change the behaviour of your programm. It is like comparing 0x42==0x0042.

You do not need to convert your address to hex in order to use it as a pointer.

A computer saves your address in binary format. In memory, your address 200000000 will be saved as 0b1011111010111100001000000000.

The output format of decimal and hexadecimal is only used to make it more comfortable for humans to read the output.

The computer does not care, if you supply decimal, hexadecimal or binary numbers, in-memory it will always work with binary representation.

This means that you can directly follow the advice of your linked answer

```<code>#include <inttypes.h> // defines PRIxPTR, see comments of @chqrlie and @JonathanLeffler

uintptr_t address= 200000000; // compiler makes sure to convert this to binary for the pc
uint32_t *Pointer = (uint32_t*) address;

printf("0x%" PRIxPTR " address\n", address); // if the ptr size is known, e.g. %lx can be used
printf("%p pointer\n", Pointer);
</code>```

sprintf converts your number into an ascii string and saves that to buff. That means you cannot cast the content of buff to get back the number. You would need to to an string to int or string to hex conversion before.

Edit:

You can test the conversion of your compiler by printing the following compare statements

```<code> printf("%d\n", address == 200000000); // output true
 printf("%d\n", address == 0xbebc200); // output true
 printf("%d\n", address == 0x00000bebc200); // output true
 printf("%d\n", address == 0b1011111010111100001000000000); // output true
</code>```

Title: Add 0 padding to a pointer address

Body:
Basically I have a hard coded address in decimal value, and I would like to convert that to a pointer, I have been following this link

But I am not getting it to run as I believe my address is being truncated i.e. the 0's in the address are being removed.

Is there any how I can maintain the 0's or is there a way where I can type cast my address stored in buff to a pointer?

#include <stdio.h>
#include <stdint.h>

int main(int argc, char *argv[]) {
    int address = 200000000;
    char buff[80];
    sprintf(buff, "0x%012x", address);
    printf("%s\n", buff);

    uint32_t * const Value = (uint32_t *)(uintptr_t)buff;
    // *Value = 10;

    printf("%p\n", Value); // Value is now storing the value of the variable buff, I dont want this

    uint32_t *const Value2 = (uint32_t *)(uintptr_t)0x00000bebc200;

    printf("%p\n", Value2); // my address gets truncated, dont want the address to be truncated
}

Body:
It is not necessary to prevent the truncation of your pointer.

When compiling for 64bit, your pointer will be 64 bit big.
This means it holds a number like 0x0123456789ABCDEF.

However, the output formatter %p will drop any leading 0, as they do not change the behaviour of your programm. It is like comparing 0x42==0x0042.

You do not need to convert your address to hex in order to use it as a pointer.

A computer saves your address in binary format. In memory, your address 200000000 will be saved as 0b1011111010111100001000000000.

The output format of decimal and hexadecimal is only used to make it more comfortable for humans to read the output.

The computer does not care, if you supply decimal, hexadecimal or binary numbers, in-memory it will always work with binary representation.

This means that you can directly follow the advice of your linked answer

#include <inttypes.h> // defines PRIxPTR, see comments of @chqrlie and @JonathanLeffler

uintptr_t address= 200000000; // compiler makes sure to convert this to binary for the pc
uint32_t *Pointer = (uint32_t*) address;

printf("0x%" PRIxPTR " address\n", address); // if the ptr size is known, e.g. %lx can be used
printf("%p pointer\n", Pointer);

sprintf converts your number into an ascii string and saves that to buff. That means you cannot cast the content of buff to get back the number. You would need to to an string to int or string to hex conversion before.

Edit:

You can test the conversion of your compiler by printing the following compare statements

 printf("%d\n", address == 200000000); // output true
 printf("%d\n", address == 0xbebc200); // output true
 printf("%d\n", address == 0x00000bebc200); // output true
 printf("%d\n", address == 0b1011111010111100001000000000); // output true


问:
Pass string class variable by reference in C++
Look at the following code:

```<code>#include <iostream>
#include <string>
using namespace std;
void reverseStr(string arr, int start, int end)
{
    while (start < end)
    {
        swap(arr[start], arr[end]);
        ++start;
        --end;
    }
}
int main()
{
    string str = "CPP";
    reverseStr(str, 0, 3);
    cout << str;
    return 0;
}
</code>```

The output is CPP, while PCC is expected.

Question: How to pass string by reference in C++? Are strings a normal array? If yes then the reference must be passed automatically, while it just creates a copy in the formal parameters.

My question is that why I have to use my function like void reverseStr(string &arr, int start, int end) instead of just void reverseStr(string arr, int start, int end). Why I have to use extra & informal parameters? Aren't string variables just other arrays?

答:
Reference with & in function parameter, this means you pass a reference to the string you initialize in the main function. Without & you will just be passing a copy and the changes you make in the copy don't reflect in the original.

Also the call should be:

```<code>reverseStr(str, 0, 2);
</code>```

Range 0 to 2, or better yet:

```<code>reverseStr(str, 0, str.size() - 1);
</code>```

As you can see by the use of .size() method, an std::string is not a char array, it's a typedef of the class template std::basic_string<char>.

Learn more about what C++ string type is in https://pt.cppreference.com/w/cpp/string

Body:
Look at the following code:

#include <iostream>
#include <string>
using namespace std;
void reverseStr(string arr, int start, int end)
{
    while (start < end)
    {
        swap(arr[start], arr[end]);
        ++start;
        --end;
    }
}
int main()
{
    string str = "CPP";
    reverseStr(str, 0, 3);
    cout << str;
    return 0;
}

The output is CPP, while PCC is expected.

Question: How to pass string by reference in C++? Are strings a normal array? If yes then the reference must be passed automatically, while it just creates a copy in the formal parameters.

My question is that why I have to use my function like void reverseStr(string &arr, int start, int end) instead of just void reverseStr(string arr, int start, int end). Why I have to use extra & informal parameters? Aren't string variables just other arrays?

Body:
Reference with & in function parameter, this means you pass a reference to the string you initialize in the main function. Without & you will just be passing a copy and the changes you make in the copy don't reflect in the original.

Also the call should be:

reverseStr(str, 0, 2);

Range 0 to 2, or better yet:

reverseStr(str, 0, str.size() - 1);

As you can see by the use of .size() method, an std::string is not a char array, it's a typedef of the class template std::basic_string<char>.

Learn more about what C++ string type is in https://pt.cppreference.com/w/cpp/string


问:
Rust embedded application is not linked correctly under AArch64 system
I'm trying to compile and debug an embedded rust application for stm32f0 using an ARM system as host.
The application already compiles and works under an Intel installation.

I am running on a Pinebook Pro, powered by a Quad Cortex-A53, 64-bit CPU. The OS is a 64-bit version of Debian:

```<code>$ uname -a
Linux pinebook 4.4.196 #1 SMP Tue Oct 15 16:54:21 EDT 2019 aarch64 GNU/Linux
</code>```

I installed rust and cargo with rustup for AArch64 (channel stable):

```<code>$ rustc --version
rustc 1.39.0 (4560ea788 2019-11-04)
$ cargo --version
cargo 1.39.0 (1c6ec66d5 2019-09-30)
</code>```

As per this issue I found out that rust-lld is not distributed in binary form for ARM systems, so I had to compile it from sources:

```<code>$ ld.lld --version
LLD 10.0.0 (https://github.com/llvm/llvm-project.git 1c247dd028b368875bc36cd2a9ccc7fd90507776) (compatible with GNU linkers)
</code>```

Now the compilation process completes without issues:

```<code>export RUSTFLAGS="-C linker=ld.lld"
cargo build
</code>```

However the resulting elf file seems to be linked incorrectly: trying to load it with gdb through openocd results in some kind of silent failure:

```<code>(gdb) target remote :3333
Remote debugging using :3333
0x00000000 in ?? ()
(gdb) load
Start address 0x0, load size 0
Transfer rate: 0 bits in <1 sec.
(gdb)
</code>```

The load size is empty, so no new program is flashed. In contrast, when using the elf compiled in my Intel system (with openocd still running on the arm laptop) everything works as expected:

```<code>(gdb) target remote 192.168.1.153:3333
Remote debugging using 192.168.1.153:3333
0x00000000 in ?? ()
(gdb) load
Loading section .vector_table, size 0xc0 lma 0x8000000
Loading section .text, size 0x686e lma 0x80000c0
Loading section .rodata, size 0x4a0 lma 0x8006940
Start address 0x8005b58, load size 28110
Transfer rate: 19 KB/sec, 7027 bytes/write.
(gdb)
</code>```

It would seems like the elf is not linked correctly. Running readelf -l highlights that on my ARM system the entry point set is 0x0, which is wrong for the stm32f0.
This is readelf on my ARM laptop:

```<code>lf file type is EXEC (Executable file)
Entry point 0x0
There are 3 program headers, starting at offset 52

Program Headers:
  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
  PHDR           0x000034 0x00010034 0x00010034 0x00060 0x00060 R   0x4
  LOAD           0x000000 0x00010000 0x00010000 0x00094 0x00094 R   0x1000
  GNU_STACK      0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0

 Section to Segment mapping:
  Segment Sections...
   00
   01
   02
</code>```

While this is from the elf that works, compiled under my Intel system:

```<code>Elf file type is EXEC (Executable file)
Entry point 0x8005b59
There are 3 program headers, starting at offset 52

Program Headers:
  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
  LOAD           0x001000 0x08000000 0x08000000 0x06de0 0x06de0 R E 0x1000
  LOAD           0x007de0 0x20000000 0x08006de0 0x00000 0x00028 RW  0x1000
  GNU_STACK      0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0

 Section to Segment mapping:
  Segment Sections...
   00     .vector_table .text .rodata
   01     .data .bss
   02
</code>```

I'm not sure if this has something to do with the target architecture being the same as the host (thus using the linux userland linking) or simple because arm systems are less supported.

Can anyone point me in the right direction?

答:
I was correct in assuming there was a problem with the linker, and there are a couple of solutions.

Since two years ago Rust uses LLD as the default linker for the ARM architecture (https://rust-embedded.github.io/blog/2018-08-2x-psa-cortex-m-breakage/). Unfortunately rust-lld itself is not distributed in binary form for the ARM platforms (ironic, isn't it?), so I had to compile it from source and specify it via command line.

Exporting the RUSTFLAGS variable works but overwrites its default value defined in .cargo/config, which would include also the directive for the linker script (-C link-arg=-Tlink.x). In short I was convinced of using the correct linker script because it was listed in .cargo/config, but the RUSTFLAGS env variable was removing it.

The solution is to either

include the linker script explicitly when exporting RUSTFLAGS:
export RUSTFLAGS="-C linker=ldd -C link-arg=-Tlink.x"

specify "-C",  "linker=lld" as a rust flag in the .cargo/config file with the other options

Enable the old linker (arm-none-eabi-ld) which is more easily retrievable by uncommenting the following line in .cargo/config: "-C", "linker=arm-none-eabi-gcc"

Body:
I'm trying to compile and debug an embedded rust application for stm32f0 using an ARM system as host.
The application already compiles and works under an Intel installation.

I am running on a Pinebook Pro, powered by a Quad Cortex-A53, 64-bit CPU. The OS is a 64-bit version of Debian:

$ uname -a
Linux pinebook 4.4.196 #1 SMP Tue Oct 15 16:54:21 EDT 2019 aarch64 GNU/Linux

I installed rust and cargo with rustup for AArch64 (channel stable):

$ rustc --version
rustc 1.39.0 (4560ea788 2019-11-04)
$ cargo --version
cargo 1.39.0 (1c6ec66d5 2019-09-30)

As per this issue I found out that rust-lld is not distributed in binary form for ARM systems, so I had to compile it from sources:

$ ld.lld --version
LLD 10.0.0 (https://github.com/llvm/llvm-project.git 1c247dd028b368875bc36cd2a9ccc7fd90507776) (compatible with GNU linkers)

Now the compilation process completes without issues:

export RUSTFLAGS="-C linker=ld.lld"
cargo build

However the resulting elf file seems to be linked incorrectly: trying to load it with gdb through openocd results in some kind of silent failure:

(gdb) target remote :3333
Remote debugging using :3333
0x00000000 in ?? ()
(gdb) load
Start address 0x0, load size 0
Transfer rate: 0 bits in <1 sec.
(gdb)

The load size is empty, so no new program is flashed. In contrast, when using the elf compiled in my Intel system (with openocd still running on the arm laptop) everything works as expected:

(gdb) target remote 192.168.1.153:3333
Remote debugging using 192.168.1.153:3333
0x00000000 in ?? ()
(gdb) load
Loading section .vector_table, size 0xc0 lma 0x8000000
Loading section .text, size 0x686e lma 0x80000c0
Loading section .rodata, size 0x4a0 lma 0x8006940
Start address 0x8005b58, load size 28110
Transfer rate: 19 KB/sec, 7027 bytes/write.
(gdb)

It would seems like the elf is not linked correctly. Running readelf -l highlights that on my ARM system the entry point set is 0x0, which is wrong for the stm32f0.
This is readelf on my ARM laptop:

lf file type is EXEC (Executable file)
Entry point 0x0
There are 3 program headers, starting at offset 52

Program Headers:
  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
  PHDR           0x000034 0x00010034 0x00010034 0x00060 0x00060 R   0x4
  LOAD           0x000000 0x00010000 0x00010000 0x00094 0x00094 R   0x1000
  GNU_STACK      0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0

 Section to Segment mapping:
  Segment Sections...
   00
   01
   02

While this is from the elf that works, compiled under my Intel system:

Elf file type is EXEC (Executable file)
Entry point 0x8005b59
There are 3 program headers, starting at offset 52

Program Headers:
  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
  LOAD           0x001000 0x08000000 0x08000000 0x06de0 0x06de0 R E 0x1000
  LOAD           0x007de0 0x20000000 0x08006de0 0x00000 0x00028 RW  0x1000
  GNU_STACK      0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0

 Section to Segment mapping:
  Segment Sections...
   00     .vector_table .text .rodata
   01     .data .bss
   02

I'm not sure if this has something to do with the target architecture being the same as the host (thus using the linux userland linking) or simple because arm systems are less supported.

Can anyone point me in the right direction?


问:
string variables in C++
OK, I know that string is a class in C++. Now if I declare an instance somewhat like string str. Is it an array of characters terminated by \0 character only or something is different from regular array of characters?

答:
A char array is simply a static allocation of memory on the stack with a char data type.
However, Here str is the object of std::string class which is an instantiation of the basic_string class template that uses char (i.e., bytes) as its character type.

Do not use cstring or string.h functions when you are declaring string with std::string keyword because std::string strings are of basic_string class type and cstring strings are of const char* type.

See the following links for more help:
char* vs std:string vs char[] in C++ & Difference between string and char[] types in C++.

Title: string variables in C++


问:
VBA ADO Parametrize LIKE Query
I've looked around but can't seem to find a solution to parametrize a query in VBA using ADO.

I'm looking to achieve something like:

```<code>.CommandText = "SELECT * FROM table WHERE F_Name LIKE '%?%'"
.Parameters.Append .CreateParameter("p1", adVarChar, adInputParam, 255, strFname)
</code>```

Could anyone help with how to apply append a parameter in the above manor?

答:
```<code>.CommandText = "SELECT * FROM table WHERE F_Name LIKE ?"
.Parameters.Append .CreateParameter("p1", adVarChar, adInputParam, 255, "%" + strFname + "%")
</code>```

works for me (without ')

Title: VBA ADO Parametrize LIKE Query

Body:
I've looked around but can't seem to find a solution to parametrize a query in VBA using ADO.

I'm looking to achieve something like:

.CommandText = "SELECT * FROM table WHERE F_Name LIKE '%?%'"
.Parameters.Append .CreateParameter("p1", adVarChar, adInputParam, 255, strFname)

Could anyone help with how to apply append a parameter in the above manor?

Body:
.CommandText = "SELECT * FROM table WHERE F_Name LIKE ?"
.Parameters.Append .CreateParameter("p1", adVarChar, adInputParam, 255, "%" + strFname + "%")

works for me (without ')


问:
Converting a Java Web Application to .Net
What is the process involved with converting a Java web application to something like ASP.NET with Silverlight or alike?

I know many Java frameworks have been proted to .Net (either C# or VB.NET), but haven't really seen many web applications done. (I might be very wrong here)

I also know very little about Java programming but know C#, VB.NET and ASP.NET. I haven;t looked at silverlight yet but know what it can do to some extent. I do know though that Java syntax is very similar to that of C, C# and C++ as they all the the "{}" brackets and layed out similarly.

For arguments sake (just to get a handle and example) what would it take to convert something like Alfresco to a .NET type web app? Also, just want to add that I am not planning on doing it but want to know that if its even worth investing time in looking into Java applications to port to .NET.

答:
This page on MSDN might be useful: http://msdn.microsoft.com/en-us/gg715299.aspx.

It does a conceptual mapping of concepts in Java to concepts in .NET.

Regarding Giacomo's mention of the Java Language Conversion Assistant (JLCA), it is in fact retired and I wouldn't recommend relying too heavily on it. As he says there's quite a bit of cleanup to do but much of that depends on how you architected your app.


问:
Schema and data migrations for node js
Is there any tool that works similar to Django South, but for Node?

Now I'm working with Sequelize. If I got it right, Sequelize does not have an option to create migration files based on existing models.
So, to create a new model/table, the steps are:

Create model with sequelize model:create <model meta>.

Edit generated migration file - add actual code for creating tables
in DB under up section.

Run migration with sequelize db:migrate.

I'm looking for something that can create migration files based on existing models, manage it similar to what South can do for Django.

Is there any option?

答:
TypeORM supports model based migrations. It can sync your db to your models directly, it can also create migration files too.

I think prisma is another option. It doesn't seem like that popular but it's a promising one.

Either way, it's just ridiculous that there are no solid tools for this. I've worked on django and .net projects in the last years and creating migrations is just easy with them. But when you try to use node.js for backend, you get stuck at a lot of points.

I was using sequelize and when I saw there was no official way to create automatic migrations from models, I've dropped using it. Maintaining your models with manually written migrations becomes very hard in my experience.

Now my only alternative is TypeORM and it just bugs me there is no other alternative in case TypeORM just goes unmaintained or if I want to use another library etc.

I'm seriously thinking dropping using node.js for backend. Yet, there are good tools to create projects integrated with modern front-end tools (like Next.js), finding a good orm is a big problem.

Title: Schema and data migrations for node js


问:
Memory Violation Dynamically Appending to Methods at runtime
Disclaimer: I'm doing this for learning purposes. This is not going to be used in code.

I'm trying to understand how method table are structure for generics, I want to dynamically appending to methods at runtime.   I found a very useful stack overflow question reference for getting me started.

I have a simple controller which I'm using as a test to verify my methods are swapping:

```<code>public class ValuesController : ControllerBase
{
    static ValuesController() {
        var methodToReplace = typeof(ValuesController).GetMethod(nameof(ValuesController.Seven),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        var methodToAppend = typeof(ValuesController).GetMethod(nameof(ValuesController.Eight),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        new Initializer(methodToReplace, methodToAppend);
    }

    [HttpGet("Seven")]
    public int Seven(string id)
    {
        return 7;
    }

    [HttpGet("Eight")]
    public int Eight(string id)
    {
        return 8;
    }
}
</code>```

I have a class Initializer which is in charge of handling appending to the method.

```<code>public class Initializer
{
    public Initializer(MethodInfo methodToReplace, MethodInfo methodToAppend)
    {
        var dummyMethod = typeof(Initializer).GetMethod(nameof(Dummy),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        var proxyMethod = typeof(Initializer).GetMethod(nameof(Proxy),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        var appendedMethod = typeof(Initializer).GetMethod(nameof(Appended),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        dummyMethod.OneWayReplace(methodToReplace);
        methodToReplace.OneWayReplace(proxyMethod);
        appendedMethod.OneWayReplace(methodToAppend);
    }

    public int Proxy(string id)
    {
        Dummy(id);
        return Appended(id);
    }

    public int Dummy(string id)
    {
        return 0;
    }

    public int Appended(string id)
    {
        return 0;
    }
}
</code>```

And then I have the Extensions which I've obtained from the original stackoverflow question:

```<code>public static class InjectionExtensions
{
    // Note: This method replaces methodToReplace with methodToInject
    // Note: methodToInject will still remain pointing to the same location
    public static unsafe MethodReplacementState OneWayReplace(this MethodInfo methodToReplace, MethodInfo methodToInject)
    {
        //#if DEBUG
        RuntimeHelpers.PrepareMethod(methodToReplace.MethodHandle);
        RuntimeHelpers.PrepareMethod(methodToInject.MethodHandle);
        //#endif
        MethodReplacementState state;

        IntPtr tar = methodToReplace.MethodHandle.Value;
        var inj = methodToInject.MethodHandle.Value + 8;

        if (!methodToReplace.IsVirtual)
            tar += 8;
        else
        {
            var index = (int)(((*(long*)tar) >> 32) & 0xFF);
            var classStart = *(IntPtr*)(methodToReplace.DeclaringType.TypeHandle.Value + (IntPtr.Size == 4 ? 40 : 64));
            tar = classStart + IntPtr.Size * index;
        }
#if DEBUG
        tar = *(IntPtr*)tar + 1;
        inj = *(IntPtr*)inj + 1;
        state.Location = tar;
        state.OriginalValue = new IntPtr(*(int*)tar);

        *(int*)tar = *(int*)inj + (int)(long)inj - (int)(long)tar;
        return state;

#else
        state.Location = tar;
        state.OriginalValue = *(IntPtr*)tar;
        * (IntPtr*)tar = *(IntPtr*)inj;
        return state;
#endif
    }
}
</code>```

Note: Using the current setup everything works fine.  However, the second I change the Initializer class to be a generic class Initializer<T> I get a memory violation:

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

My guess is that either the methodToReplace.DeclaringType.TypeHandle.Value calculation differs for generics,  Or since the compiler is the one who generates the generic class it written to protected memory?

Edit
I've found more information I need to prepare the method properly when using generic parameters e.g:

```<code>RuntimeHelpers.PrepareMethod(methodToInject.MethodHandle, new[] { typeof(T).TypeHandle });
</code>```

However there are still a few more pieces to the puzzle to get this working.

Edit

There are a few open source project's such as harmony that do similar things,  However it looks like their emitting their own assemblies.  While I've considered the option, I would still prefer to understand how I method tables work with generics

How can I append to methods that reside in generic classes?

答:
I suppose you have already seen: Dynamically replace the contents of a C# method?

I have adapted some of those methods in my own project @ https://github.com/juliusfriedman/net7mma_core/blob/master/Concepts/Classes/MethodHelper.cs

I think the problem is that if your are running with the Debugger Attached then you need to also handle the portion of the logic which is currently defined by IFDEF at compilation time and replace that with an System.Diagnostics.Debugger.IsAttached although the offsets calculations (to jump over the debugger injected code) will probably have to change depending on various things like the version of the framework in use.

See https://github.com/juliusfriedman/net7mma_core/blob/master/Concepts/Classes/MethodHelper.cs#L35

This works for me in .Net Core 3.1 when the debugger IS NOT attached and I am running in Release mode, when running in Debug mode with or without the debugger attached or in Release mode with the debugger attached I receive different exceptions. (In debug I receive Arithmetic Overflow, while in release I receive Execution Engine Exception).

Furthermore this only works until the JIT Tiering kicks in, if I run the method a 2nd time without the debugger attached I am getting a Internal CLR Error.

I believe this has to do with the code injected by the debugger when attached and to be honest I am not up to do date on exactly what the debugger is injecting when attached.

I would make a simplified repo of the problem and ask a question @ https://github.com/dotnet/runtime if you need this to work with the debugger attached and I am sure someone there will guide you in the right direction.

Body:
Disclaimer: I'm doing this for learning purposes. This is not going to be used in code.

I'm trying to understand how method table are structure for generics, I want to dynamically appending to methods at runtime.   I found a very useful stack overflow question reference for getting me started.

I have a simple controller which I'm using as a test to verify my methods are swapping:

public class ValuesController : ControllerBase
{
    static ValuesController() {
        var methodToReplace = typeof(ValuesController).GetMethod(nameof(ValuesController.Seven),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        var methodToAppend = typeof(ValuesController).GetMethod(nameof(ValuesController.Eight),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        new Initializer(methodToReplace, methodToAppend);
    }

    [HttpGet("Seven")]
    public int Seven(string id)
    {
        return 7;
    }

    [HttpGet("Eight")]
    public int Eight(string id)
    {
        return 8;
    }
}

I have a class Initializer which is in charge of handling appending to the method.

public class Initializer
{
    public Initializer(MethodInfo methodToReplace, MethodInfo methodToAppend)
    {
        var dummyMethod = typeof(Initializer).GetMethod(nameof(Dummy),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        var proxyMethod = typeof(Initializer).GetMethod(nameof(Proxy),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        var appendedMethod = typeof(Initializer).GetMethod(nameof(Appended),
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

        dummyMethod.OneWayReplace(methodToReplace);
        methodToReplace.OneWayReplace(proxyMethod);
        appendedMethod.OneWayReplace(methodToAppend);
    }

    public int Proxy(string id)
    {
        Dummy(id);
        return Appended(id);
    }

    public int Dummy(string id)
    {
        return 0;
    }

    public int Appended(string id)
    {
        return 0;
    }
}

And then I have the Extensions which I've obtained from the original stackoverflow question:

public static class InjectionExtensions
{
    // Note: This method replaces methodToReplace with methodToInject
    // Note: methodToInject will still remain pointing to the same location
    public static unsafe MethodReplacementState OneWayReplace(this MethodInfo methodToReplace, MethodInfo methodToInject)
    {
        //#if DEBUG
        RuntimeHelpers.PrepareMethod(methodToReplace.MethodHandle);
        RuntimeHelpers.PrepareMethod(methodToInject.MethodHandle);
        //#endif
        MethodReplacementState state;

        IntPtr tar = methodToReplace.MethodHandle.Value;
        var inj = methodToInject.MethodHandle.Value + 8;

        if (!methodToReplace.IsVirtual)
            tar += 8;
        else
        {
            var index = (int)(((*(long*)tar) >> 32) & 0xFF);
            var classStart = *(IntPtr*)(methodToReplace.DeclaringType.TypeHandle.Value + (IntPtr.Size == 4 ? 40 : 64));
            tar = classStart + IntPtr.Size * index;
        }
#if DEBUG
        tar = *(IntPtr*)tar + 1;
        inj = *(IntPtr*)inj + 1;
        state.Location = tar;
        state.OriginalValue = new IntPtr(*(int*)tar);

        *(int*)tar = *(int*)inj + (int)(long)inj - (int)(long)tar;
        return state;

#else
        state.Location = tar;
        state.OriginalValue = *(IntPtr*)tar;
        * (IntPtr*)tar = *(IntPtr*)inj;
        return state;
#endif
    }
}

Note: Using the current setup everything works fine.  However, the second I change the Initializer class to be a generic class Initializer<T> I get a memory violation:

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'

My guess is that either the methodToReplace.DeclaringType.TypeHandle.Value calculation differs for generics,  Or since the compiler is the one who generates the generic class it written to protected memory?

Edit
I've found more information I need to prepare the method properly when using generic parameters e.g:

RuntimeHelpers.PrepareMethod(methodToInject.MethodHandle, new[] { typeof(T).TypeHandle });

However there are still a few more pieces to the puzzle to get this working.

Edit

There are a few open source project's such as harmony that do similar things,  However it looks like their emitting their own assemblies.  While I've considered the option, I would still prefer to understand how I method tables work with generics

How can I append to methods that reside in generic classes?


问:
Cosmos DB Trigger binding not registered?
I have a simple azure function cosmos trigger set up, like so:

```<code>{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "documents",
      "direction": "in",
      "leaseCollectionName": "leases",
      "connectionStringSetting": "DbConnectionString",
      "databaseName": "mydb",
      "collectionName": "mycollection",
      "createLeaseCollectionIfNotExists": "true"
    }
  ],
  "scriptFile": "../dist/TestCosmosTrigger/index.js"
}
</code>```

When I run the function I get an error:

The 'TestNotifier' function is in error: The binding type(s)
  'cosmosDBTrigger' are not registered. Please ensure the type is
  correct and the binding extension is installed.

Not sure what I'm doing wrong, perhaps it's a bug in the nodejs azure functions?

edit: after updating the azure function tools on my computer now a whole bunch of other bindings have started failing with the same error such as signalr:

{
      "type": "signalRConnectionInfo",
      "name": "connectionInfo",
      "hubName": "chat",
      "userId": "{headers.authorization}",
      "direction": "in"
    }

signalRConnectionInfo binding extension is not installed.

答:
After updating azure function core tools with:

npm i -g azure-functions-core-tools@core --unsafe-perm true

and then running:

func extensions install -p Microsoft.Azure.WebJobs.Extensions.SignalRService -v 1.0.0

It looks like the above issue was resolved, a new problem opened up but that's a seperate issue.

Body:
I have a simple azure function cosmos trigger set up, like so:

{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "documents",
      "direction": "in",
      "leaseCollectionName": "leases",
      "connectionStringSetting": "DbConnectionString",
      "databaseName": "mydb",
      "collectionName": "mycollection",
      "createLeaseCollectionIfNotExists": "true"
    }
  ],
  "scriptFile": "../dist/TestCosmosTrigger/index.js"
}

When I run the function I get an error:

The 'TestNotifier' function is in error: The binding type(s)
  'cosmosDBTrigger' are not registered. Please ensure the type is
  correct and the binding extension is installed.

Not sure what I'm doing wrong, perhaps it's a bug in the nodejs azure functions?

edit: after updating the azure function tools on my computer now a whole bunch of other bindings have started failing with the same error such as signalr:

{
      "type": "signalRConnectionInfo",
      "name": "connectionInfo",
      "hubName": "chat",
      "userId": "{headers.authorization}",
      "direction": "in"
    }

signalRConnectionInfo binding extension is not installed.


问:
PHP "apc_store" and "apc_fetch" are not working as expected
I was trying to use APC but it doesn't seem to work as I expected.

file1:

```<code>$bar = 'BAR';
apc_store('foo', $bar, 3600);
var_dump(apc_fetch('foo'));           // It works here. Displays BAR
</code>```

file2:

```<code>var_dump(apc_fetch('foo'));
</code>```

When I execute file2 within seconds, it returns false instead of 'BAR' which is the data stored in the cache.

答: Install this ( http://svn.php.net/viewvc/pecl/apc/trunk/apc.php?view=markup ) in a protected area of the server, set it up as describe in the comments, and that should make diagnosing your APC caching issues a breeze... or atleast give you a better insight into why something isn't working as desired.</p>

Body:
I was trying to use APC but it doesn't seem to work as I expected.

file1:

$bar = 'BAR';
apc_store('foo', $bar, 3600);
var_dump(apc_fetch('foo'));           // It works here. Displays BAR

file2:

var_dump(apc_fetch('foo'));

When I execute file2 within seconds, it returns false instead of 'BAR' which is the data stored in the cache.


问:
typescript: enforcing existing object keys
I would like dropdownAttributes to limited to attributes on DropDownItem interface.

```<code>interface DropDownItem {
    [key: string]: any;
}
</code>```

```<code>interface Props {
   dropdownList: DropDownItem[];
   dropdownAttributes: string[];
}
</code>```

if DropDownItem did now have dynamic properties I think I could solve this with keyof like this:

```<code>interface Props {
   dropdownList: DropDownItem[];
   dropdownAttributes: (keyof DropDownItem)[];
}
</code>```

But that does not work now in my case. How to solve?

答:
It seems like you want Props to be generic so that it can be used by different object types. This can be achieved by defining a generic type T in Props

```<code>interface Props<T> {
   dropdownList: T[];
   dropdownAttributes: (keyof T)[];
}
</code>```

Now, if we know the types of a certain object in advance, we can create an interface for that, and create a type that uses that interface in Prop

```<code>interface MyDropDownItem {
  foo : number
}

type MyDropDownItemProps = Props<MyDropDownItem>;
</code>```

We can now only use instances of MyDropDownItem in dropdownList and its keys in dropdownAttributes

```<code>const good: MyDropDownItemProps = {
  dropdownList: [{foo: 2}],
  dropdownAttributes : ['foo']
}

const bad: MyDropDownItemProps = {
  dropdownList: [{foo: 2, bar: 's' /* error here */}],
  dropdownAttributes : ['foo', 'bar' /* and here */ ]
}
</code>```

This of course assumes you know the structure of your dropdowns in advance, because that's the only thing typescript can help you with. Typescript won't help you with runtime type safety.

Check it out on stackblitz

Body:
I would like dropdownAttributes to limited to attributes on DropDownItem interface.

interface DropDownItem {
    [key: string]: any;
}

interface Props {
   dropdownList: DropDownItem[];
   dropdownAttributes: string[];
}

if DropDownItem did now have dynamic properties I think I could solve this with keyof like this:

interface Props {
   dropdownList: DropDownItem[];
   dropdownAttributes: (keyof DropDownItem)[];
}

But that does not work now in my case. How to solve?

Body:
It seems like you want Props to be generic so that it can be used by different object types. This can be achieved by defining a generic type T in Props

interface Props<T> {
   dropdownList: T[];
   dropdownAttributes: (keyof T)[];
}

Now, if we know the types of a certain object in advance, we can create an interface for that, and create a type that uses that interface in Prop

interface MyDropDownItem {
  foo : number
}

type MyDropDownItemProps = Props<MyDropDownItem>;

We can now only use instances of MyDropDownItem in dropdownList and its keys in dropdownAttributes

const good: MyDropDownItemProps = {
  dropdownList: [{foo: 2}],
  dropdownAttributes : ['foo']
}

const bad: MyDropDownItemProps = {
  dropdownList: [{foo: 2, bar: 's' /* error here */}],
  dropdownAttributes : ['foo', 'bar' /* and here */ ]
}

This of course assumes you know the structure of your dropdowns in advance, because that's the only thing typescript can help you with. Typescript won't help you with runtime type safety.

Check it out on stackblitz


问:
Remove elements of 2d array whose 1st column values are duplicates (Swift)
This query is a small twist on a commonly asked question.

The goal is to filter a 2d array to remove duplicate element pairs whose first-column values are duplicates. For example:

```<code>[[1, 1, 1,  2, 2,  3, 3, 3, 3], [0.1, 0.15, 0.2,  0.05, 0.1,  0.2, 0.25, 0.3, 0.35]]
     ->    [[1, 2, 3],[0.2, 0.1, 0.35]]
</code>```

Since the second-column values vary, there is obviously some discretion that needs to be applied when filtering: here, the last value of the set of duplicates is chosen.

One of the myriad answers to this related question -- a functional programming solution by Tim MB -- can be adapted to the task:

```<code>// Use FP-style filtering to eliminate repeated elements
let rawArray: [[Float]] = [...]
let filteredArray = rawArray
    .transpose
    .enumerated()
    .filter{ (rawArray[0]).lastIndex(of: $0.1[0]) == $0.0 }
    .map{ $0.1 }
    .transpose
</code>```

However, this solution is rather slow, which is unfortunate because it's elegant.

A faster solution that keeps the FP spirit is to use dictionary hashing:

```<code>// Use array -> dict -> array trick to remove repeated elements
let rawArray: [[Float]] = [...]
let filteredArray = Array( Array(
    rawArray
        .transpose
        .reduce(into: [:], { dict, elements in
            dict[elements[0], default:(0,0)] = elements[1]
        } )
        .map{ ($0.key, $0.value) } )
    .sorted{ $0.0 < $1.0 }
    .map{ [$0.0, $0.1] }
    .transpose) as! Array2D
</code>```

My questions are:

Is this dictionary trick a good idea? Given that it uses floats as keys?

Why is the FP solution slow?  Can it be speeded up?

Are there better alternatives?

答:
You can accomplish what you want by first filtering the indices of the first array which the element is the first occurrence in reverse order. Then you just need to map the subsequences using them:

```<code>let rawArray: [[Float]] = [[1, 1, 1, 2, 2, 3, 3, 3, 3], [0.1, 0.15, 0.2, 0.05, 0.1, 0.2, 0.25, 0.3, 0.3]]
var set: Set<Float> = []
let indices = rawArray
    .first?
    .indices
    .reversed()
    .filter { set.insert(rawArray.first![$0]).inserted }
    .reversed() ?? []
let result = rawArray.map { elements in indices.map { elements[$0] } }
print(result) //  [[1, 2, 3], [0.2, 0.1, 0.3]]
</code>```

Another option is to create two empty subsequences, iterate the first rawArray subsequence indices reversed and try to insert the float value into a set, if inserted append the corresponding elements to the subsequences, then you just need to recreate the resulting array with those two new sequences reversed:

```<code>let rawArray: [[Float]] = [[1, 1, 1, 2, 2, 3, 3, 3, 3], [0.1, 0.15, 0.2, 0.05, 0.1, 0.2, 0.25, 0.3, 0.3]]
var set: Set<Float> = []
var sub1: [Float] = []
var sub2: [Float] = []
rawArray[0].indices.reversed().forEach {
    let value = rawArray[0][$0]
    if set.insert(value).inserted {
        sub1.append(value)
        sub2.append(rawArray[1][$0])
    }
}
let result: [[Float]] = [sub1.reversed(), sub2.reversed()] // [[1, 2, 3], [0.2, 0.1, 0.3]]
</code>```

You can make it even faster if the result array is declared as a reversed collection of floating points. It would be O(1) for [ReversedCollection<[Float]>]  instead of O(n) for [[Float]] for each subsequence.

Body:
This query is a small twist on a commonly asked question.

The goal is to filter a 2d array to remove duplicate element pairs whose first-column values are duplicates. For example:

[[1, 1, 1,  2, 2,  3, 3, 3, 3], [0.1, 0.15, 0.2,  0.05, 0.1,  0.2, 0.25, 0.3, 0.35]]
     ->    [[1, 2, 3],[0.2, 0.1, 0.35]]

Since the second-column values vary, there is obviously some discretion that needs to be applied when filtering: here, the last value of the set of duplicates is chosen.

One of the myriad answers to this related question -- a functional programming solution by Tim MB -- can be adapted to the task:

// Use FP-style filtering to eliminate repeated elements
let rawArray: [[Float]] = [...]
let filteredArray = rawArray
    .transpose
    .enumerated()
    .filter{ (rawArray[0]).lastIndex(of: $0.1[0]) == $0.0 }
    .map{ $0.1 }
    .transpose

However, this solution is rather slow, which is unfortunate because it's elegant.

A faster solution that keeps the FP spirit is to use dictionary hashing:

// Use array -> dict -> array trick to remove repeated elements
let rawArray: [[Float]] = [...]
let filteredArray = Array( Array(
    rawArray
        .transpose
        .reduce(into: [:], { dict, elements in
            dict[elements[0], default:(0,0)] = elements[1]
        } )
        .map{ ($0.key, $0.value) } )
    .sorted{ $0.0 < $1.0 }
    .map{ [$0.0, $0.1] }
    .transpose) as! Array2D

My questions are:

Is this dictionary trick a good idea? Given that it uses floats as keys?

Why is the FP solution slow?  Can it be speeded up?

Are there better alternatives?

Body:
You can accomplish what you want by first filtering the indices of the first array which the element is the first occurrence in reverse order. Then you just need to map the subsequences using them:

let rawArray: [[Float]] = [[1, 1, 1, 2, 2, 3, 3, 3, 3], [0.1, 0.15, 0.2, 0.05, 0.1, 0.2, 0.25, 0.3, 0.3]]
var set: Set<Float> = []
let indices = rawArray
    .first?
    .indices
    .reversed()
    .filter { set.insert(rawArray.first![$0]).inserted }
    .reversed() ?? []
let result = rawArray.map { elements in indices.map { elements[$0] } }
print(result) //  [[1, 2, 3], [0.2, 0.1, 0.3]]

Another option is to create two empty subsequences, iterate the first rawArray subsequence indices reversed and try to insert the float value into a set, if inserted append the corresponding elements to the subsequences, then you just need to recreate the resulting array with those two new sequences reversed:

let rawArray: [[Float]] = [[1, 1, 1, 2, 2, 3, 3, 3, 3], [0.1, 0.15, 0.2, 0.05, 0.1, 0.2, 0.25, 0.3, 0.3]]
var set: Set<Float> = []
var sub1: [Float] = []
var sub2: [Float] = []
rawArray[0].indices.reversed().forEach {
    let value = rawArray[0][$0]
    if set.insert(value).inserted {
        sub1.append(value)
        sub2.append(rawArray[1][$0])
    }
}
let result: [[Float]] = [sub1.reversed(), sub2.reversed()] // [[1, 2, 3], [0.2, 0.1, 0.3]]

You can make it even faster if the result array is declared as a reversed collection of floating points. It would be O(1) for [ReversedCollection<[Float]>]  instead of O(n) for [[Float]] for each subsequence.


问:
Day difference between two dates
Output between 15/02/2020 and 02/03/2020 produces 18, but I expect 16.

What am I doing wrong?

```<code>public void checkNumberOfDaysBetweenTwoDates(models.Date date2) {
    int day_diff, mon_diff, year_diff;

    if(date2.checkIfLegal()) {
        if(date2.day < day) {
            date2.day += date2.numberOfDaysInMonth();
        }
        date2.month = date2.month - 1;
    }

    if(date2.month < month) {
        date2.month += 12;
        date2.year -= 1;
    }

    day_diff = date2.day - day;
    mon_diff = date2.month - month;
    year_diff = date2.year - year;

    System.out.println("days: " + day_diff + "months: " + mon_diff + "years: " + year_diff);
}

private boolean isLeapYear() {
    return year % 4 == 0 &&
        (year % 100 != 0 || year % 400 == 0);
}

public boolean checkIfLegal() {
    boolean validation = false;

    if(month < 1 || month > 12 || day < 1 || day > numberOfDaysInMonth()) {
        validation = false;
    } else {
        validation = true;
    }

    return validation;
}

private int numberOfDaysInMonth() {
    if (month == 2 && isLeapYear())
        return 29;
    else
        return daysInMonth[month - 1];
}
</code>```

答:
You add the number of days in a month if the day of the second date is less than the day of the first date:

```<code>date2.day += date2.numberOfDaysInMonth();
</code>```

You add the number of days in the month of date2 (here 31, the number of days in March). But you must add the number of days in the previous month (here 29, the number of days in February).

Another thing to consider: Method checkIfLegal can be simplified to

```<code>public boolean checkIfLegal() {
    return month >= 1 && month <= 12 && day >= 1 && day <= numberOfDaysInMonth();
}
</code>```

And the method should have a parameter which defines the date to check. Do not use a global variable here!

Title: Day difference between two dates

Body:
Output between 15/02/2020 and 02/03/2020 produces 18, but I expect 16.

What am I doing wrong?

public void checkNumberOfDaysBetweenTwoDates(models.Date date2) {
    int day_diff, mon_diff, year_diff;

    if(date2.checkIfLegal()) {
        if(date2.day < day) {
            date2.day += date2.numberOfDaysInMonth();
        }
        date2.month = date2.month - 1;
    }

    if(date2.month < month) {
        date2.month += 12;
        date2.year -= 1;
    }

    day_diff = date2.day - day;
    mon_diff = date2.month - month;
    year_diff = date2.year - year;

    System.out.println("days: " + day_diff + "months: " + mon_diff + "years: " + year_diff);
}

private boolean isLeapYear() {
    return year % 4 == 0 &&
        (year % 100 != 0 || year % 400 == 0);
}

public boolean checkIfLegal() {
    boolean validation = false;

    if(month < 1 || month > 12 || day < 1 || day > numberOfDaysInMonth()) {
        validation = false;
    } else {
        validation = true;
    }

    return validation;
}

private int numberOfDaysInMonth() {
    if (month == 2 && isLeapYear())
        return 29;
    else
        return daysInMonth[month - 1];
}

Body:
You add the number of days in a month if the day of the second date is less than the day of the first date:

date2.day += date2.numberOfDaysInMonth();

You add the number of days in the month of date2 (here 31, the number of days in March). But you must add the number of days in the previous month (here 29, the number of days in February).

Another thing to consider: Method checkIfLegal can be simplified to

public boolean checkIfLegal() {
    return month >= 1 && month <= 12 && day >= 1 && day <= numberOfDaysInMonth();
}

And the method should have a parameter which defines the date to check. Do not use a global variable here!


问:
HTTPError: 400 Client Error: Bad Request using python-firebase
I'm trying to upload data to firebase realtime database using python-firebase but I'm getting the following error:
HTTPError: 400 Client Error: Bad Request for url: https://app.firebaseio.com/essential/activepassive/.json
My code:</p>

```<code>from firebase import firebase
firebase=firebase.FirebaseApplication('https://app.firebaseio.com/',None)
firebase.post('/essential/activepassive',dictionary)
</code>```

答:
Error 400 means an Invalid JSON in your request:you may have '#' or other invalid character in your json file.

you can use this data for test

```<code>data_good = {'url': 'url1', 'address': 'address1','name': 'name1'}
</code>```

Body:
I'm trying to upload data to firebase realtime database using python-firebase but I'm getting the following error:
HTTPError: 400 Client Error: Bad Request for url: https://app.firebaseio.com/essential/activepassive/.json
My code:

from firebase import firebase
firebase=firebase.FirebaseApplication('https://app.firebaseio.com/',None)
firebase.post('/essential/activepassive',dictionary)

Body:
Error 400 means an Invalid JSON in your request:you may have '#' or other invalid character in your json file.

you can use this data for test

data_good = {'url': 'url1', 'address': 'address1','name': 'name1'}


问:
Uncaught ReferenceError: writeIn is not defined at change (<anonymous>:5:4) at <anonymous>:7:1
I try to write a function to change the color of a text, but the error occurs. I winder how to fix this.

```<code>function change() {
var colour = prompt("What's your favourite colour?");
a = colour.value
id = document.querySelector('.tab ');
id.style.backgoundColor = writeIn(a) ;
}
change();
console.log(a);
</code>```

I edited the code as below, the error went, but still the value is undifined and no change occurs in the text.

```<code>var changing = function change() {
var cls = document.querySelector('.tab ');
var colour = prompt("What's your favourite colour?");
var a = colour.value;
cls.style.backgoundColor = a ;
alert(a);
}
changing();
console.log(a);
</code>```

答:
In your code you haven't declared writeIn(a) function anywhere. So this is the reason for error.

Just comment that line it will work, or declare the writeIn function.

Body:
I try to write a function to change the color of a text, but the error occurs. I winder how to fix this.

function change() {
var colour = prompt("What's your favourite colour?");
a = colour.value
id = document.querySelector('.tab ');
id.style.backgoundColor = writeIn(a) ;
}
change();
console.log(a);

I edited the code as below, the error went, but still the value is undifined and no change occurs in the text.

var changing = function change() {
var cls = document.querySelector('.tab ');
var colour = prompt("What's your favourite colour?");
var a = colour.value;
cls.style.backgoundColor = a ;
alert(a);
}
changing();
console.log(a);


问:
Persisting a Protocol Buffer Model with JDO on App Engine
we are building an Android app that communicates with a Java App Engine Server via Protocol Buffers. We use JDO as the persistence mechanism on the server.

My question is how to persist objects in the App Engine database. It seems like the only way to do it is the create two classes for each model: one model which is generated from the .proto file and a second class that wraps the first class and provides JDO annotations, additional methods etc. This seems rather cumbersome to me and I am wondering what the best practice regarding this might be. Is there a way to avoid this duplication (JPA for instance allows to specify the persistence annotations in external XML files, but we would rather avoid JPA on App Engine because of the poor documentation)?

答:
App Engine's datastore only stores Model Protocol Buffers. If the protocol buffer your client sends you is a Model PB, you could store it directly by poking it into the low level APIs. If it's any other sort of PB, you either need to convert it (manually) into an Entity, or you need to serialize it and store it in a binary property of the entity. Which of those you choose depends on how you need to query the stored object.

Either way, JDO is probably a poor choice - you should look into Objectify, or use the low-level API directly.


问:
When popping , Why do we need to pass a context to Navigator in flutter?
Since flutter uses a stack to manage the screens which can be accessed through the Navigator class , I have the below understanding of it :

When we do Navigator.push(context , ... )  :  Here the context is used so that it knows on top of which other widget it should push the new screen.

What I don't understand is why it needs a context to pop a screen out of view ?

Can't it simply pop the top most screen of the stack and show the screen below that ?

What exactly is the role of context here and how does it differ when pushing and popping

答:
The reason is the same for both push and pop - it's to find the Navigator.

Looking at .pop you see that it's a static, convenience function that does:

```<code>  return Navigator.of(context).pop<T>(result);
</code>```

The context is used in .of to locate the navigator in the widget tree above the widget where you are calling push or pop. As you'd expect, of (another static convenience function) locates the actual navigator using:

```<code> context.findAncestorStateOfType()
</code>```

So, in summary, you pass context so that context.findAncestor... can be used to find the navigator on which to call the method.

Body:
The reason is the same for both push and pop - it's to find the Navigator.

Looking at .pop you see that it's a static, convenience function that does:

  return Navigator.of(context).pop<T>(result);

The context is used in .of to locate the navigator in the widget tree above the widget where you are calling push or pop. As you'd expect, of (another static convenience function) locates the actual navigator using:

 context.findAncestorStateOfType()

So, in summary, you pass context so that context.findAncestor... can be used to find the navigator on which to call the method.


问:
R convert time (xx:xx:xx) to min. as.POSIXct returns error "character string is not in a standard unambiguous format"
I have some data about focus times in xx:xx:xx format that I would like to add together over several sessions. So I am trying to convert each of them to minutes or any format that can be summed and understood. I've tried as.POSIX.ct but I get the error in the title. I've also tried lubidate hms(day1)/60 and I get another error. Here's a shortened reproducible example.

```<code>day1 <- c("01:05:38", "00:56:54", "00:48:17")
day2 <- c("00:37:57", "00:21:09", "00:43:34")
day1convert <- as.numeric(as.POSIXct(day1), units = "mins")
</code>```

This returns the error: "Error in as.POSIXlt.character(x, tz, ...) :
  character string is not in a standard unambiguous format"

```<code>library(lubridate)
convert<-hms(day1)/60
</code>```

This returns the error:"Error in validObject(.Object) :
  invalid class “Period” object: periods must have integer values

Any help would be appreciated.

Body:
I have some data about focus times in xx:xx:xx format that I would like to add together over several sessions. So I am trying to convert each of them to minutes or any format that can be summed and understood. I've tried as.POSIX.ct but I get the error in the title. I've also tried lubidate hms(day1)/60 and I get another error. Here's a shortened reproducible example.

day1 <- c("01:05:38", "00:56:54", "00:48:17")
day2 <- c("00:37:57", "00:21:09", "00:43:34")
day1convert <- as.numeric(as.POSIXct(day1), units = "mins")

This returns the error: "Error in as.POSIXlt.character(x, tz, ...) :
  character string is not in a standard unambiguous format"

library(lubridate)
convert<-hms(day1)/60

This returns the error:"Error in validObject(.Object) :
  invalid class “Period” object: periods must have integer values

Any help would be appreciated.

Body:
In base R:

sapply(strsplit(day1, ":"), function(x) as.difftime(sum(c(60, 1, 1/60)*as.numeric(x)), units="mins"))
#> [1] 65.63333 56.90000 48.28333


问:
How to implement Material Speed Dial on Flutter?
Is there any native Flutter library for achieving Material Design Speed Dial?

I found only this FAB documentation, but it doesn't say anything about creating a menu out of it, though Material Design FAB documentation says at the top that FAB is supported in Flutter (it doesn't say how much it supports. Only that it supports, which would lead me to understand that it supports everything in the page).

Should I instead develop mine or look for third party libraries?

答:
Nevermind. I'm creating my own Speed Dial. For now, it is part of a very simple project, but once I test it more and add animations, I'll share a final link.

It still don't have animations, because I'm using Visibility for showing or hiding the buttons, and it was tested only in Scaffold's FAB, placed on bottom right of screen, so no link for now, sorry. Less than an alpha right now (and I still need to study how one shares an API for adding to dependency).

I hope I'll be able to create a simple and light enough implementation. Easy to use and easy to understand if anybody wishes to take a look into the code later on. I've seen some implementations, but they are very complex and create (in my view) unnecessary extra widgets.

Some implementations I found:

https://flutterawesome.com/flutter-plugin-to-implement-a-material-design-speed-dial/

https://flutterawesome.com/flutter-floating-action-button-with-speed-dial/


问:
CallLog.Calls.NEW? What does it mean?
I am currently trying to figure out what

```<code>CallLog.Calls.NEW
</code>```

means.

The documentation says:

Whether or not the call has been
  acknowledged

( http://developer.android.com/reference/android/provider/CallLog.Calls.html#NEW ). I tried to reproduce this.

I made a call to another phone and hung up once it started ringing. What would I expect? An entry with TYPE = OUTGOING_TYPE and NEW = 0, right? But NEW is 1. That really doesn't make any sense to me...

Any ideas?

答:
See the source for it here.

The calls are always added with a NEW value of 1:

```<code>values.put(NEW, Integer.valueOf(1));
</code>```

Probably, there is a method in the phone call log app or in the call notification to set it as zero. BTW, I did not look for that.

Title: CallLog.Calls.NEW? What does it mean?

Body:
I am currently trying to figure out what

CallLog.Calls.NEW

means.

The documentation says:

Whether or not the call has been
  acknowledged

( http://developer.android.com/reference/android/provider/CallLog.Calls.html#NEW ). I tried to reproduce this.

I made a call to another phone and hung up once it started ringing. What would I expect? An entry with TYPE = OUTGOING_TYPE and NEW = 0, right? But NEW is 1. That really doesn't make any sense to me...

Any ideas?

Body:
See the source for it here.

The calls are always added with a NEW value of 1:

values.put(NEW, Integer.valueOf(1));

Probably, there is a method in the phone call log app or in the call notification to set it as zero. BTW, I did not look for that.


问:
Transport.send not working on javax.mail library
I have to classes the main class plus JavaMailUtl class
This is my JavaMailUtl class:

```<code>import javax.mail.Authenticator;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class JavaMailUtl {
    public static void sendMail(String recepient) throws Exception{
        System.out.println("Preparing Email");
        Properties properties = new Properties();

        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");

        String myAccountEmail = "someEmail@gmail.com";
        String password = "xxxxxxxx";

        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new javax.mail.PasswordAuthentication(myAccountEmail, password);
            }

});
        Message message = prepareMessage(session, myAccountEmail, recepient);
        Transport.send(message);
        System.out.println("Message sent!");
    }

    private static Message prepareMessage(Session session, String myAccountEmail, String recepient){
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(myAccountEmail));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recepient));
            message.setSubject("Gmail API");
            message.setText("This Message sent from Java APP");
        } catch (Exception ex) {
            Logger.getLogger(JavaMailUtl.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}

</code>```

and this is my main class:

```<code>public class JavaEmailMessaging {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        JavaMailUtl.sendMail("someOtherEmail@gmail.com");
    }

}
</code>```

When I try to run the project I get the following error:

```<code>Preparing Email
Exception in thread "main" java.lang.NullPointerException
    at javax.mail.Transport.send(Transport.java:123)
    at mailing.email.messaging.JavaMailUtl.sendMail(JavaMailUtl.java:43)
    at mailing.email.messaging.JavaEmailMessaging.main(JavaEmailMessaging.java:18)
</code>```

Doubled check the code lots of times and found no problem for me every object I have is pointing to  the right place.

答:
Your prepareMessage method returns null. Define message before the try - and then return it.

Something like this:

```<code>    private static Message prepareMessage(Session session, String myAccountEmail, String recepient) {
        Message message = null;
        try {
            message = new MimeMessage(session);
            message.setFrom(new InternetAddress(myAccountEmail));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recepient));
            message.setSubject("Gmail API");
            message.setText("This Message sent from Java APP");
        } catch (Exception ex) {
            Logger.getLogger(JavaMailUtl.class.getName()).log(Level.SEVERE, null, ex);
        }
        return message;
    }
</code>```

Hope that helps.

EDIT: Also, it's worth noting that an enhancement in Java 14 should make this situation less painful. You'll get more info on what exactly was null.

Body:
I have to classes the main class plus JavaMailUtl class
This is my JavaMailUtl class:

import javax.mail.Authenticator;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class JavaMailUtl {
    public static void sendMail(String recepient) throws Exception{
        System.out.println("Preparing Email");
        Properties properties = new Properties();

        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");

        String myAccountEmail = "someEmail@gmail.com";
        String password = "xxxxxxxx";

        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new javax.mail.PasswordAuthentication(myAccountEmail, password);
            }

});
        Message message = prepareMessage(session, myAccountEmail, recepient);
        Transport.send(message);
        System.out.println("Message sent!");
    }

    private static Message prepareMessage(Session session, String myAccountEmail, String recepient){
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(myAccountEmail));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recepient));
            message.setSubject("Gmail API");
            message.setText("This Message sent from Java APP");
        } catch (Exception ex) {
            Logger.getLogger(JavaMailUtl.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}

and this is my main class:

public class JavaEmailMessaging {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        JavaMailUtl.sendMail("someOtherEmail@gmail.com");
    }

}

When I try to run the project I get the following error:

Preparing Email
Exception in thread "main" java.lang.NullPointerException
    at javax.mail.Transport.send(Transport.java:123)
    at mailing.email.messaging.JavaMailUtl.sendMail(JavaMailUtl.java:43)
    at mailing.email.messaging.JavaEmailMessaging.main(JavaEmailMessaging.java:18)

Doubled check the code lots of times and found no problem for me every object I have is pointing to  the right place.

Body:
Your prepareMessage method returns null. Define message before the try - and then return it.

Something like this:

    private static Message prepareMessage(Session session, String myAccountEmail, String recepient) {
        Message message = null;
        try {
            message = new MimeMessage(session);
            message.setFrom(new InternetAddress(myAccountEmail));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recepient));
            message.setSubject("Gmail API");
            message.setText("This Message sent from Java APP");
        } catch (Exception ex) {
            Logger.getLogger(JavaMailUtl.class.getName()).log(Level.SEVERE, null, ex);
        }
        return message;
    }

Hope that helps.

EDIT: Also, it's worth noting that an enhancement in Java 14 should make this situation less painful. You'll get more info on what exactly was null.


问:
How can I put two bars of distinct series next to each other in the same chart?
Let's assume our data frame has two series of type integer: estimated_value and sell_price.

I want to have two bars next to each other in the same bar chart.
The left one shows average(estimated_value) and the right one shows average(sell_price).
They shall share the same axis.

I thought this would be a very common use case but I could not find any example in the docs. All the examples use 'colour' or 'column' to group bars.

I've tried using y2 but it seems to simply erase the difference to y1 instead of adding a second series.

Then I tried using a layeredChart but this puts both bars on top of each other instead of next to each other.

答:
It sounds like you have wide-form data rather than long-form data. The difference is discussed in Long-form vs. Wide-form data.

Once you've transformed your data to long-form, you can use standard encodings to achieve this result. Here's how it might look, using some example data:

```<code>import altair as alt
import pandas as pd

data = pd.DataFrame({
    'estimated_value': [500, 600, 700, 800, 900],
    'sell_price': [550, 610, 690, 810, 950]
})

alt.Chart(data).transform_fold(
    ['estimated_value', 'sell_price'], as_=['category', 'price']
).mark_bar().encode(
    y='category:N',
    x='average(price):Q',
)
</code>```

Body:
It sounds like you have wide-form data rather than long-form data. The difference is discussed in Long-form vs. Wide-form data.

Once you've transformed your data to long-form, you can use standard encodings to achieve this result. Here's how it might look, using some example data:

import altair as alt
import pandas as pd

data = pd.DataFrame({
    'estimated_value': [500, 600, 700, 800, 900],
    'sell_price': [550, 610, 690, 810, 950]
})

alt.Chart(data).transform_fold(
    ['estimated_value', 'sell_price'], as_=['category', 'price']
).mark_bar().encode(
    y='category:N',
    x='average(price):Q',
)


问:
TypeError: undefined is not an object (evaluating 'event.target.value')
I'm working on a React Native project and I'm trying to make a Login form.

But I have some trouble to handle the text change in the TextInput.

My login form code

```<code>export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: '',
      password: '',
    };
    this.handleChange = this.handleChange.bind(this);
  }

  onLogin() {
    const { email, password } = this.state;
    Alert.alert('Credentials', `${email} + ${password}`);
  }

  handleChange(event) {
    this.setState({
      email: event.target.value,
      password: event.target.value,
    });
  }

  render() {
    const { email, password } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.form}>
          <Title>Connectez-vous</Title>
          <TextInput
            style={{ backgroundColor: '#f8f8ff' }}
            value={email}
            onChangeText={this.handleChange}
            label="Adresse email"
            mode="outlined"
          />
          <TextInput
            style={{
              backgroundColor: '#f8f8ff',
            }}
            value={password}
            onChangeText={this.handleChange}
            label="Mot de passe"
            mode="outlined"
            secureTextEntry
          />
          <Button
            mode="outlined"
            onPress={() => this.onLogin}
            style={{ marginTop: '5%', marginHorizontal: '25%' }}
          >
            Connexion
          </Button>
        </View>
      </View>
    );
  }
}
</code>```

When I try to write something in the TextInput I got the error : TypeError: undefined is not an object (evaluating 'event.target.value').

答:
Your onLogin fucntion will display nothing, because you have not bound the function to your class, so this just points to the _global object instead of class.

So either, explicitly bind the method

```<code>this.onLogin = this.onLogin.bind(this)
</code>```

or more preferably start using arrow function syntax

```<code>onLogin = () => {
  const { email, password } = this.state
  Alert.alert('Credentials', `${email} + ${password}`);
}
</code>```

As to the text-handling, <TextInput> component already has pre-defined onTextChange property, which accepts the inptu directly, instead of event which is reserved for onChange. You've essentially meshed the two together, so of course it doesn't work.

```<code>handleEmailChange = (textVal) => this.setState({
  email: textVal
})

<TextInput
  // ... other props
  onTextChange={this.handleEmailChange}
/>
</code>```

Body:
I'm working on a React Native project and I'm trying to make a Login form.

But I have some trouble to handle the text change in the TextInput.

My login form code

export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: '',
      password: '',
    };
    this.handleChange = this.handleChange.bind(this);
  }

  onLogin() {
    const { email, password } = this.state;
    Alert.alert('Credentials', `${email} + ${password}`);
  }

  handleChange(event) {
    this.setState({
      email: event.target.value,
      password: event.target.value,
    });
  }

  render() {
    const { email, password } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.form}>
          <Title>Connectez-vous</Title>
          <TextInput
            style={{ backgroundColor: '#f8f8ff' }}
            value={email}
            onChangeText={this.handleChange}
            label="Adresse email"
            mode="outlined"
          />
          <TextInput
            style={{
              backgroundColor: '#f8f8ff',
            }}
            value={password}
            onChangeText={this.handleChange}
            label="Mot de passe"
            mode="outlined"
            secureTextEntry
          />
          <Button
            mode="outlined"
            onPress={() => this.onLogin}
            style={{ marginTop: '5%', marginHorizontal: '25%' }}
          >
            Connexion
          </Button>
        </View>
      </View>
    );
  }
}

When I try to write something in the TextInput I got the error : TypeError: undefined is not an object (evaluating 'event.target.value').

Body:
Your onLogin fucntion will display nothing, because you have not bound the function to your class, so this just points to the _global object instead of class.

So either, explicitly bind the method

this.onLogin = this.onLogin.bind(this)

or more preferably start using arrow function syntax

onLogin = () => {
  const { email, password } = this.state
  Alert.alert('Credentials', `${email} + ${password}`);
}

As to the text-handling, <TextInput> component already has pre-defined onTextChange property, which accepts the inptu directly, instead of event which is reserved for onChange. You've essentially meshed the two together, so of course it doesn't work.

handleEmailChange = (textVal) => this.setState({
  email: textVal
})

<TextInput
  // ... other props
  onTextChange={this.handleEmailChange}
/>


问:
Solve system of differential equation with embedded non diferential equations, using Octave/Matlab (see picture)
I have the following equation system (click to see picture)
, and would like to solve for X(t), Y(t), Z(t), hopefully using Octave/Matlab, which I'm familiar with, but I would not mind solving it by any other means necessary.

Now, Fsolve is useful for regular equation systems, and Ode45, Lsode are useful for differential equations. But, what about this particular system? Note that the differential equation at the bottom contains not only Y, but, also, both X and Z, and those are dependent on the two non-differential equations above.

To be honest, I'm not quite sure how to approach a basic code to solve this system, and after spending some time thinking, I decided to ask for help. I really appreciate any guidance to solve this problem somewhat efficiently, if it is even possible. Almost any reply would be of some use to me right now.

答:
If you know y, you can solve for x, and this even unconditionally as the second equation in monotonous in x

```<code>x = fsolve(@(x) y^2-1413.7*x-1095.2*cos(x)+2169, 0)
</code>```

Then once you know x, you can solve for z using the known inverse cosine

```<code>z = acos(0.20978-cos(x))
</code>```

This may actually fail to give a result if cos(x) comes close to -1. One can artificially cut out that error, introducing a possibly wrong solution

```<code>z = acos(min(1,0.20978-cos(x)))
</code>```

For simplicity, assemble these operations in a helper function

```<code>function [x,z] = solve_xz(y)
    x = fsolve(@(x) y^2-1413.7*x-1095.2*cos(x)+2169, 0);
    z = acos(min(1,0.20978-cos(x)));
end
</code>```

Now use that to get the ODE for y

```<code>function dy = ode_y(t,y)
    [x,z] = solve_xz(y(1));
    dy = [ y(2); y(3); 6666.6667*(z-x)-333.3333*y(1)-33.3333*y(2)-5*y(3) ];
end
</code>```

and apply the ODE solver of your choice. It is quite likely that the system is stiff, so ode45 might not be the best solver.

Body:
If you know y, you can solve for x, and this even unconditionally as the second equation in monotonous in x

x = fsolve(@(x) y^2-1413.7*x-1095.2*cos(x)+2169, 0)

Then once you know x, you can solve for z using the known inverse cosine

z = acos(0.20978-cos(x))

This may actually fail to give a result if cos(x) comes close to -1. One can artificially cut out that error, introducing a possibly wrong solution

z = acos(min(1,0.20978-cos(x)))

For simplicity, assemble these operations in a helper function

function [x,z] = solve_xz(y)
    x = fsolve(@(x) y^2-1413.7*x-1095.2*cos(x)+2169, 0);
    z = acos(min(1,0.20978-cos(x)));
end

Now use that to get the ODE for y

function dy = ode_y(t,y)
    [x,z] = solve_xz(y(1));
    dy = [ y(2); y(3); 6666.6667*(z-x)-333.3333*y(1)-33.3333*y(2)-5*y(3) ];
end

and apply the ODE solver of your choice. It is quite likely that the system is stiff, so ode45 might not be the best solver.


问:
Amazon S3 Static Web Hosting with ASPX file extension but pure HTML
Is it possible to host web pages with .aspx extension but without dynamic code, including only HTML?

For example, index.aspx as

```<code><!doctype html>
<head>
<meta http-equiv="content-type" content="text/html">
</head>
<body>
This is a fake ASPX page
</body>
</html>
</code>```

答:
Yes you can

Example

When you upload your file add the following metatag

Content-Type: text/html

In this case, the object is public

Body:
Is it possible to host web pages with .aspx extension but without dynamic code, including only HTML?

For example, index.aspx as

<!doctype html>

<meta http-equiv="content-type" content="text/html">

This is a fake ASPX page