问:
Function arguments in javascript
I am coming from python and trying to learn JavaScript. I noticed that when, by accident, I tried to call a function with the wrong number of arguments, it didn't raised an error and just returned Nan.

What's the explanation for this behavior?

EDIT: Get warning when passing too few arguments to a javascript function

This is exaclty what i was looking for, thank you @Code-Apprentice

答:
You should add an example or code part of what you mean when you're asking a question. Anywayyyy... For your question you can read about this here.

TL;DR?

Parameter Rules

JavaScript function definitions do not specify data types for parameters.

JavaScript functions do not perform type checking on the passed arguments.

JavaScript functions do not check the number of arguments received.

Title: Function arguments in javascript


来源: stackexchange

问:
Here Fleet Telematics CalculateRoute service not accessible using api key
I'm trying to use the Here Fleet Telematics CalculateRoute.json service, to calculate trip costs (toll, etc). The sample page uses api_id and api_key for authentication. In my (Freemium) account, I don't see a way where I can generate that.

What I did is copy the request the sample site makes, and replace the app_id and app_key parameters with apikey=**key**. I also removed the jsoncallback parameter.
I get the back following JSON:

```<code>{
  "faultCode": "s14e781b4-b577-4b58-86bb-359ee5c8a979",
  "responseCode": "400",
  "message": "The request is missing the app_id and app_code parameters. They must both be passed as query parameters. If you do not have app_id and app_code, please obtain them through your customer representative or at http://developer.here.com/myapps."
}
</code>```

Update:
What I hope to achieve, is use the POST http method. According to https://developer.here.com/documentation/fleet-telematics/api-reference.html, section "Calculates a route with additional fleet telematics features", that should be possible.

The exact request message is (without actual api key):

```<code>POST https://fleet.ls.hereapi.com/2/calculateroute.json
Content-Type: application/json

{
    "apiKey": "**SNIP**",
    "waypoint0": "38.72639,-9.14949",
    "waypoint1": "47.54881,7.58782",
    "detail": "1",
    "maneuverAttributes": "none",
    "linkAttributes": "none,sh",
    "legAttributes": "none,li",
    "currency": "EUR",
    "departure": "",
    "tollVehicleType": "3",
    "trailerType": "2",
    "trailersCount": "1",
    "vehicleNumberAxles": "3",
    "trailerNumberAxles": "2",
    "hybrid": "0",
    "emissionType": "5",
    "fuelType": "diesel",
    "height": "4m",
    "trailerHeight": "400",
    "vehicleWeight": "12000",
    "limitedWeight": "40t",
    "disabledEquipped": "0",
    "minimalPollution": "0",
    "hov": "0",
    "passengersCount": "1",
    "tiresCount": "14",
    "commercial": "1",
    "heightAbove1stAxle": "1m",
    "width": "2.55",
    "length": "16.5",
    "mode": "fastest;truck;traffic:disabled",
    "rollups": "none,country;tollsys",
    "alternatives": "1"
}
</code>```

This returns the following:

```<code>HTTP/1.1 401 Unauthorized
Content-Type: application/json
Date: Mon, 01 Jun 2020 11:10:09 GMT
Server: nginx-clojure
Content-Length: 74
Connection: Close

{
  "error": "Unauthorized",
  "error_description": "Token or apiKey is missing."
}
</code>```

Whereas, passing all the same values as url arguments in a GET request works.

答:
You need to use the following endpoint:

https://fleet.ls.hereapi.com/2/calculateroute.json?apiKey={YOUR_API_KEY}&...
```

See Send a Request and Calculate Toll Cost documentation pages.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use the Here Fleet Telematics CalculateRoute.json service, to calculate trip costs (toll, etc). The sample page uses api_id and api_key for authentication. In my (Freemium) account, I don't see a way where I can generate that.

What I did is copy the request the sample site makes, and replace the app_id and app_key parameters with apikey=**key**. I also removed the jsoncallback parameter.
I get the back following JSON:

{
  "faultCode": "s14e781b4-b577-4b58-86bb-359ee5c8a979",
  "responseCode": "400",
  "message": "The request is missing the app_id and app_code parameters. They must both be passed as query parameters. If you do not have app_id and app_code, please obtain them through your customer representative or at http://developer.here.com/myapps."
}

Update:
What I hope to achieve, is use the POST http method. According to https://developer.here.com/documentation/fleet-telematics/api-reference.html, section "Calculates a route with additional fleet telematics features", that should be possible.

The exact request message is (without actual api key):

POST https://fleet.ls.hereapi.com/2/calculateroute.json
Content-Type: application/json

{
    "apiKey": "**SNIP**",
    "waypoint0": "38.72639,-9.14949",
    "waypoint1": "47.54881,7.58782",
    "detail": "1",
    "maneuverAttributes": "none",
    "linkAttributes": "none,sh",
    "legAttributes": "none,li",
    "currency": "EUR",
    "departure": "",
    "tollVehicleType": "3",
    "trailerType": "2",
    "trailersCount": "1",
    "vehicleNumberAxles": "3",
    "trailerNumberAxles": "2",
    "hybrid": "0",
    "emissionType": "5",
    "fuelType": "diesel",
    "height": "4m",
    "trailerHeight": "400",
    "vehicleWeight": "12000",
    "limitedWeight": "40t",
    "disabledEquipped": "0",
    "minimalPollution": "0",
    "hov": "0",
    "passengersCount": "1",
    "tiresCount": "14",
    "commercial": "1",
    "heightAbove1stAxle": "1m",
    "width": "2.55",
    "length": "16.5",
    "mode": "fastest;truck;traffic:disabled",
    "rollups": "none,country;tollsys",
    "alternatives": "1"
}

This returns the following:

HTTP/1.1 401 Unauthorized
Content-Type: application/json
Date: Mon, 01 Jun 2020 11:10:09 GMT
Server: nginx-clojure
Content-Length: 74
Connection: Close

{
  "error": "Unauthorized",
  "error_description": "Token or apiKey is missing."
}

Whereas, passing all the same values as url arguments in a GET request works.

Body:
You need to use the following endpoint:

https://fleet.ls.hereapi.com/2/calculateroute.json?apiKey={YOUR_API_KEY}&...

See Send a Request and Calculate Toll Cost documentation pages.


问:
Get substring from twitter source in R
I have a dataframe in which one column is the twitter source, however, right now it looks messy. To clean it I would like to extract only: Twitter for iPhone, Twitter for Android, etc.

So I want to extract all text between ">" and "<"

Thank you

答:
You can use sub plus backreference:

Data:

```<code>df <- data.frame(source = '<ref=""http://twitter.com/download/iphone"rel=""nofollow"">Twitter for iPhone </a>')
</code>```

Solution:

```<code>sub('.*nofollow"">(Twitter for \\w+\\b).*', '\\1', df$source)
</code>```

Alternatively, you can use str_extract and positive lookbehind and lookahead:

```<code>library(stringr)
str_extract(df$source, '(?<=nofollow"">)[\\w\\s]+(?=\\s</a>)')
</code>```

Result:

```<code>[1] "Twitter for iPhone"
</code>```

Title: Get substring from twitter source in R

Body:
You can use sub plus backreference:

Data:

df <- data.frame(source = '<ref=""http://twitter.com/download/iphone"rel=""nofollow"">Twitter for iPhone </a>')

Solution:

sub('.*nofollow"">(Twitter for \\w+\\b).*', '\\1', df$source)

Alternatively, you can use str_extract and positive lookbehind and lookahead:

library(stringr)
str_extract(df$source, '(?<=nofollow"">)[\\w\\s]+(?=\\s</a>)')

Result:

[1] "Twitter for iPhone"


问:
Align Materials to same widths and heights without a Table
I created a material for my app which should enclose some text. It looks like this:

Sometimes, there is overflowing text. With a flexible it looks like this:

And I also want it to align like in a Table. Without alignment to the others it looks like this:

The Border between the colors should be at the same position for all of those elements so it looks clean.

How can I achieve all of this? The Flexible Widget throws a WrongParent Exception when Put into a Table.

My Code:

```<code>import 'dart:math';

import 'package:flutter/material.dart';

import 'nook_constants.dart';

class NookTable extends StatelessWidget {
  final double width;
  final double height;
  final EdgeInsets margin;
  final Widget child;
  final String title;
  final String text;
  final String font;

  NookTable({
    this.width,
    this.height,
    this.margin: nookDefaultMargin,
    this.child,
    this.title,
    this.text,
    this.font
  });

  final cell = (Widget widget) => Padding(
      padding: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      child: widget,
    );

  @override
  Widget build(BuildContext context) {
    var margin = EdgeInsets.only(
      left: this.margin?.left ?? 0.0,
      right: this.margin?.right ?? 0.0,
      top: this.margin?.top ?? 0.0,
      bottom: max(2, this.margin?.bottom ?? 0.0),
    );

    return Container(
      width: width,
      height: height,
      clipBehavior: Clip.antiAlias,
      margin: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      decoration: BoxDecoration(
        color: Colors.transparent,
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          NookTitleDetails(text: title, width: width,),
          NookTextDetails(text: text,),
        ],
      ),
    );
  }
}

class NookTextDetails extends StatelessWidget {
  final String text;
  final String font;

  NookTextDetails({
    this.text,
    this.font
  });

  final cell = (Widget widget) => Padding(
      padding: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      child: widget,
    );

  @override
  Widget build(BuildContext context) {
    return Flexible(
      child: Material(
        clipBehavior: Clip.antiAlias,
        borderRadius: BorderRadius.only(bottomRight: Radius.circular(25), topRight: Radius.circular(25)),
        color: nookBeige,
        child: cell(Text(text))
      ),
    );
  }
}
class NookTitleDetails extends StatelessWidget {
  final String text;
  final String font;
  final double width;

  NookTitleDetails({
    this.text,
    this.font,
    this.width
  });

  final cell = (Widget widget) => Padding(
      padding: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      child: widget,
    );

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      child: Material(
        clipBehavior: Clip.antiAlias,
        borderRadius: BorderRadius.only(bottomLeft: Radius.circular(25), topLeft: Radius.circular(25)),
        color: nooklightGreen,
        child: cell(Text(text, style: TextStyle(color: nookWhite)))
      ),
    );
  }
}
</code>```

答:
```<code>               Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Flexible(
                      flex: 0,
                      child: Container(
                                    width:100,
                                    child:Text('Text to the left')
                                     )
                                  ),
                    Expanded(
                      flex: 4,
                     child:Text('Text to the right')

                    ),
                  ],
                ),
</code>```

Body:
I created a material for my app which should enclose some text. It looks like this:

Sometimes, there is overflowing text. With a flexible it looks like this:

And I also want it to align like in a Table. Without alignment to the others it looks like this:

The Border between the colors should be at the same position for all of those elements so it looks clean.

How can I achieve all of this? The Flexible Widget throws a WrongParent Exception when Put into a Table.

My Code:

import 'dart:math';

import 'package:flutter/material.dart';

import 'nook_constants.dart';

class NookTable extends StatelessWidget {
  final double width;
  final double height;
  final EdgeInsets margin;
  final Widget child;
  final String title;
  final String text;
  final String font;

  NookTable({
    this.width,
    this.height,
    this.margin: nookDefaultMargin,
    this.child,
    this.title,
    this.text,
    this.font
  });

  final cell = (Widget widget) => Padding(
      padding: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      child: widget,
    );

  @override
  Widget build(BuildContext context) {
    var margin = EdgeInsets.only(
      left: this.margin?.left ?? 0.0,
      right: this.margin?.right ?? 0.0,
      top: this.margin?.top ?? 0.0,
      bottom: max(2, this.margin?.bottom ?? 0.0),
    );

    return Container(
      width: width,
      height: height,
      clipBehavior: Clip.antiAlias,
      margin: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      decoration: BoxDecoration(
        color: Colors.transparent,
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          NookTitleDetails(text: title, width: width,),
          NookTextDetails(text: text,),
        ],
      ),
    );
  }
}

class NookTextDetails extends StatelessWidget {
  final String text;
  final String font;

  NookTextDetails({
    this.text,
    this.font
  });

  final cell = (Widget widget) => Padding(
      padding: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      child: widget,
    );

  @override
  Widget build(BuildContext context) {
    return Flexible(
      child: Material(
        clipBehavior: Clip.antiAlias,
        borderRadius: BorderRadius.only(bottomRight: Radius.circular(25), topRight: Radius.circular(25)),
        color: nookBeige,
        child: cell(Text(text))
      ),
    );
  }
}
class NookTitleDetails extends StatelessWidget {
  final String text;
  final String font;
  final double width;

  NookTitleDetails({
    this.text,
    this.font,
    this.width
  });

  final cell = (Widget widget) => Padding(
      padding: EdgeInsets.only(left: 15, top: 5, bottom: 5, right: 15),
      child: widget,
    );

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      child: Material(
        clipBehavior: Clip.antiAlias,
        borderRadius: BorderRadius.only(bottomLeft: Radius.circular(25), topLeft: Radius.circular(25)),
        color: nooklightGreen,
        child: cell(Text(text, style: TextStyle(color: nookWhite)))
      ),
    );
  }
}


答:
```<code>dane.groupBy (_._1.matches (".*-01-.*")).slice (0, 1).map (x => x._2).flatten .map (y => y._2).sum
</code>```

I really should look up 'collect', which somehow should replace my map/flatten/map.

My result is: Double = 2234.29

ContentLicense: CC BY-SA 3.0

Title: Complex multi-dimensional list operations in Scala

Body:
Given a list such as the following:

val dane = List(
    ("2011-01-04", -137.76),
    ("2011-01-04", 2376.45),
    ("2011-01-04", -1.70),
    ("2011-01-04", -1.70),
    ("2011-01-04", -1.00),
    // ... skip a few ...
    ("2011-12-22", -178.02),
    ("2011-12-29", 1800.82),
    ("2011-12-23", -83.97),
    ("2011-12-24", -200.00),
    ("2011-12-24", -30.55),
    ("2011-12-30", 728.00)
)

I'd like to sum the values (i.e. the second item of the inner lists) of a specific month (e.g. January, or 01), using the following operations in the specified order:

groupBy

slice

collect

sum

Body:
dane.groupBy (_._1.matches (".*-01-.*")).slice (0, 1).map (x => x._2).flatten .map (y => y._2).sum

I really should look up 'collect', which somehow should replace my map/flatten/map.

My result is: Double = 2234.29


问:
Force line break after inline-block element using CSS
I am currently trying to make a simple form. As an example, this is what I'm trying to get it to look like.

This is the current architecture for each field:

    First Name
    <input></input>

```

<p>I struggle once I get to the CSS part. Here's a full example, and any help would be greatly appreciated</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
    text-align: center;
}

form p {
    display: inline-block;
}

form label {
    text-align: left;
    display: block;
}</code>```

    <form>

Name: <input type="text">

Password: <input type="text">

    </form>

```

I just cannot figure out how to get a line break after the input with the current CSS.

答:
can use float instead of inline-block

form {
    max-width: max-content;
    margin: auto;
}

form p {
    float: left;
    clear: left;
}
```

Body:
I am currently trying to make a simple form. As an example, this is what I'm trying to get it to look like.

This is the current architecture for each field:

    First Name
    <input></input>

I struggle once I get to the CSS part. Here's a full example, and any help would be greatly appreciated

div {
    text-align: center;
}

form p {
    display: inline-block;
}

form label {
    text-align: left;
    display: block;
}

    <form>

Name: <input type="text">

Password: <input type="text">

    </form>

I just cannot figure out how to get a line break after the input with the current CSS.


问:
Cloud Formation: Environment failed to launch as it entered Terminated state
I am building an elastic beanstalk environment. I get the above error when I run the template. I have added the IAM roles giving full EC2 access to cloud formation

```<code> Resources:
  TestApp:
    Type: 'AWS::ElasticBeanstalk::Application'
    Properties: {}
    Metadata:
      'AWS::CloudFormation::Designer':
        id: 53bb2af6-3a68-487a-8048-34f111147171

  EBE1RNK0:
    Type: 'AWS::ElasticBeanstalk::Environment'
    Properties:
      ApplicationName: !Ref TestApp
      Description: AWS Elastic Beanstalk Environment running Node Sample Application
      EnvironmentName: NodejsEnvironment
      SolutionStackName: 64bit Amazon Linux 2 v5.0.1 running Node.js 12
      OptionSettings:
        - Namespace: aws:autoscaling:launchconfiguration
          OptionName: InstanceType
          Value: t1.micro
</code>```

答:
SOLVED: I have missed out on adding the instance profile, as that would enable me to pass information to an EC2 when the instance starts running. </p>

<p>This should be below your options settings. Show below. </p>

```<code>OptionSettings:
    - Namespace: 'aws:autoscaling:launchconfiguration'
      OptionName: IamInstanceProfile
      Value: aws-elasticbeanstalk-ec2-role
</code>```

Body:
I am building an elastic beanstalk environment. I get the above error when I run the template. I have added the IAM roles giving full EC2 access to cloud formation

 Resources:
  TestApp:
    Type: 'AWS::ElasticBeanstalk::Application'
    Properties: {}
    Metadata:
      'AWS::CloudFormation::Designer':
        id: 53bb2af6-3a68-487a-8048-34f111147171

  EBE1RNK0:
    Type: 'AWS::ElasticBeanstalk::Environment'
    Properties:
      ApplicationName: !Ref TestApp
      Description: AWS Elastic Beanstalk Environment running Node Sample Application
      EnvironmentName: NodejsEnvironment
      SolutionStackName: 64bit Amazon Linux 2 v5.0.1 running Node.js 12
      OptionSettings:
        - Namespace: aws:autoscaling:launchconfiguration
          OptionName: InstanceType
          Value: t1.micro

Body:
SOLVED: I have missed out on adding the instance profile, as that would enable me to pass information to an EC2 when the instance starts running.

This should be below your options settings. Show below.

OptionSettings:
    - Namespace: 'aws:autoscaling:launchconfiguration'
      OptionName: IamInstanceProfile
      Value: aws-elasticbeanstalk-ec2-role


问:
Laravel: Can't change db connection from local to remote
Well, this is killing me.

I tried everything possible to change the connection inside a Laravel project but nothing works and keeps tied to a local database connection that I have.
These are the two databases that my project has:

I worked most of the time with the local one, but I need to run some commands on the production one (I can connect easily with MySQL Workbench since my IP is on the whitelist), so I need to change it. My ".env" and my "database.php" config are pointing to the ip of the production database, I have run all the commands for clearing the cache php artisan config:clear->php artisan cache:clear-> php artisan config:cache, and after that I see also my bootstrap/cache/config.php with the proper data.

I know that is reading my .env file because if I change APP_ENV=production to APP_ENV=testdummychange and running php artisan env is retrieving the change as expected.

Tinker

By using Tinker to check the connection I see:

And I'm invoking a Model from Tinker that exists both in production and local, but in local has some dummy test and ALWAYS retrieves the value from the local one:

And, despite the warnings you can see the same result instantly, I mean, I know that nothing is cached:

Is good to mention that I'm using XAMPP to run the MySQL Service on port 3306, and despite the lack of common sense I'm starting to think that this client is storing some credentials or something, because there is not any other place where I can place the DB credentials on a Laravel project.

Is there any other possible place that is storing my db credentials on a Laravel/PHP project? I'm out of ideas.

答:
Ok, first of all thanks for @MaartenDevand and @Ryan Vincent who tried to help me.

For those who could be facing a problem like this, I found out that the DB_SOCKET configured on my .env file which configures the "unix socket" wasn't working remotely and that was causing my connection string to be overriden.

Simply removing the DB_SOCKET key, everything is working again.


问:
WindowBuilder SWT Table
Can you suggest me how to build a Table with Eclipse WindowBuilder Plugin and SWT?

I read the official docs but I found orrible example with fixed column size. I would like to build a Table who fit the parent container (I used composite) when it is resized.

P.S.: Maybe I should use Swing instead?? All valid example I have seen are with JTable..

Can you help me?

Thank you

Thank you for your reply!

I have to do a little GUI application for a friend, I'm not so practice nor with Swing neither with SWT.

Anyway I manage to do a Simple ApplicationWindow with menubar, some submenu item and a composite container under the menu where panel should appear when user clicks on menu item.

Than I manage to build a TableViewer inside that composite component.. but now I would like add another table in the same place (the table represents different thing and should appear or disappear when user click some menu button).

In Swing I see many example of CardLayout but nothing with SWT.

Can you suggest me a simple example of layered layout with SWT?? I have the impression that Swing is much more simple..

Thank you all

答:
On my modest opinion, Swing is well documented than SWT and maybe more simple. I switched to it.

Thank you.

Title: WindowBuilder SWT Table


问:
Array Sorting according to two or more values
How can i accomplish sorting an array according to two values.
Is there built in function for that?</p>

答: Use the sortOn() function.</p>

Body: Use the sortOn() function.


问:
How to properly call service methods from interceptor in angular
I am trying to build an error interceptor in my angular app. I imported the auth service into it through the constructor. But I am getting an error when I call a method from it that it does not exist. This is the interceptor.

```<code>
 import {Injectable } from '@angular/core';
 import {
    HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse
} from '@angular/common/http';
import { AuthService } from '../auth/auth.service';

import {Observable, throwError} from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor{

    constructor(
        private authService: AuthService,
    ){

    }
     intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{

        return next.handle(req).pipe(
            catchError(this.handleError)
        );
    }

    private handleError(error: HttpErrorResponse) {
        if(error.status === 401){
            this.authService.logout();
        }
        return throwError(error);
    }
}

</code>```

And this is my auth-service.

```<code>import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    url = 'http://localhost:3000/users/login'
    isLoggedIn = false;
    constructor(private http: HttpClient) { }
    redirectUrl: string;

    login(credentials): Observable<any> {
        return this.http.post<any>(this.url, credentials).pipe(catchError(err => {
            return throwError(err);
        }));
    }

    logout(): void {
        localStorage.removeItem('token');
        this.isLoggedIn = false;
    }

    getAuthToken(): string{
        return localStorage.getItem('token');
    }
}
</code>```

After I try to run it, I get TypeError: Cannot read property 'logout' of undefined

答:
there is an answer to this question here but it was difficult to find.

When providing dependencies to inject into your Interceptors, you need to declare them under the deps key in the same object that defined your Interceptor in your Module. The following is an example:

```<code>{
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorInterceptor,
    deps: [AuthService]
},
</code>```

Hope this helps

Body:
I am trying to build an error interceptor in my angular app. I imported the auth service into it through the constructor. But I am getting an error when I call a method from it that it does not exist. This is the interceptor.

 import {Injectable } from '@angular/core';
 import {
    HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse
} from '@angular/common/http';
import { AuthService } from '../auth/auth.service';

import {Observable, throwError} from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor{

    constructor(
        private authService: AuthService,
    ){

    }
     intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{

        return next.handle(req).pipe(
            catchError(this.handleError)
        );
    }

    private handleError(error: HttpErrorResponse) {
        if(error.status === 401){
            this.authService.logout();
        }
        return throwError(error);
    }
}

And this is my auth-service.

import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    url = 'http://localhost:3000/users/login'
    isLoggedIn = false;
    constructor(private http: HttpClient) { }
    redirectUrl: string;

    login(credentials): Observable<any> {
        return this.http.post<any>(this.url, credentials).pipe(catchError(err => {
            return throwError(err);
        }));
    }

    logout(): void {
        localStorage.removeItem('token');
        this.isLoggedIn = false;
    }

    getAuthToken(): string{
        return localStorage.getItem('token');
    }
}

After I try to run it, I get TypeError: Cannot read property 'logout' of undefined

Body:
there is an answer to this question here but it was difficult to find.

When providing dependencies to inject into your Interceptors, you need to declare them under the deps key in the same object that defined your Interceptor in your Module. The following is an example:

{
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorInterceptor,
    deps: [AuthService]
},

Hope this helps


问:
Enable hover for touch/click on mobile
Everything works the way it should on desktop view but the DIV which shows on hover in desktop doesn't show in mobile view. I want to show that DIV on touch/click in mobile/tablet.

As per some suggestions, I tried with :active after :hover too but that doesn't work.

I don't mind JS or jQuery answers too.

DEMO: https://jsfiddle.net/ovg6xzhu/

HTML:

```<code><div class="hoverEffect hoverEffect-first">
  <img src="https://via.placeholder.com/150" />
  <div class="mask">
    <h2>Web Services!</h2>
    <p>We are going to build another sets of css hover image effects with CSS3 animations.<br /><a href="#">View All</a></p>
  </div>
</div>
</code>```

CSS:

```<code>.hoverEffect {
  width: 100%;
  float: left;
  overflow: hidden;
  position: relative;
  text-align: center;
  cursor: default;
  border-radius: 2px;
  margin-bottom: 30px;
}
.hoverEffect .mask {
  width: 100%;
  position: absolute;
  overflow: hidden;
  top: 0;
  left: 0
}
.hoverEffect img {
  display: block;
  position: relative
}
.hoverEffect h2 {
  text-transform: uppercase;
  color: #fff;
  text-align: center;
  position: relative;
  padding: 10px;
  margin: 20px 0 0 0
}
.hoverEffect p {
  position: relative;
  color: #fff;
  padding: 0px 20px 20px;
  text-align: center
}
.hoverEffect-first img {
  transition: all 0.2s linear;
  width:100%;
  height:auto;
}
.hoverEffect-first .mask {
  opacity: 0;
  background-color: rgba(61, 90, 128, 0.95);
  transition: all 0.4s ease-in-out;
  width: 100%;
  height: 100%;
}
.hoverEffect-first h2 {
  margin: 10px 40px;
  transform: translateY(-100px);
  opacity: 0;
  transition: all 0.2s ease-in-out;
}
.hoverEffect-first p {
  transform: translateY(100px);
  opacity: 0;
  transition: all 0.2s linear;
}
.hoverEffect-first:hover img, .hoverEffect-first:active img {
  transform: scale(1.1);
}
.hoverEffect-first:hover .mask, .hoverEffect-first:active .mask {
  opacity: 1;
}
.hoverEffect-first:hover h2,
.hoverEffect-first:hover p,
.hoverEffect-first:active h2,
.hoverEffect-first:active p {
  opacity: 1;
  transform: translateY(0px);
}
.hoverEffect-first:hover p, .hoverEffect-first:active p {
  transition-delay: 0.1s;
}
.hoverEffect-first:hover a.info, .hoverEffect-first:active a.info {
  transition-delay: 0.2s;
}
</code>```

答: Your code is working. Always make sure to clear your browser cache. A quick trick to do this on mobile would be to add " /?random " at the end of your url to get a fresh load. Make sure to change " random " to anything you wish per refresh so it keeps sending you a fresh load. That said I would also have to agree with ehab's answer, it's not very intuitive to show/hide your content upon hovering on mobile. Add visual indicators like a button or let the animation take place naturally when it enters the viewport. </p>

Title: Enable hover for touch/click on mobile

Body:
Everything works the way it should on desktop view but the DIV which shows on hover in desktop doesn't show in mobile view. I want to show that DIV on touch/click in mobile/tablet.

As per some suggestions, I tried with :active after :hover too but that doesn't work.

I don't mind JS or jQuery answers too.

DEMO: https://jsfiddle.net/ovg6xzhu/

HTML:

Web Services!

We are going to build another sets of css hover image effects with CSS3 animations.
View All

CSS:

.hoverEffect {
  width: 100%;
  float: left;
  overflow: hidden;
  position: relative;
  text-align: center;
  cursor: default;
  border-radius: 2px;
  margin-bottom: 30px;
}
.hoverEffect .mask {
  width: 100%;
  position: absolute;
  overflow: hidden;
  top: 0;
  left: 0
}
.hoverEffect img {
  display: block;
  position: relative
}
.hoverEffect h2 {
  text-transform: uppercase;
  color: #fff;
  text-align: center;
  position: relative;
  padding: 10px;
  margin: 20px 0 0 0
}
.hoverEffect p {
  position: relative;
  color: #fff;
  padding: 0px 20px 20px;
  text-align: center
}
.hoverEffect-first img {
  transition: all 0.2s linear;
  width:100%;
  height:auto;
}
.hoverEffect-first .mask {
  opacity: 0;
  background-color: rgba(61, 90, 128, 0.95);
  transition: all 0.4s ease-in-out;
  width: 100%;
  height: 100%;
}
.hoverEffect-first h2 {
  margin: 10px 40px;
  transform: translateY(-100px);
  opacity: 0;
  transition: all 0.2s ease-in-out;
}
.hoverEffect-first p {
  transform: translateY(100px);
  opacity: 0;
  transition: all 0.2s linear;
}
.hoverEffect-first:hover img, .hoverEffect-first:active img {
  transform: scale(1.1);
}
.hoverEffect-first:hover .mask, .hoverEffect-first:active .mask {
  opacity: 1;
}
.hoverEffect-first:hover h2,
.hoverEffect-first:hover p,
.hoverEffect-first:active h2,
.hoverEffect-first:active p {
  opacity: 1;
  transform: translateY(0px);
}
.hoverEffect-first:hover p, .hoverEffect-first:active p {
  transition-delay: 0.1s;
}
.hoverEffect-first:hover a.info, .hoverEffect-first:active a.info {
  transition-delay: 0.2s;
}


问:
Get the console log of website and send to websocket
I have the following situation:

I want to get the console log of a website and send that to WebSocket clients.

I was able to create a node server and send data to connected users with below code.

const puppeteer = require('puppeteer');
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 2222 });

wss.on('connection', function connection(ws) {
  ws.send("sending the sample data");
});
```

<p>I was able to get the console log of website using following code:</p>

<pre class="lang-js prettyprint-override"><code>(async () => {
  const browser = await puppeteer.launch({
    args: [
      '--no-sandbox',
      '--headless',
      '--disable-gpu',
      '--window-size=1920x1080'
    ]
  });

  const page = await browser.newPage();

  await page.goto('https://example.com/test.php');

  page.on('console', msg => console.log(msg.text()));

})();
</code>```

Here page.on is a callback function, which is called every time there is a console log. How do I broadcast that msg (console.log from puppeteer) to WebSocket clients?

Please note that the website is opened once only when the app is started and console.log output is generated using setInterval every second. So new users get only the latest data.

答:
Instead of console.log(msg.text()) you need to broadcast the message to all ws clients, right?

So a simple code will be:

```<code>page.on('console', msg => {
  wss.clients.forEach(function each(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(msg.text());
    }
  });
});
</code>```

Read here for more info

Body:
I have the following situation:

I want to get the console log of a website and send that to WebSocket clients.

I was able to create a node server and send data to connected users with below code.

const puppeteer = require('puppeteer');
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 2222 });

wss.on('connection', function connection(ws) {
  ws.send("sending the sample data");
});

I was able to get the console log of website using following code:

(async () => {
  const browser = await puppeteer.launch({
    args: [
      '--no-sandbox',
      '--headless',
      '--disable-gpu',
      '--window-size=1920x1080'
    ]
  });

  const page = await browser.newPage();

  await page.goto('https://example.com/test.php');

  page.on('console', msg => console.log(msg.text()));

})();

Here page.on is a callback function, which is called every time there is a console log. How do I broadcast that msg (console.log from puppeteer) to WebSocket clients?

Please note that the website is opened once only when the app is started and console.log output is generated using setInterval every second. So new users get only the latest data.

Body:
Instead of console.log(msg.text()) you need to broadcast the message to all ws clients, right?

So a simple code will be:

page.on('console', msg => {
  wss.clients.forEach(function each(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(msg.text());
    }
  });
});

Read here for more info


问:
Stripe confirmCardSetup with custom card data for payment method
```<code>stripe.confirmCardSetup(clientSecret,
        {
          payment_method: {
            card: {
               number: this.state.form.values.number,
            exp_month: this.state.form.values.expiry.substring(0,2),
            exp_year: this.state.form.values.expiry.substring(3,5),
            cvc: this.state.form.values.cvc,
             },
            billing_details: {
              name: name,
            },
          },
        }
      ).then(function(result) {...})
</code>```

I was trying to create a payment method that can be used later by the customer through stripe's confirmCardSetup, not using stripe elements but with card info (number, cvc, expiry date) passed into the payment method field. It didn't work, and I'm wondering if I can do something of this nature? (We're on react native and don't want to use tipsi-stripe)

答:
I figured out how to make this work. Here's the solution in case anyone else comes across this same issue:

```<code>var paymentMethod = {
  payment_method: {
    card: this.cardNumberElement,
    billing_details: {
      name: this.billingNameText.getValue()
    }
  }
};

stripe.confirmCardSetup(setupIntentSecret, paymentMethod)
      .then(function(result) { ... });
</code>```

This works if you assign the property card to the cardElement object you created using this code:

```<code>this.elements = this.stripe.elements();
this.cardNumberElement = this.elements.create('cardNumber');
this.cardNumberElement.mount('#card-number');
this.cardExpiryElement = this.elements.create('cardExpiry');
this.cardExpiryElement.mount('#card-expiry');
this.cardCvcElement = this.elements.create('cardCvc');
this.cardCvcElement.mount('#card-cvc');
</code>```

The key is that you must create all the components from the same elements object. This will associate all of the components together and send all of the information from all of the objects over to the Stripe API.

Body:
stripe.confirmCardSetup(clientSecret,
        {
          payment_method: {
            card: {
               number: this.state.form.values.number,
            exp_month: this.state.form.values.expiry.substring(0,2),
            exp_year: this.state.form.values.expiry.substring(3,5),
            cvc: this.state.form.values.cvc,
             },
            billing_details: {
              name: name,
            },
          },
        }
      ).then(function(result) {...})

I was trying to create a payment method that can be used later by the customer through stripe's confirmCardSetup, not using stripe elements but with card info (number, cvc, expiry date) passed into the payment method field. It didn't work, and I'm wondering if I can do something of this nature? (We're on react native and don't want to use tipsi-stripe)

Body:
I figured out how to make this work. Here's the solution in case anyone else comes across this same issue:

var paymentMethod = {
  payment_method: {
    card: this.cardNumberElement,
    billing_details: {
      name: this.billingNameText.getValue()
    }
  }
};

stripe.confirmCardSetup(setupIntentSecret, paymentMethod)
      .then(function(result) { ... });

This works if you assign the property card to the cardElement object you created using this code:

this.elements = this.stripe.elements();
this.cardNumberElement = this.elements.create('cardNumber');
this.cardNumberElement.mount('#card-number');
this.cardExpiryElement = this.elements.create('cardExpiry');
this.cardExpiryElement.mount('#card-expiry');
this.cardCvcElement = this.elements.create('cardCvc');
this.cardCvcElement.mount('#card-cvc');

The key is that you must create all the components from the same elements object. This will associate all of the components together and send all of the information from all of the objects over to the Stripe API.


问:
Heorku Application Open Failure
I am trying to deploy me react app on Heroku. Everything says deployed on Heroku but when I type Heroku open, it says application error and the winddow suggests to do Heroku --tail. When I do Heroku --tail on command line, I receive the following error:

```<code> State changed from starting to crashed
2020-05-31T21:02:37.775855+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=ancient-gorge-48530.herokuapp.com request_id=d9a3fe26-753e-417d-b296-b77f9ea48280 fwd="24.105.211.206" dyno= connect= service= status=503 bytes= protocol=https
2020-05-31T21:02:39.965317+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=ancient-gorge-48530.herokuapp.com request_id=b767e1b3-d89d-4cf1-b762-aa7ca6b06496 fwd="24.105.211.206" dyno= connect= service= status=503 bytes= protocol=https
2020-05-31T21:02:47.963754+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=ancient-gorge-48530.herokuapp.com request_id=252ba8b0-1413-4762-8f9e-866f4ce263dc fwd="24.105.211.206" dyno= connect= service= status=503 bytes= protocol=https
2020-05-31T21:02:48.946628+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=ancient-gorge-48530.herokuapp.com request_id=ec439c87-bbdd-4880-a3e9-f93911527f1f fwd="24.105.211.206" dyno= connect= service= status=503 bytes= protocol=https
2020-05-31T21:03:34.544211+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=ancient-gorge-48530.herokuapp.com request_id=0d845c3c-198e-48a0-b8ed-225a89af5af0 fwd="24.105.211.206" dyno= connect= service= status=503 bytes= protocol=https
2020-05-31T21:03:36.818111+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=ancient-gorge-48530.herokuapp.com request_id=d179d8d0-da44-4353-99d3-776cb60fa7a4 fwd="24.105.211.206" dyno= connect= service= status=503 bytes= protocol=https
</code>```

答: The problem usually comes from Procfile, make sure your Procfile was properly set up

Title: Heorku Application Open Failure

Body:
I am trying to deploy me react app on Heroku. Everything says deployed on Heroku but when I type Heroku open, it says application error and the winddow suggests to do Heroku --tail. When I do Heroku --tail on command line, I receive the following error:

 State changed from starting to crashed
2020-05-31T21:02:37.775855+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=ancient-gorge-48530.herokuapp.com request_id=d9a3fe26-753e-417d-b296-b77f9ea48280 fwd="24.105.211.206" dyno= connect= service= status=503 bytes= protocol=https
2020-05-31T21:02:39.965317+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=ancient-gorge-48530.herokuapp.com request_id=b767e1b3-d89d-4cf1-b762-aa7ca6b06496 fwd="24.105.211.206" dyno= connect= service= status=503 bytes= protocol=https
2020-05-31T21:02:47.963754+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=ancient-gorge-48530.herokuapp.com request_id=252ba8b0-1413-4762-8f9e-866f4ce263dc fwd="24.105.211.206" dyno= connect= service= status=503 bytes= protocol=https
2020-05-31T21:02:48.946628+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=ancient-gorge-48530.herokuapp.com request_id=ec439c87-bbdd-4880-a3e9-f93911527f1f fwd="24.105.211.206" dyno= connect= service= status=503 bytes= protocol=https
2020-05-31T21:03:34.544211+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=ancient-gorge-48530.herokuapp.com request_id=0d845c3c-198e-48a0-b8ed-225a89af5af0 fwd="24.105.211.206" dyno= connect= service= status=503 bytes= protocol=https
2020-05-31T21:03:36.818111+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=ancient-gorge-48530.herokuapp.com request_id=d179d8d0-da44-4353-99d3-776cb60fa7a4 fwd="24.105.211.206" dyno= connect= service= status=503 bytes= protocol=https


问:
How POCO (de)serialization works in protobuf-net?
Is it possible to (de)serialize a POCO type using neither protobuf-net attributes nor explicitly adding types into the model?</p>

答:
At the moment - in short, no. It needs to have a basic understanding of how you intend it to operate. I guess maybe I could add something to let you specify a default strategy for completely unadorned types (things that aren't DataContract, ProtoContract or XmlType), but the most appropriate option there would be "all public members" (much like XmlSerializer).

The reason I don't want to encourage this is that it is brittle. Because of how the protobuf spec is defined, all you get is field-numbers. It is easy enough to say "ok, order them alphabetically and use their positions", but that is not safe if you ever want to change the type. And let's face it, we all do. You'd be amazed how often I add an AardvarkCount property, which messes with alphabetical orderings.

Hence, I don't want to make it easy to get people into a position where they risk data integrity. Because I don't like people shouting at me. If there was a global default policy, it would be easy to use that policy without realising it, which is when you start getting into trouble.

I do, however, intend making it easier to choose those strategies on a per-type basis (the code all exists, it just isn't in the public API) - for example:

```<code>model.Add(typeof(MyCrazyType), false).ApplyPolicy(ImplicitFields.AllPublic);
</code>```

(the ImplicitFields stuff already exists, back to v1 days) or maybe just:

```<code>model.Add(typeof(MyCrazyType), ImplicitFields.AllPublic);
</code>```

any help? does the reasoning make sense?

Body:
At the moment - in short, no. It needs to have a basic understanding of how you intend it to operate. I guess maybe I could add something to let you specify a default strategy for completely unadorned types (things that aren't DataContract, ProtoContract or XmlType), but the most appropriate option there would be "all public members" (much like XmlSerializer).

The reason I don't want to encourage this is that it is brittle. Because of how the protobuf spec is defined, all you get is field-numbers. It is easy enough to say "ok, order them alphabetically and use their positions", but that is not safe if you ever want to change the type. And let's face it, we all do. You'd be amazed how often I add an AardvarkCount property, which messes with alphabetical orderings.

Hence, I don't want to make it easy to get people into a position where they risk data integrity. Because I don't like people shouting at me. If there was a global default policy, it would be easy to use that policy without realising it, which is when you start getting into trouble.

I do, however, intend making it easier to choose those strategies on a per-type basis (the code all exists, it just isn't in the public API) - for example:

model.Add(typeof(MyCrazyType), false).ApplyPolicy(ImplicitFields.AllPublic);

(the ImplicitFields stuff already exists, back to v1 days) or maybe just:

model.Add(typeof(MyCrazyType), ImplicitFields.AllPublic);

any help? does the reasoning make sense?


问:
How to add required argument with optional flag
I'm writing a differ. The command line needs to handle two files - left and right. I would like the synapsis to be like this:

```<code>differ.py [-f] FILE1 [[-t] FILE2]
</code>```

WHERE -f is the option that accepts FILE1, -t accepts FILE2.
FILE1 is mandatory, FILE2 can be read from stdin or real file. I would like it to be used like this:

```<code>differ.py myfile1
differ.py myfile1 myfile2
differ.py myfile1 -t myfile2
differ.py -f myfile1
differ.py -f myfile1 myfile2
differ.py -f myfile1 -t myfile2
</code>```

Is it possible with argparse module? If so, then how?
Thanks in advance.

答:
This is not possible through argparse. It goes against too much of the design. An argument can't be both a positional argument and an option value, and which positional argument a positional argument is doesn't depend on the presence or position of options. You can't even work around any of this with mutually exclusive groups, because a positional argument can't be part of such a group. The help formatter isn't designed for any of this, either.

Even if you moved all the validation and help formatting out of argparse and into your own code, you'd be overriding so much and getting so little out of argparse that it'd be easier to just parse the command line manually.

If this is really the interface you want, it'll be easiest to parse sys.argv manually.

Body:
I'm writing a differ. The command line needs to handle two files - left and right. I would like the synapsis to be like this:

differ.py [-f] FILE1 [[-t] FILE2]

WHERE -f is the option that accepts FILE1, -t accepts FILE2.
FILE1 is mandatory, FILE2 can be read from stdin or real file. I would like it to be used like this:

differ.py myfile1
differ.py myfile1 myfile2
differ.py myfile1 -t myfile2
differ.py -f myfile1
differ.py -f myfile1 myfile2
differ.py -f myfile1 -t myfile2

Is it possible with argparse module? If so, then how?
Thanks in advance.


问:
img-responsive in Bootstrap does not work
according to http://getbootstrap.com/css/#images-responsive, I want to make my image to support a responsive website by using

```<code><img src="..." class="img-responsive" alt="Responsive image">
</code>```

But it is not working.

Here is my code,

```<code><body>
    <img class="img-responsive" src="images/myImage.png" />
</body>
</code>```

The original image size is 284x191

When I open a browser on 1920*1080 screen size, the image size is 284x191. But when I open a browser on 1280*720 screen size, the image size is still the same.

I don't know what I did wrong to reduce the image size dynamically.
Thanks for help.

答: use class="img-fluid" for bootstrap 4 version</p>

Body:
according to http://getbootstrap.com/css/#images-responsive, I want to make my image to support a responsive website by using

But it is not working.

Here is my code,

The original image size is 284x191

When I open a browser on 1920*1080 screen size, the image size is 284x191. But when I open a browser on 1280*720 screen size, the image size is still the same.

I don't know what I did wrong to reduce the image size dynamically.
Thanks for help.


问:
(C) String Changing Withing Data Structure When I Don't Want It To
Before I start, here is the block of code that is causing me problems.

```<code>
typedef struct SymbPair{
    char *symbol;
    int memoryAddress;
}SymbPair;

typedef struct SymbTable{
    SymbPair *pairs;
    int numberOfItems;
} SymbTable;

SymbTable createTable(){
  SymbTable table;
  table.pairs =  (SymbPair*) calloc(1,sizeof(SymbPair));
  table.numberOfItems = 0;
  return table;
}

int checkForColon(char *word){
  if (word[strlen(word) - 1] == ':'){
    return  1;
  } else {
  return 0;
  }
}

void removeLastChar(char *word, char *buffer){
  int size = strlen(word);
  char blank[size - 1];
  for (int i = 0; i < size - 1; i++){
    blank[i] = word[i];
  }
  blank[size - 1] = '\0';
  strcpy(buffer,blank);
}

void symbPairSet(char *word, int address, SymbPair *pair){
  pair -> memoryAddress = address;
  pair -> symbol = word;
}

void addToSymbTable(SymbPair sp, SymbTable *array){
  int currentTotal = array->numberOfItems;
  array -> pairs = (SymbPair*) realloc(array->pairs,currentTotal+2);
  array->pairs[currentTotal]=sp;
  array -> numberOfItems = currentTotal + 1;
}

void firstPass(SymbTable *table, char **instructions){
  int totalLabels = 0;
  int i = 0;
  while (instructions[i] != NULL){
    if (checkForColon(instructions[i])){
      char buffer[strlen(instructions[i]) - 1];
      removeLastChar(instructions[i],buffer);
      SymbPair new;
      symbPairSet(buffer,(i*4) - totalLabels,&new);
      addToSymbTable(new,table);
      totalLabels++;

  }
    i++;
}

}

int main(){
SymbTable table = createTable();
firstPass(&table,instructionArray);
return EXIT_SUCCESS;
}
</code>```

First pass takes in an array of strings and looks for strings that end in a colon and then removes the colon and adds the edited string into an array of symbol pairs which is held in a struct call symb table that holds the array and its size. With my current input there should be one item in the array with symbol loop and address 8. My issue is that within the firstPass function the string has the correct value but once it is passed into the value in main it changes completely. The value for the symbol (or the string) changes from inside the firstPass function to when it is being assigned in the main but it should be the same. Any help?

Here is a link to an image of the debugger after the SymbPair is first set

Here is what happens only a few steps afer

答:
If you have this:

```<code>char blank[size - 1];
</code>```

then this

```<code>blank[size - 1] = '\0';
</code>```

is writing outside your array as it only has elements 0 to size - 2

if you write outside your variables you're changing other data, which seems consistent with your problem.

Body:
Before I start, here is the block of code that is causing me problems.

typedef struct SymbPair{
    char *symbol;
    int memoryAddress;
}SymbPair;

typedef struct SymbTable{
    SymbPair *pairs;
    int numberOfItems;
} SymbTable;

SymbTable createTable(){
  SymbTable table;
  table.pairs =  (SymbPair*) calloc(1,sizeof(SymbPair));
  table.numberOfItems = 0;
  return table;
}

int checkForColon(char *word){
  if (word[strlen(word) - 1] == ':'){
    return  1;
  } else {
  return 0;
  }
}

void removeLastChar(char *word, char *buffer){
  int size = strlen(word);
  char blank[size - 1];
  for (int i = 0; i < size - 1; i++){
    blank[i] = word[i];
  }
  blank[size - 1] = '\0';
  strcpy(buffer,blank);
}

void symbPairSet(char *word, int address, SymbPair *pair){
  pair -> memoryAddress = address;
  pair -> symbol = word;
}

void addToSymbTable(SymbPair sp, SymbTable *array){
  int currentTotal = array->numberOfItems;
  array -> pairs = (SymbPair*) realloc(array->pairs,currentTotal+2);
  array->pairs[currentTotal]=sp;
  array -> numberOfItems = currentTotal + 1;
}

void firstPass(SymbTable *table, char **instructions){
  int totalLabels = 0;
  int i = 0;
  while (instructions[i] != NULL){
    if (checkForColon(instructions[i])){
      char buffer[strlen(instructions[i]) - 1];
      removeLastChar(instructions[i],buffer);
      SymbPair new;
      symbPairSet(buffer,(i*4) - totalLabels,&new);
      addToSymbTable(new,table);
      totalLabels++;

  }
    i++;
}

}

int main(){
SymbTable table = createTable();
firstPass(&table,instructionArray);
return EXIT_SUCCESS;
}

First pass takes in an array of strings and looks for strings that end in a colon and then removes the colon and adds the edited string into an array of symbol pairs which is held in a struct call symb table that holds the array and its size. With my current input there should be one item in the array with symbol loop and address 8. My issue is that within the firstPass function the string has the correct value but once it is passed into the value in main it changes completely. The value for the symbol (or the string) changes from inside the firstPass function to when it is being assigned in the main but it should be the same. Any help?

Here is a link to an image of the debugger after the SymbPair is first set

Here is what happens only a few steps afer

Body:
If you have this:

char blank[size - 1];

then this

blank[size - 1] = '\0';

is writing outside your array as it only has elements 0 to size - 2

if you write outside your variables you're changing other data, which seems consistent with your problem.


问:
Problems with reading and writing to text files in python
I am trying to take an input and write the input to a text file to keep it stored. However, I can't seem to get the user input written over to the text file. Here is my code:

```<code>SaveUsername = open(r"C:\Users\Ty\Desktop\Login_sys\SaveUsername.txt","w+")
SavePassword = open(r"C:\Users\Ty\Desktop\Login_sys\SavePassword.txt","w+")
NewUsername = input("Please enter a username: ")
NewPassword = input("Please enter a password: ")
SaveUsername.write(NewUsername)
print (SaveUsername.readline())
SavePassword.write(NewPassword)
print (SavePassword.readline())
</code>```

I am printing the readline to see if the code gets written and it never does.  Please help, thanks.

答: Close a file & open for reading before reading it.</p>

Body:
I am trying to take an input and write the input to a text file to keep it stored. However, I can't seem to get the user input written over to the text file. Here is my code:

SaveUsername = open(r"C:\Users\Ty\Desktop\Login_sys\SaveUsername.txt","w+")
SavePassword = open(r"C:\Users\Ty\Desktop\Login_sys\SavePassword.txt","w+")
NewUsername = input("Please enter a username: ")
NewPassword = input("Please enter a password: ")
SaveUsername.write(NewUsername)
print (SaveUsername.readline())
SavePassword.write(NewPassword)
print (SavePassword.readline())

I am printing the readline to see if the code gets written and it never does.  Please help, thanks.


问:
Add ExtJS code assist to IntellijIDEA
how would I enable code-completion, docs-browsing in IntelliJIDEA 10 Ultimate?</p>

答: Refer to the blog post about working with JavaScript libraries. The same applies for IntelliJ IDEA product.</p>

Title: Add ExtJS code assist to IntellijIDEA


问:
How are BIOS interrupts deconflicted with reserved hardware interrupts?
I'm reading a section of kernel bootloader code (from Stanford's CS140 Pintos OS):

```<code># Configure serial port so we can report progress without connected VGA.
# See [IntrList] for details.
        sub %dx, %dx                    # Serial port 0.
        mov $0xe3, %al                  # 9600 bps, N-8-1.
                                        # AH is already 0 (Initialize Port).
        int $0x14                       # Destroys AX.
</code>```

The processor is executing these instructions in real address mode.  Presumably the interrupt is handled by find the 21st (index=0x14) entry of the Interrupt Vector Table and executing the handler there.  According to this source, the interrupt table is initialized by BIOS in real mode.  This Wikipedia page lists BIOS interrupts that are available, including the one used above.

My confusion comes from the fact that the interrupt exception numbers listed conflict substantially with the descriptions of Real Mode reserved interrupts in the Intel reference (page 20-6) (and also repeated in this Wikipedia page)

How are those interrupt numbers de-conflicted?

答:
I think the legend goes back to IBM didn't bother to read the intel architecture manual when they made the PC.  Intel, from the first 8086, reserved the first 32 vectors for hardware use; IBM spec'd the PC BIOS ignoring this, and started services at 16 (0x10 -- video services); with one weird one at vector 5 for printing the current page of the video screen.   Vector 5 is used by the bounds check instruction.

Interrupt 0x10 lives on as a "coprocessor error"; a remnant of when the floating point processor was an optional auxiliary chip.

Interrupt 0x14, which concerns you, was defined by the bios for serial port handling; and by the CPU as a virtualization exception.

When you are in real mode, there is no virtualization; thus there is no conflict.  If you are in a virtual execution mode, and execute an int $0x14, the cpu just follows the idt; since the real virtual exception is caused by an access violation in the virtual machine, and causes an exit to the virtual machine monitor.  [ exit is the term used by hypervisor people for the conditions that cause the virtual machine to stop executing ].

So, there is no ambiguity, just a somewhat idiotic adherence to a badly constructed interface.

Body:
I'm reading a section of kernel bootloader code (from Stanford's CS140 Pintos OS):

# Configure serial port so we can report progress without connected VGA.
# See [IntrList] for details.
        sub %dx, %dx                    # Serial port 0.
        mov $0xe3, %al                  # 9600 bps, N-8-1.
                                        # AH is already 0 (Initialize Port).
        int $0x14                       # Destroys AX.

The processor is executing these instructions in real address mode.  Presumably the interrupt is handled by find the 21st (index=0x14) entry of the Interrupt Vector Table and executing the handler there.  According to this source, the interrupt table is initialized by BIOS in real mode.  This Wikipedia page lists BIOS interrupts that are available, including the one used above.

My confusion comes from the fact that the interrupt exception numbers listed conflict substantially with the descriptions of Real Mode reserved interrupts in the Intel reference (page 20-6) (and also repeated in this Wikipedia page)

How are those interrupt numbers de-conflicted?


问:
Filter an html table into another table by a value and removing columns with javascript
Hi I have two html tables id="source" and id="destination"

the source table has 7 columns and the destination table has 5 columns.

I need to filter the data by col2(value 150) into the destination table, but only display columns 1, 3, 4, 5 and 6. In another words ignore col2 and col7 as the image shows.

I've seen some examples of that, but they are all in jquery and I would like to do this with javascript as I'm not familiar with jquery.
I was using two functions and still not getting the results I need.

```<code>function copytable() {
var source = document.getElementById('source');
var destination = document.getElementById('destination');
var copy = source.cloneNode(true);
copy.setAttribute('id', 'destination');
destination.parentNode.replaceChild(copy, destination);
filterTable();
}

function filterTable() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("destination");
 tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
if (td) {
  if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
    tr[i].style.display = "";
  } else {
    tr[i].style.display = "none";
  }
}
}
}
</code>```

答:
There is step by step, all explanations are described in javascript code :

function filterValue() {
 var vl = document.getElementById('txtValue').value; //get value for filtering
 var stbl = document.getElementById('source');  //get source table
 var dtbl = document.getElementById('destionation'); //get destination table
 for(var i=0;i<stbl.rows.length;i++) {  //loop through source table
   var row=stbl.rows[i]; //get row (one by one) from source table
   if(row.cells[1].innerHTML==vl) {  //if entered value is equal with value into col2 of source table
    var newrow=dtbl.insertRow();  //create new row in destination table
    for(var x=0;x<row.cells.length;x++) { //loop through all cells
      if(x!=1 && x!=6) {  //take, "copy", all cells expect col2 and col7 cells
        var cell=newrow.insertCell(); //add cell in new created row
        cell.innerHTML=row.cells[x].innerHTML; //"copy" value from source cell into destination cell
      }
    }
  }
 }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#source, #destionation {margin-top:15px; border:solid 1px #c0c0c0;}
#source tr:first-child, #destionation tr:first-child {background-color:#B6D7A8; border-bottom:solid 1px #c0c0c0;}</code>```

Filter by value from col2 :
<input type="text" id="txtValue" value="" />
<input type="button" value="Filter" onclick="filterValue();" />

  col1
  col2
  col3
  col4
  col5
  col6
  col7

45	150	john	3.00	15.00	95	45:00:00

46	150	Anyone	3.00	15.00	95	37:00:00

49	220	Not included	3.00	15.00	95	15:22:00

48	150	And so on	3.00	15.00	95	35:50:00

  col1
  col3
  col4
  col5
  col6

```

Body:
Hi I have two html tables id="source" and id="destination"

the source table has 7 columns and the destination table has 5 columns.

I need to filter the data by col2(value 150) into the destination table, but only display columns 1, 3, 4, 5 and 6. In another words ignore col2 and col7 as the image shows.

I've seen some examples of that, but they are all in jquery and I would like to do this with javascript as I'm not familiar with jquery.
I was using two functions and still not getting the results I need.

function copytable() {
var source = document.getElementById('source');
var destination = document.getElementById('destination');
var copy = source.cloneNode(true);
copy.setAttribute('id', 'destination');
destination.parentNode.replaceChild(copy, destination);
filterTable();
}

function filterTable() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("destination");
 tr = table.getElementsByTagName("tr");
for (i = 0; i
 -1) {
    tr[i].style.display = "";
  } else {
    tr[i].style.display = "none";
  }
}
}
}

Body:
There is step by step, all explanations are described in javascript code :

function filterValue() {
 var vl = document.getElementById('txtValue').value; //get value for filtering
 var stbl = document.getElementById('source');  //get source table
 var dtbl = document.getElementById('destionation'); //get destination table
 for(var i=0;i<stbl.rows.length;i++) {  //loop through source table
   var row=stbl.rows[i]; //get row (one by one) from source table
   if(row.cells[1].innerHTML==vl) {  //if entered value is equal with value into col2 of source table
    var newrow=dtbl.insertRow();  //create new row in destination table
    for(var x=0;x<row.cells.length;x++) { //loop through all cells
      if(x!=1 && x!=6) {  //take, "copy", all cells expect col2 and col7 cells
        var cell=newrow.insertCell(); //add cell in new created row
        cell.innerHTML=row.cells[x].innerHTML; //"copy" value from source cell into destination cell
      }
    }
  }
 }
}

#source, #destionation {margin-top:15px; border:solid 1px #c0c0c0;}
#source tr:first-child, #destionation tr:first-child {background-color:#B6D7A8; border-bottom:solid 1px #c0c0c0;}

Filter by value from <b>col2</b> :
<input type="text" id="txtValue" value="" />
<input type="button" value="Filter" onclick="filterValue();" /><br>
  <table id="source" cellpadding="5" cellspacing="0">
 <tr>
  <td>col1</td>
  <td>col2</td>
  <td>col3</td>
  <td>col4</td>
  <td>col5</td>
  <td>col6</td>
  <td>col7</td>
 </tr>
 <tr><td>45</td><td>150</td><td>john</td><td>3.00</td><td>15.00</td><td>95</td><td>45:00:00</td></tr>
 <tr><td>46</td><td>150</td><td>Anyone</td><td>3.00</td><td>15.00</td><td>95</td><td>37:00:00</td></tr>
 <tr><td>49</td><td>220</td><td>Not included</td><td>3.00</td><td>15.00</td><td>95</td><td>15:22:00</td></tr>
 <tr><td>48</td><td>150</td><td>And so on</td><td>3.00</td><td>15.00</td><td>95</td><td>35:50:00</td></tr>
 </tr>
  </table>
  <table id="destionation" cellpadding="5" cellspacing="0">
 <tr>
  <td>col1</td>
  <td>col3</td>
  <td>col4</td>
  <td>col5</td>
  <td>col6</td>
 </tr>
  </table>


问:
vue js reusing component twice in same page
i  have a components  with axios call. i declare two of then with a props that give the uri to axios call

```<code>export default {
name: "CardData",

props :['uri','suffixe' ,'label'],

data : function (){
    return  {

        lab : this.label,
        suff: this.suffixe,
        data :0,
    }
},

methods :{
    init(){

        self = this;
        this.$http.get(this.$ApiUri+this.uri)

            .then(function (response) {
                self.loading = true;
                // handle success
                if (response.data){
                    if (response.data.nb){
                      console.log('we have nb :' + response.data.nb );
                      self.data = response.data.nb;
                    }

                    self.loading = false;
                }
            })
            .catch(function (error) {console.log(error);});
    },
},

mounted(){

     this.init();
},
</code>```

i have a container that call this components twice

```<code> <CardData uri="getNbNews" suffixe=" "  label="News" :key="100" ></CardData>
 <CardData uri="getNbSources" suffixe=" "  label="Sources" :key="101"></CardData>
</code>```

i can see the result on console.log  to response.data.nb
but only one is updated on front ... other contain 0
i can't figure it out

答:
ok ..  i missed this noob thing

```<code>self = this
</code>```

to

```<code>const self = this
</code>```

coupled to  @Cristiano Soleti :key param anwser solve the problem. thanks :).

Body:
i  have a components  with axios call. i declare two of then with a props that give the uri to axios call

export default {
name: "CardData",

props :['uri','suffixe' ,'label'],

data : function (){
    return  {

        lab : this.label,
        suff: this.suffixe,
        data :0,
    }
},

methods :{
    init(){

        self = this;
        this.$http.get(this.$ApiUri+this.uri)

            .then(function (response) {
                self.loading = true;
                // handle success
                if (response.data){
                    if (response.data.nb){
                      console.log('we have nb :' + response.data.nb );
                      self.data = response.data.nb;
                    }

                    self.loading = false;
                }
            })
            .catch(function (error) {console.log(error);});
    },
},

mounted(){

     this.init();
},

i have a container that call this components twice

 <CardData uri="getNbNews" suffixe=" "  label="News" :key="100" ></CardData>
 <CardData uri="getNbSources" suffixe=" "  label="Sources" :key="101"></CardData>

i can see the result on console.log  to response.data.nb
but only one is updated on front ... other contain 0
i can't figure it out

Body:
ok ..  i missed this noob thing

self = this

to

const self = this

coupled to  @Cristiano Soleti :key param anwser solve the problem. thanks :).


问:
Submitting form a bootstrap form, innerHTML, Alert
I am trying to submit a form which is in bootstrap. Once submission is done (on-click function) I want an alert message which is working fine. But I am unable to go to home page after that.
Following file opens after that.
file:///action_page.php?FName=&LName=&email=&pwd=

I am okay to display massage using innerHTML. After that also page is switching to same php file.

```<code><script>
function myFunction() {
document.getElementById("submission").innerHTML = alert("successfully submitted");
  window.location.href = ".....";
    }
}
</script>

<body>
 <button id="submit" onclick="myFunction()"class="text-light"
  type="submit">Submit</button>
</body>
</code>```

答:
Since you want to make an alert, instead of using:

```<code>document.getElementById("submission").innerHTML = alert("successfully submitted");
</code>```

just use alert('successfully submitted');. Alerts aren't shown inside of an HTML, they show on top of your page.

This fixes your problem:

function func() {
  alert("success!");
  window.location = "https://google.com";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="func()">Click me</button></code>```

If you're using this button in your form, you will have to override action attribute of the form by doing this. Also, if you're using this button to submit a form, use <input type="submit"> instead.

To override action of your form, use formaction

W3schools quote:

The input formaction attribute specifies the URL of the file that will
  process the input when the form is submitted.

Note: This attribute overrides the action attribute of the
  element.

You can combine this with alert so you don't need a separate function:

```<code><input type="submit" onclick="alert('success!')" formaction="home.html" value="Click me">

<!-- if you really want, you can also use a button -->

<button type="submit" onclick="alert('success!')" formaction="home.html">Click me</button>
</code>```

Formaction reference

Body:
I am trying to submit a form which is in bootstrap. Once submission is done (on-click function) I want an alert message which is working fine. But I am unable to go to home page after that.
Following file opens after that.
file:///action_page.php?FName=&LName=&email=&pwd=

I am okay to display massage using innerHTML. After that also page is switching to same php file.

 <button id="submit" onclick="myFunction()"class="text-light"
  type="submit">Submit</button>

Body:
Since you want to make an alert, instead of using:

document.getElementById("submission").innerHTML = alert("successfully submitted");

just use alert('successfully submitted');. Alerts aren't shown inside of an HTML, they show on top of your page.

This fixes your problem:

function func() {
  alert("success!");
  window.location = "https://google.com";
}

<button onclick="func()">Click me</button>

If you're using this button in your form, you will have to override action attribute of the form by doing this. Also, if you're using this button to submit a form, use <input type="submit"> instead.

To override action of your form, use formaction

W3schools quote:

The input formaction attribute specifies the URL of the file that will
  process the input when the form is submitted.

Note: This attribute overrides the action attribute of the
  element.

You can combine this with alert so you don't need a separate function:

<input type="submit" onclick="alert('success!')" formaction="home.html" value="Click me">

<!-- if you really want, you can also use a button -->

<button type="submit" onclick="alert('success!')" formaction="home.html">Click me</button>

Formaction reference


问:
AgoraKit cannot send `userinfo` to remote users
I am integrating Agora into my iOS Swift 5 app, and the basic use case reveal inexplicable behavior. Say Alice calls Bob, when Alice joins channel with userinfo specified:

```<code>        agoraKit.joinChannel(
            byToken: nil
          , channelId: "chan-1234"
          , info: "alice-userid"
          , uid: 0
        ) { [weak self] (sid, uid, elapsed) in
            print("\n Join channel ...: for sid: \(sid), uid: \(uid), dt: \(elapsed)")
        }
</code>```

the info: "alice-userid" data cannot be accessed by Bob in:

```<code>    func rtcEngine(_ engine: AgoraRtcEngineKit, firstRemoteVideoDecodedOfUid uid:UInt, size:CGSize, elapsed:Int) {

        let userInfo = agoraKit.getUserInfo(byUid: uid, withError: nil)
        print("added user: \(uid), with userinfo: \(userInfo)") // get uid, nil

    }
</code>```

On Bob's side, userInfo is nil. So I tried joining with user account,

```<code>         agoraKit.registerLocalUserAccount("alice-userid", appId: AppID)
        agoraKit.joinChannel(
              byUserAccount: "alice-account-data"
            , token: nil
            , channelId: "chan-1234"
        ) { [weak self] (sid, uid, elapsed) in
            print("\n Join channel ...: for sid: \(sid), uid: \(uid), dt: \(elapsed)")
        }
</code>```

This fails outright. I am referencing the docs here:

Building a 1-to-many iOS video app with Agora

FAQ - Strings

In the second case the doc has typos, and the API is out of date.

答:
Let's suppose that you have already registered Alice and Bob with registerLocalUserAccount:appId: method. Both of them must join the channel with joinChannelByUserAccount:token:channelId:joinSuccess: method. Make sure that registerLocalUserAccount:appId: method is returning 0 which means that client was successfully registered.

Now as stated in Agora documentation about getUserInfoByUid:withError: method:

After a user joins the channel, the SDK gets the user ID and user account of the remote user, caches them in a mapping table object (AgoraUserInfo), and triggers the didUpdatedUserInfo callback on the local client. After receiving the didUpdatedUserInfo callback, you can call this method to get the user account of the user from the userInfo object by passing in the user ID.

This means that the proper timing for calling getUserInfoByUid:withError: is when rtcEngine:didUpdatedUserInfo:withUid: delegate method is called.

I'm guessing from your snippets that your class is already conforming to AgoraRtcEngineDelegate protocol. So all you have to do is to implement this delegate method and call getUserInfoByUid:withError: inside method body.

EXAMPLE:

Step 1:

Make your class conform to AgoraRtcEngineDelegate:

// Assign delegate when instantiating
lazy var agoraKit: AgoraRtcEngineKit = {
  AgoraRtcEngineKit.sharedEngine(withAppId: "YourAppID", delegate: self)
}()

// Assign delegate later
agoraKit.delegate = self
```

<pre class="lang-swift prettyprint-override"><code>// Conform to AgoraRtcEngineDelegate
extension MyClass: AgoraRtcEngineDelegate {
  //...
}
</code>```

Step 2:

Register user with registerLocalUserAccount:appId: method.

// User with 'bob' username will be registered
let registerResponse: Int32 = agoraKit.registerLocalUserAccount("bob", appId: "YourAppID")
if registerResponse == 0 {
    // Successfully registered
} else {
    // Failed to register
}
```

<p>Step 3: </p>

<p>Join channel after user registered successfully.</p>

<pre class="lang-swift prettyprint-override"><code>agoraKit.joinChannel(byUserAccount: "bob", token: nil, channelId: "room123") { (channel, uid, elapsed) in
    print("User joined channel \(channel) with \(uid). Elapsed time is \(elapsed)ms.")
}
</code>```

Step 4:

Implement rtcEngine:didUpdatedUserInfo:withUid: delegate method.

// This method will be triggered after Agora SDK
// caches user ID and user account of the remote user.
func rtcEngine(_ engine: AgoraRtcEngineKit, didUpdatedUserInfo userInfo: AgoraUserInfo, withUid uid: UInt) {
    var error: AgoraErrorCode = .noError
    let userInfoWithUid = agoraKit.getUserInfo(byUid: uid, withError: &error)
    if error == .noError {
        // Do something with AgoraUserInfo object
    }
}
```

Body:
I am integrating Agora into my iOS Swift 5 app, and the basic use case reveal inexplicable behavior. Say Alice calls Bob, when Alice joins channel with userinfo specified:

        agoraKit.joinChannel(
            byToken: nil
          , channelId: "chan-1234"
          , info: "alice-userid"
          , uid: 0
        ) { [weak self] (sid, uid, elapsed) in
            print("\n Join channel ...: for sid: \(sid), uid: \(uid), dt: \(elapsed)")
        }

the info: "alice-userid" data cannot be accessed by Bob in:

    func rtcEngine(_ engine: AgoraRtcEngineKit, firstRemoteVideoDecodedOfUid uid:UInt, size:CGSize, elapsed:Int) {

        let userInfo = agoraKit.getUserInfo(byUid: uid, withError: nil)
        print("added user: \(uid), with userinfo: \(userInfo)") // get uid, nil

    }

On Bob's side, userInfo is nil. So I tried joining with user account,

         agoraKit.registerLocalUserAccount("alice-userid", appId: AppID)
        agoraKit.joinChannel(
              byUserAccount: "alice-account-data"
            , token: nil
            , channelId: "chan-1234"
        ) { [weak self] (sid, uid, elapsed) in
            print("\n Join channel ...: for sid: \(sid), uid: \(uid), dt: \(elapsed)")
        }

This fails outright. I am referencing the docs here:

Building a 1-to-many iOS video app with Agora

FAQ - Strings

In the second case the doc has typos, and the API is out of date.

Body:
Let's suppose that you have already registered Alice and Bob with registerLocalUserAccount:appId: method. Both of them must join the channel with joinChannelByUserAccount:token:channelId:joinSuccess: method. Make sure that registerLocalUserAccount:appId: method is returning 0 which means that client was successfully registered.

Now as stated in Agora documentation about getUserInfoByUid:withError: method:

After a user joins the channel, the SDK gets the user ID and user account of the remote user, caches them in a mapping table object (AgoraUserInfo), and triggers the didUpdatedUserInfo callback on the local client. After receiving the didUpdatedUserInfo callback, you can call this method to get the user account of the user from the userInfo object by passing in the user ID.

This means that the proper timing for calling getUserInfoByUid:withError: is when rtcEngine:didUpdatedUserInfo:withUid: delegate method is called.

I'm guessing from your snippets that your class is already conforming to AgoraRtcEngineDelegate protocol. So all you have to do is to implement this delegate method and call getUserInfoByUid:withError: inside method body.

EXAMPLE:

Step 1:

Make your class conform to AgoraRtcEngineDelegate:

// Assign delegate when instantiating
lazy var agoraKit: AgoraRtcEngineKit = {
  AgoraRtcEngineKit.sharedEngine(withAppId: "YourAppID", delegate: self)
}()

// Assign delegate later
agoraKit.delegate = self

// Conform to AgoraRtcEngineDelegate
extension MyClass: AgoraRtcEngineDelegate {
  //...
}

Step 2:

Register user with registerLocalUserAccount:appId: method.

// User with 'bob' username will be registered
let registerResponse: Int32 = agoraKit.registerLocalUserAccount("bob", appId: "YourAppID")
if registerResponse == 0 {
    // Successfully registered
} else {
    // Failed to register
}

Step 3:

Join channel after user registered successfully.

agoraKit.joinChannel(byUserAccount: "bob", token: nil, channelId: "room123") { (channel, uid, elapsed) in
    print("User joined channel \(channel) with \(uid). Elapsed time is \(elapsed)ms.")
}

Step 4:

Implement rtcEngine:didUpdatedUserInfo:withUid: delegate method.

// This method will be triggered after Agora SDK
// caches user ID and user account of the remote user.
func rtcEngine(_ engine: AgoraRtcEngineKit, didUpdatedUserInfo userInfo: AgoraUserInfo, withUid uid: UInt) {
    var error: AgoraErrorCode = .noError
    let userInfoWithUid = agoraKit.getUserInfo(byUid: uid, withError: &error)
    if error == .noError {
        // Do something with AgoraUserInfo object
    }
}


问:
Stop Macro if MsgBox appears
I have a Macro that performs a few validations. I've simplified the code below for illustration.

If all the validations are successful, then I want it to run the "ActiveWorkbook.SaveAs" line.

If a MsgBox has to popup, then I don't want to run the "ActiveWorkbook.SaveAs" line

How could I tweak my code to make this possible? Thank you for helping me!

```<code>Sub blank()

'Validations
If Cells(10, 4).Value = "" Then
MsgBox "Please fill in Invoice Date"
End If

If Cells(11, 4).Value = "" Then
MsgBox "Please fill in Invoice Number"
End If

'Save As
ActiveWorkbook.SaveAs filename:="Lease Admin Processing Input Form"

End Sub
</code>```

答:
Just check if both the validations are true. If they both are true then run the Save As part, otherwise it will skip to save as :)</p>

```<code>Sub blank()

'Validations
If Cells(10, 4).Value = "" Then
MsgBox "Please fill in Invoice Date"
End If

If Cells(11, 4).Value = "" Then
MsgBox "Please fill in Invoice Number"
End If

If Cells(10, 4).Value = "" And Cells(11, 4).Value = "" Then
'Save As
ActiveWorkbook.SaveAs filename:="Lease Admin Processing Input Form"
End If
End Sub
</code>```

Title: Stop Macro if MsgBox appears

Body:
I have a Macro that performs a few validations. I've simplified the code below for illustration.

If all the validations are successful, then I want it to run the "ActiveWorkbook.SaveAs" line.

If a MsgBox has to popup, then I don't want to run the "ActiveWorkbook.SaveAs" line

How could I tweak my code to make this possible? Thank you for helping me!

Sub blank()

'Validations
If Cells(10, 4).Value = "" Then
MsgBox "Please fill in Invoice Date"
End If

If Cells(11, 4).Value = "" Then
MsgBox "Please fill in Invoice Number"
End If

'Save As
ActiveWorkbook.SaveAs filename:="Lease Admin Processing Input Form"

End Sub

Body:
Just check if both the validations are true. If they both are true then run the Save As part, otherwise it will skip to save as :)

Sub blank()

'Validations
If Cells(10, 4).Value = "" Then
MsgBox "Please fill in Invoice Date"
End If

If Cells(11, 4).Value = "" Then
MsgBox "Please fill in Invoice Number"
End If

If Cells(10, 4).Value = "" And Cells(11, 4).Value = "" Then
'Save As
ActiveWorkbook.SaveAs filename:="Lease Admin Processing Input Form"
End If
End Sub


问:
Login pop-up for Home page module links
I have to display a login-pop-up window when the user clicks on the links in a custom module. I have the pop-up using rokbox and am displaying it for other links. I am adding the links to the module from adminside and it the user is not logged in it should show the link for rokbox pop-up and if he is logged it should show the actual link. Please let me know where I need to make modifications. I think I can get all the module contents inside the default.php of mod_custom and can check the conditions. But then also , it will be applied for all the custom modules. Now how can I specify it is checking the condition for a particular module in Home page.

It will be helpful if someone can answer it ASAP.

答: I have done it using Extension called Jumi. This will allow us to insert/call custom PHP code. What I did is, I put the contents in a PHP file and called it in a article. So in the PHP file we can check whether the user is logged in and other things. Then I called this article in a module.Now it is working.</p>

Title: Login pop-up for Home page module links


问:
Mongoose 'static' methods vs. 'instance' methods
I believe this question is similar to this one but the terminology is different. From the Mongoose 4 documentation:

We may also define our own custom document instance methods too.

```<code>// define a schema
var animalSchema = new Schema({ name: String, type: String });

// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function (cb) {
  return this.model('Animal').find({ type: this.type }, cb);
}
</code>```

Now all of our animal instances have a findSimilarTypes method available to it.

And then:

Adding static methods to a Model is simple as well. Continuing with our animalSchema:

```<code>// assign a function to the "statics" object of our animalSchema
animalSchema.statics.findByName = function (name, cb) {
  return this.find({ name: new RegExp(name, 'i') }, cb);
}

var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function (err, animals) {
  console.log(animals);
});
</code>```

It seems with static methods each of the animal instances would have the findByName method available to it as well.  What are the statics and methods objects in a Schema? What is the difference and why would I use one over the other?

答:
Well to me it doesn't mean add anythings by adding Mongoose in front of 'static' or even in front 'instance' keyword.

What I believe meaning and purpose of static is same everywhere,  even it's also true for an alien language or some sort of driver which represents Model for building the block like another object-oriented programming. The same also goes for instance.

From Wikipedia:
A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of data and behavior. The data and behavior comprise an interface, which specifies how the object may be utilized by any of various consumers[1] of the object.

Data is represented as properties of the object and behaviors are represented as methods of the object. For example, a Window object could have methods such as open and close, while its state (whether it is opened or closed at any given point in time) would be a property.

Static methods are meant to be relevant to all the instances of a class rather than to any specific instance. They are similar to static variables in that sense. An example would be a static method to sum the values of all the variables of every instance of a class. For example, if there were a Product class it might have a static method to compute the average price of all products.

Math.max(double a, double b)

This static method has no owning object and does not run on an instance. It receives all information from its arguments.[7]

A static method can be invoked even if no instances of the class exist yet. Static methods are called "static" because they are resolved at compile time based on the class they are called on and not dynamically as in the case with instance methods, which are resolved polymorphically based on the runtime type of the object.

https://en.wikipedia.org/wiki/Method_(computer_programming)

Body:
I believe this question is similar to this one but the terminology is different. From the Mongoose 4 documentation:

We may also define our own custom document instance methods too.

// define a schema
var animalSchema = new Schema({ name: String, type: String });

// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function (cb) {
  return this.model('Animal').find({ type: this.type }, cb);
}

Now all of our animal instances have a findSimilarTypes method available to it.

And then:

Adding static methods to a Model is simple as well. Continuing with our animalSchema:

// assign a function to the "statics" object of our animalSchema
animalSchema.statics.findByName = function (name, cb) {
  return this.find({ name: new RegExp(name, 'i') }, cb);
}

var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function (err, animals) {
  console.log(animals);
});

It seems with static methods each of the animal instances would have the findByName method available to it as well.  What are the statics and methods objects in a Schema? What is the difference and why would I use one over the other?


问:
Running a python program from a C++ program?
I've been messing around with Selenium in python, and I really want to have an existing C++ program run my python code.

Basically, my python code just finds a website, and downloads the file which afterwards my C++ program wants to open the file and do a bunch of operations on it. If I had a myPythonCode.py file, and my other C++ files (header.h, main.cpp, otherFunctions.cpp...) how would I go about running the python code from my C++ program?

Also both of my programs are console programs, and I was hoping that a user would have an uninterrupted experience running the program (for example, if the user wants to download a file while running the C++ program the terminal doesn't have to close, or open a different window to start the python program). Any help in going about this would be greatly appreciated!

答: Check out the boost library which allows running python on C++ and using your C++ in python.  https://www.boost.org/doc/libs/1_49_0/libs/python/doc/</p>