问:
CollectionResult<T> in typescript
I`m trying to create a generic class for proxy service that gets a response from the server. When I stay to implement this class I get a problem, to call a method from generic class. How can I call static method fromJs(item) that declared in generic type?

```<code>export class CollectionResult<T> implements ICollectionResult<T> {
    items: Array<T>;

    constructor(data?: T) {
        if (data) {
            for (var property in data) {
                if (data.hasOwnProperty(property))
                    (<any>this)[property] = (<any>data)[property];
            }
        }
    }

    init(data?: any) {
        if (data) {
            Object.assign(this, data);
            this.items = [];
            for (let item of data.items) {
                this.items.push(T//NOTE: Error here//.fromJS(item));
            }
        }
    }

     fromJS(data: any): CollectionResult<T> {
        let result = new CollectionResult<T>();
        result.init(data);
        return result;
    }

    toJSON(data?: any) {
        data = typeof data === 'object' ? data : {};
        Object.assign(data, this);
        if (this.items && this.items.constructor === Array) {
            data["items"] = [];
            for (let item of this.items) {
                data["items"].push(item);
            }
        }
        return data;
    }
}

export interface ICollectionResult<T> {
    items: Array<T>;
}
</code>```

// Generic Class that is passing in CollectionResult

```<code>export class ProgramDto implements
IProgramDto {
    year: number;
    month: number;
    accounts: number;

    constructor(data?: ProgramDto) {
        if (data) {
            for (var property in data) {
                if (data.hasOwnProperty(property))
                    (<any>this)[property] = (<any>data)[property];
            }
        }
    }

    init(data?: any) {
        if (data) {
            Object.assign(this, data);
        }
    }

    static fromJS(data: any): ProgramDto {
        let result = new ProgramDto();
        result.init(data);
        return result;
    }

    toJSON(data?: any) {
        data = typeof data === 'object' ? data : {};
        Object.assign(data, this);

        return data;
    }
}

export interface IProgramDto {
    year: number;
    month: number;
    accounts: number;
}
</code>```

//Usage in proxy methods

```<code>Get(): Observable<CollectionResult<ProgramDto >> {
        let url = `${this.baseUrl}/Api/Controller/Method`;
        url = url.replace(/[?&]$/, "");
        let options = this.getOptions();
        return this.sendRequestWithResponse(url, options, CollectionResult<ProgramDto>.fromJS, new CollectionResult<ProgramDto>());
    }
</code>```

答:
You can't access members of a generic type parameter. Type parameters are erased during compilation, so you can't depend on them for anything else other than type checking.

You can pass in the class as a parameter and constrain that to have the fromJs method:

```<code>type CollectionResultDataClass<T> = {
    new(...a: any[]): T
    fromJs(o: any): T
}

export class CollectionResult<T> implements ICollectionResult<T> {
    items: Array<T>;

    constructor(private cls: CollectionResultDataClass<T>, data?: T) {
        // ...
    }

    init(data?: any) {
        if (data) {
            Object.assign(this, data);
            this.items = [];
            for (let item of data.items) {
                this.items.push(this.cls.fromJs(item));
            }
        }
    }

    fromJS(data: any): CollectionResult<T> {
        let result = new CollectionResult<T>(this.cls);
        result.init(data);
        return result;
    }

    toJSON(data?: any) {
        //..
    }
}

//Usage
class MyDataClass {
    static fromJs(o: any) {
        return Object.assign(new MyDataClass(), o);
    }
}

new CollectionResult(MyDataClass, new MyDataClass());
</code>```

Title: CollectionResult<T> in typescript

Body:
I`m trying to create a generic class for proxy service that gets a response from the server. When I stay to implement this class I get a problem, to call a method from generic class. How can I call static method fromJs(item) that declared in generic type?

export class CollectionResult<T> implements ICollectionResult<T> {
    items: Array<T>;

    constructor(data?: T) {
        if (data) {
            for (var property in data) {
                if (data.hasOwnProperty(property))
                    (<any>this)[property] = (<any>data)[property];
            }
        }
    }

    init(data?: any) {
        if (data) {
            Object.assign(this, data);
            this.items = [];
            for (let item of data.items) {
                this.items.push(T//NOTE: Error here//.fromJS(item));
            }
        }
    }

     fromJS(data: any): CollectionResult<T> {
        let result = new CollectionResult<T>();
        result.init(data);
        return result;
    }

    toJSON(data?: any) {
        data = typeof data === 'object' ? data : {};
        Object.assign(data, this);
        if (this.items && this.items.constructor === Array) {
            data["items"] = [];
            for (let item of this.items) {
                data["items"].push(item);
            }
        }
        return data;
    }
}

export interface ICollectionResult<T> {
    items: Array<T>;
}

// Generic Class that is passing in CollectionResult

export class ProgramDto implements
IProgramDto {
    year: number;
    month: number;
    accounts: number;

    constructor(data?: ProgramDto) {
        if (data) {
            for (var property in data) {
                if (data.hasOwnProperty(property))
                    (<any>this)[property] = (<any>data)[property];
            }
        }
    }

    init(data?: any) {
        if (data) {
            Object.assign(this, data);
        }
    }

    static fromJS(data: any): ProgramDto {
        let result = new ProgramDto();
        result.init(data);
        return result;
    }

    toJSON(data?: any) {
        data = typeof data === 'object' ? data : {};
        Object.assign(data, this);

        return data;
    }
}

export interface IProgramDto {
    year: number;
    month: number;
    accounts: number;
}

//Usage in proxy methods

Get(): Observable<CollectionResult<ProgramDto >> {
        let url = `${this.baseUrl}/Api/Controller/Method`;
        url = url.replace(/[?&]$/, "");
        let options = this.getOptions();
        return this.sendRequestWithResponse(url, options, CollectionResult<ProgramDto>.fromJS, new CollectionResult<ProgramDto>());
    }

Body:
You can't access members of a generic type parameter. Type parameters are erased during compilation, so you can't depend on them for anything else other than type checking.

You can pass in the class as a parameter and constrain that to have the fromJs method:

type CollectionResultDataClass<T> = {
    new(...a: any[]): T
    fromJs(o: any): T
}

export class CollectionResult<T> implements ICollectionResult<T> {
    items: Array<T>;

    constructor(private cls: CollectionResultDataClass<T>, data?: T) {
        // ...
    }

    init(data?: any) {
        if (data) {
            Object.assign(this, data);
            this.items = [];
            for (let item of data.items) {
                this.items.push(this.cls.fromJs(item));
            }
        }
    }

    fromJS(data: any): CollectionResult<T> {
        let result = new CollectionResult<T>(this.cls);
        result.init(data);
        return result;
    }

    toJSON(data?: any) {
        //..
    }
}

//Usage
class MyDataClass {
    static fromJs(o: any) {
        return Object.assign(new MyDataClass(), o);
    }
}

new CollectionResult(MyDataClass, new MyDataClass());


来源: stackexchange

问:
Strange type of union
Sorry for the strange title, I don't have much experience with SQL. I'm working with 2 tables : table COMPONENTS, that lists some components, and table OPERATIONS that is a list of operations applied to components.

Table COMPONENTS looks like that :

```<code>+-------+--------------+-------------------+-------+
| Level | Main Article | Secondary Article | Brand |
+-------+--------------+-------------------+-------+
|     1 | Article A    | Article 1         | Foo   |
|     1 | Article B    | Article 1         | Bar   |
+-------+--------------+-------------------+-------+
</code>```

It has a lot more columns, but this is the idea. Basically it lists all articles in stock and what articles they are made of.

The OPERATIONStable contains all the operations a secondary article has to undergo to be incorporated into a main one :

```<code>+--------------------+-----------+------+
| Secondary Article  | Operation | Cost |
+--------------------+-----------+------+
| Article 1          | Cutting   | X    |
| Article 1          | Knitting  | Y    |
| Article 1          | Bleaching | Z    |
+--------------------+-----------+------+
</code>```

What would be the best way to combine those two tables into one that would have this structure ?

```<code>+-------+--------------+-------------------+-----------+------+-------+
| Level | Main Article | Secondary Article | Operation | Cost | Brand |
+-------+--------------+-------------------+-----------+------+-------+
|     1 | Article A    | Article 1         |           |      | Foo   |
|     1 | Article A    | Article 1         | Cutting   | X    | Foo   |
|     1 | Article A    | Article 1         | Knitting  | Y    | Foo   |
|     1 | Article A    | Article 1         | Bleaching | Z    | Foo   |
|     1 | Article B    | Article 1         |           |      | Bar   |
|     1 | Article B    | Article 1         | Cutting   | X    | Bar   |
|     1 | Article B    | Article 1         | Knitting  | Y    | Bar   |
|     1 | Article B    | Article 1         | Bleaching | Z    | Bar   |
+-------+--------------+-------------------+-----------+------+-------+
</code>```

I tried to simplify the problem as much as possible. How should I proceed to manage this ? I tried with joins and unions, but it doesn't work.

It seems to me that this would be super easy to do with a programming language that allows loops, but I'm completely lost here.

答:
Rather than using a UNION I would do something like this:

```<code>SELECT C.Level,
       C.MainArticle,
       C.SecondaryArticle,
       O.Operation,
       O.Cost,
       C.Brand
FROM COMPONENTS C
     CROSS APPLY (VALUES(0),(1)) V(Header)
     LEFT JOIN OPERATIONS O ON V.Header = 1
                           AND C.SecondaryArticle = O.SecondaryArticle
ORDER BY C.MainArticle,
         V.Header,
         O.Cost;
</code>```

db<>fiddle

ContentLicense: CC BY-SA 4.0

Title: Strange type of union

Body:
Sorry for the strange title, I don't have much experience with SQL. I'm working with 2 tables : table COMPONENTS, that lists some components, and table OPERATIONS that is a list of operations applied to components.

Table COMPONENTS looks like that :

+-------+--------------+-------------------+-------+
| Level | Main Article | Secondary Article | Brand |
+-------+--------------+-------------------+-------+
|     1 | Article A    | Article 1         | Foo   |
|     1 | Article B    | Article 1         | Bar   |
+-------+--------------+-------------------+-------+

It has a lot more columns, but this is the idea. Basically it lists all articles in stock and what articles they are made of.

The OPERATIONStable contains all the operations a secondary article has to undergo to be incorporated into a main one :

+--------------------+-----------+------+
| Secondary Article  | Operation | Cost |
+--------------------+-----------+------+
| Article 1          | Cutting   | X    |
| Article 1          | Knitting  | Y    |
| Article 1          | Bleaching | Z    |
+--------------------+-----------+------+

What would be the best way to combine those two tables into one that would have this structure ?

+-------+--------------+-------------------+-----------+------+-------+
| Level | Main Article | Secondary Article | Operation | Cost | Brand |
+-------+--------------+-------------------+-----------+------+-------+
|     1 | Article A    | Article 1         |           |      | Foo   |
|     1 | Article A    | Article 1         | Cutting   | X    | Foo   |
|     1 | Article A    | Article 1         | Knitting  | Y    | Foo   |
|     1 | Article A    | Article 1         | Bleaching | Z    | Foo   |
|     1 | Article B    | Article 1         |           |      | Bar   |
|     1 | Article B    | Article 1         | Cutting   | X    | Bar   |
|     1 | Article B    | Article 1         | Knitting  | Y    | Bar   |
|     1 | Article B    | Article 1         | Bleaching | Z    | Bar   |
+-------+--------------+-------------------+-----------+------+-------+

I tried to simplify the problem as much as possible. How should I proceed to manage this ? I tried with joins and unions, but it doesn't work.

It seems to me that this would be super easy to do with a programming language that allows loops, but I'm completely lost here.

Body:
Rather than using a UNION I would do something like this:

SELECT C.Level,
       C.MainArticle,
       C.SecondaryArticle,
       O.Operation,
       O.Cost,
       C.Brand
FROM COMPONENTS C
     CROSS APPLY (VALUES(0),(1)) V(Header)
     LEFT JOIN OPERATIONS O ON V.Header = 1
                           AND C.SecondaryArticle = O.SecondaryArticle
ORDER BY C.MainArticle,
         V.Header,
         O.Cost;

db<>fiddle


问:
Algorithm to find next greater permutation of a given string
I want an efficient algorithm to find the next greater permutation of the given string.</p>

答:
A great solution that works is described here: https://www.nayuki.io/page/next-lexicographical-permutation-algorithm.
and if you are looking for

source code:

```<code>/**
     * method to find the next lexicographical greater string
     *
     * @param w
     * @return a new string
     */
    static String biggerIsGreater(String w) {
        char charArray[] = w.toCharArray();
        int n = charArray.length;
        int endIndex = 0;

        // step-1) Start from the right most character and find the first character
        // that is smaller than previous character.
        for (endIndex = n - 1; endIndex > 0; endIndex--) {
            if (charArray[endIndex] > charArray[endIndex - 1]) {
                break;
            }
        }

        // If no such char found, then all characters are in descending order
        // means there cannot be a greater string with same set of characters
        if (endIndex == 0) {
            return "no answer";
        } else {
            int firstSmallChar = charArray[endIndex - 1], nextSmallChar = endIndex;

            // step-2) Find the smallest character on right side of (endIndex - 1)'th
            // character that is greater than charArray[endIndex - 1]
            for (int startIndex = endIndex + 1; startIndex < n; startIndex++) {
                if (charArray[startIndex] > firstSmallChar && charArray[startIndex] < charArray[nextSmallChar]) {
                    nextSmallChar = startIndex;
                }
            }

            // step-3) Swap the above found next smallest character with charArray[endIndex - 1]
            swap(charArray, endIndex - 1, nextSmallChar);

            // step-4) Sort the charArray after (endIndex - 1)in ascending order
            Arrays.sort(charArray, endIndex , n);

        }
        return new String(charArray);
    }

    /**
     * method to swap ith character with jth character inside charArray
     *
     * @param charArray
     * @param i
     * @param j
     */
    static void swap(char charArray[], int i, int j) {
        char temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;
    }
</code>```

If you are looking for video explanation for the same, you can visit here.

ContentLicense: CC BY-SA 2.5

Body:
A great solution that works is described here: https://www.nayuki.io/page/next-lexicographical-permutation-algorithm.
and if you are looking for

source code:

/**
     * method to find the next lexicographical greater string
     *
     * @param w
     * @return a new string
     */
    static String biggerIsGreater(String w) {
        char charArray[] = w.toCharArray();
        int n = charArray.length;
        int endIndex = 0;

        // step-1) Start from the right most character and find the first character
        // that is smaller than previous character.
        for (endIndex = n - 1; endIndex > 0; endIndex--) {
            if (charArray[endIndex] > charArray[endIndex - 1]) {
                break;
            }
        }

        // If no such char found, then all characters are in descending order
        // means there cannot be a greater string with same set of characters
        if (endIndex == 0) {
            return "no answer";
        } else {
            int firstSmallChar = charArray[endIndex - 1], nextSmallChar = endIndex;

            // step-2) Find the smallest character on right side of (endIndex - 1)'th
            // character that is greater than charArray[endIndex - 1]
            for (int startIndex = endIndex + 1; startIndex < n; startIndex++) {
                if (charArray[startIndex] > firstSmallChar && charArray[startIndex] < charArray[nextSmallChar]) {
                    nextSmallChar = startIndex;
                }
            }

            // step-3) Swap the above found next smallest character with charArray[endIndex - 1]
            swap(charArray, endIndex - 1, nextSmallChar);

            // step-4) Sort the charArray after (endIndex - 1)in ascending order
            Arrays.sort(charArray, endIndex , n);

        }
        return new String(charArray);
    }

    /**
     * method to swap ith character with jth character inside charArray
     *
     * @param charArray
     * @param i
     * @param j
     */
    static void swap(char charArray[], int i, int j) {
        char temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;
    }

If you are looking for video explanation for the same, you can visit here.


问:
Xena user membership returning all rows
I am working with the Xena api

I am having issues getting data back from the api even though i have a valid access token.

```<code>https://my.xena.biz/Api/User/XenaUserMembership
</code>```

returns

```<code>{
    "Message": "An error has occurred.",
    "ExceptionMessage": "Object reference not set to an instance of an object.",
    "ExceptionType": "System.NullReferenceException",
    "StackTrace": "   at Xena.Web.Api.ApiUserController.GetXenaUserMembershipList(ListOptions listOptions, String queryString) in C:\\Development\\Xena\\Xena\\src\\Xena.Web\\Api\\ApiUserController.cs:line 249\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_1.<GetExecutor>b__3(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()"
}
</code>```

pagesize required

Then I found that page size was a required field.

```<code>https://my.xena.biz/Api/User/XenaUserMembership?PageSize=1
</code>```

Results

```<code>  "Count": 72,
    "Entities": [
        {
            "Id": 1,
            "MembershipId": 8326,
            "FiscalSetupId": 7,
            "UserId": 52522,
            "ResourceId": 832544,
            "ResourceName": "XXX XXXX",
            "ResourceTheme": "theme-default",
            "CurrencyAbbreviation": "DKK",
            "FiscalSetupName": "TestCompany",
            "VCardId": 54544,
            "XenaSubscriptionId": 832140,
            "SproomKey": null,
            "PictureLastVersionId": 5427538,
            "PictureUrl": "/Blob/Public/VCard/54544/Thumbnail/5427538",
            "SecurityGroups": "Admin"
        }
    ]
}
</code>```

I am no logger getting the error but i want to get the full results back. It says that count = 72 how do i get a full list of all 72 objects?

答:
After digging around in the documentation i finally found.  ForceNoPaging=true which when added to the end of the request it returns the full response.</p>

```<code>https://my.xena.biz/Api/User/XenaUserMembership?ForceNoPaging=true
</code>```

Title: Xena user membership returning all rows

Body:
I am working with the Xena api

I am having issues getting data back from the api even though i have a valid access token.

https://my.xena.biz/Api/User/XenaUserMembership

returns

{
    "Message": "An error has occurred.",
    "ExceptionMessage": "Object reference not set to an instance of an object.",
    "ExceptionType": "System.NullReferenceException",
    "StackTrace": "   at Xena.Web.Api.ApiUserController.GetXenaUserMembershipList(ListOptions listOptions, String queryString) in C:\\Development\\Xena\\Xena\\src\\Xena.Web\\Api\\ApiUserController.cs:line 249\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_1.<GetExecutor>b__3(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()"
}

pagesize required

Then I found that page size was a required field.

https://my.xena.biz/Api/User/XenaUserMembership?PageSize=1

Results

  "Count": 72,
    "Entities": [
        {
            "Id": 1,
            "MembershipId": 8326,
            "FiscalSetupId": 7,
            "UserId": 52522,
            "ResourceId": 832544,
            "ResourceName": "XXX XXXX",
            "ResourceTheme": "theme-default",
            "CurrencyAbbreviation": "DKK",
            "FiscalSetupName": "TestCompany",
            "VCardId": 54544,
            "XenaSubscriptionId": 832140,
            "SproomKey": null,
            "PictureLastVersionId": 5427538,
            "PictureUrl": "/Blob/Public/VCard/54544/Thumbnail/5427538",
            "SecurityGroups": "Admin"
        }
    ]
}

I am no logger getting the error but i want to get the full results back. It says that count = 72 how do i get a full list of all 72 objects?

Body:
After digging around in the documentation i finally found.  ForceNoPaging=true which when added to the end of the request it returns the full response.

https://my.xena.biz/Api/User/XenaUserMembership?ForceNoPaging=true


答:
Your join/union intuition was right, you can do something like this:

```<code>select
    Level,
    `Main Article`,
    `Secondary Article`,
    '' as Operation,
    '' as Cost,
    Brand
from
    COMPONENTS
union select
    COMPONENTS.Level,
    COMPONENTS.`Main Article`,
    COMPONENTS.`Secondary Article`,
    OPERATIONS.Operation,
    OPERATIONS.Cost,
    COMPONENTS.Brand
from
    COMPONENTS
    left join OPERATIONS on COMPONENTS.`Secondary Article` = OPERATIONS.`Secondary Article`
</code>```

Title: Strange type of union

Body:
Your join/union intuition was right, you can do something like this:

select
    Level,
    `Main Article`,
    `Secondary Article`,
    '' as Operation,
    '' as Cost,
    Brand
from
    COMPONENTS
union select
    COMPONENTS.Level,
    COMPONENTS.`Main Article`,
    COMPONENTS.`Secondary Article`,
    OPERATIONS.Operation,
    OPERATIONS.Cost,
    COMPONENTS.Brand
from
    COMPONENTS
    left join OPERATIONS on COMPONENTS.`Secondary Article` = OPERATIONS.`Secondary Article`


问:
Re-direct all traffic to error page using IIS Manager 2008?
Our database has just crashed so need to take down IIS - is there anyway to just have a catch all, so whatever page a user visits will display an error message, as opposed to just stopping the service and having the 'Unable to connect' error.

Thanks

答:
If you stick a file called app_offline.htm in the root of your web application, IIS will shut-down the application, unload the application domain from the server, and stop processing any new incoming requests for that application.

It will then simply return the contents of the app_offline.htm file to anyone making requests to your application giving you the chance to send back an informative message.

ContentLicense: CC BY-SA 3.0


问:
Type-safe states with exhaustive pattern matching in Akka Typed
I started working with Akka Typed to get exhaustive pattern matching on my behaviors, which has been great for the external facing contract of each actor. However, if the actor is a state machine, chances are the different states have state specific commands.

I can hide state-specific commands as private members of the overall command like this:

```<code>sealed trait Command
final case class Add(id: Int) extends Command
private final case object AccumulationTimeout extends Command
private final case object Ack extends Command
</code>```

However, my two states accumulating and emitting have to handle each other's commands. I could use .receivePartial or include a catch all

```<code>case _ => Behaviors.unhandled
</code>```

In both cases, I've lost exhaustive pattern matching to make sure I handle my state properly.

I can further refine the commands as such:

```<code>sealed trait Command

sealed trait Accumulating extends Command
private final case object AccumulationTimeout extends Accumulating

sealed trait Emitting extends Command
private final case object Ack extends Emitting

final case class Add(id: Int) extends Accumulating with Emitting
</code>```

With this I can define Behavior[Accumulating] and Behavior[Emitting] which both are Behavior[Command], but the catch is that there is no way for either of the behaviors to transition to the other, since both have to return their own type.

I've tried various permutations of .widen and .narrow to no avail and realize that what I truly need is a way to define a Behavior as

```<code>def receiveMessage[T, V <: T](handler: V => Behavior[T]): Behavior[T] = ???
</code>```

where handler would give me exhaustive checking on the narrow type V and for any message T outside of V would return Behaviors.unhandled. I just can't seem to make the types work to implement such a function.

答:
One idea would be to do an initial matching on the state-specific subset of commands. Something like:

def accumulating: Behavior[Command] =
  Behaviors.receive {
    case acc: Accumulating =>
      acc match {
        //... complete for the message subtype or compiler fails...
      }
    case _ =>
      // other state subtypes are
      Behaviors.unhandled
```

Body:
I started working with Akka Typed to get exhaustive pattern matching on my behaviors, which has been great for the external facing contract of each actor. However, if the actor is a state machine, chances are the different states have state specific commands.

I can hide state-specific commands as private members of the overall command like this:

sealed trait Command
final case class Add(id: Int) extends Command
private final case object AccumulationTimeout extends Command
private final case object Ack extends Command

However, my two states accumulating and emitting have to handle each other's commands. I could use .receivePartial or include a catch all

case _ => Behaviors.unhandled

In both cases, I've lost exhaustive pattern matching to make sure I handle my state properly.

I can further refine the commands as such:

sealed trait Command

sealed trait Accumulating extends Command
private final case object AccumulationTimeout extends Accumulating

sealed trait Emitting extends Command
private final case object Ack extends Emitting

final case class Add(id: Int) extends Accumulating with Emitting

With this I can define Behavior[Accumulating] and Behavior[Emitting] which both are Behavior[Command], but the catch is that there is no way for either of the behaviors to transition to the other, since both have to return their own type.

I've tried various permutations of .widen and .narrow to no avail and realize that what I truly need is a way to define a Behavior as

def receiveMessage[T, V <: T](handler: V => Behavior[T]): Behavior[T] = ???

where handler would give me exhaustive checking on the narrow type V and for any message T outside of V would return Behaviors.unhandled. I just can't seem to make the types work to implement such a function.


问:
ArrayindexOutOfBounds Exception strange tried to refactor many times Kotlin issue
The app has a bottomnavigation of two tabs one for tasks and one for notes.

I get no errror on the start as it starts by loding the tasks. but when I press the notes tab it crashes.

have subtracted 1 from the position of the masterlist as I have added a button to the top (1st position in the array) thinking this would correct it.

BaseRecyclerAdapter class

```<code>abstract class BaseRecyclerAdapter<T>(
    protected val masterList: MutableList<T> = mutableListOf()
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    override fun getItemCount(): Int = masterList.size + 1

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is TaskAdapter.AddButtonViewHolder) {
            holder.onBind(Unit)
        } else {
            (holder as BaseViewHolder<T>).onBind(masterList[position - 1])
        }
    }

    override fun getItemViewType(position: Int): Int =
        if (position == 0) {
            TYPE_ADD_BUTTON
        } else {
            TYPE_INFO
        }

    abstract class BaseViewHolder<E>(val view: View) : RecyclerView.ViewHolder(view) {
        abstract fun onBind(data: E)
    }

    abstract class AddButtonViewHolder(view: View) : BaseViewHolder<Unit>(view)

    companion object {
        const val TYPE_ADD_BUTTON = 0
        const val TYPE_INFO = 1
    }
}
</code>```

NotesAdapter

```<code>class NoteAdapter(notesList: MutableList<Note> = mutableListOf()) : BaseRecyclerAdapter<Note>(notesList) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =

        if(viewType == TYPE_ADD_BUTTON){
            AddButtonViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.view_add_button, parent, false))
        } else {
            NoteViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_note, parent, false))

        }

    override fun getItemViewType(position: Int): Int =
        if(position == 0){
            TYPE_ADD_BUTTON
        }else {
            TYPE_INFO
        }

    override fun getItemCount(): Int = masterList.size + 1

    class NoteViewHolder(view: View) :BaseViewHolder<Note>(view){

        override fun onBind(data: Note) {
            (view as NoteView).initView(data)
        }
    }

    class AddButtonViewHolder(view: View): BaseRecyclerAdapter.AddButtonViewHolder(view){
        override fun onBind(data: Unit) {
            view.buttonText.text = view.context.getText(R.string.add_button_note)
        }

    }
}
</code>```

NoteListFragment

```<code>class NotesListFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_notes_list, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerViewNote.layoutManager = LinearLayoutManager(context)
        val adapter = NoteAdapter(mutableListOf(
            Note("Ben Mohammad", null),
            Note("Joesph and and Maria", null)
        ))
        recyclerViewNote.adapter = adapter
    }

    companion object {

        fun newInstance() = NotesListFragment()
    }

}
</code>```

NoteView

```<code>class NoteView @JvmOverloads constructor (context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 1) :
    ConstraintLayout(context, attrs, defStyleAttr){

    fun initView(note: Note){
        description.text = note.description
  }
}
</code>```

I've used Custom views nested That is what I'm trying to do....obviously trying to keep it very OOP style getting stuck with it...

```<code>class TaskAdapter(
    tasksList: MutableList<Task> = mutableListOf()
) : BaseRecyclerAdapter<Task>(tasksList) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =

        if (viewType == TYPE_INFO) {
            TaskViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_task, parent, false))
        } else {
            AddButtonViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.view_add_button, parent, false))
        }

    class TaskViewHolder(view: View) : BaseViewHolder<Task>(view) {

        override fun onBind(data: Task) {
            (view as TaskView).initView(data)

        }
    }

    class AddButtonViewHolder(view: View) : BaseRecyclerAdapter.AddButtonViewHolder(view) {
        override fun onBind(data: Unit) {
            view.buttonText.text = view.context.getText(R.string.add_button_task)
        }

    }

}
</code>```

TasksListfragment

```<code>class TasksListFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_tasks_list, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerView.layoutManager = LinearLayoutManager(context)
        val adapter = TaskAdapter(
            mutableListOf(
                Task(
                    "Testing one!!",
                    mutableListOf(
                        Todo("Test 1!!"),
                        Todo("Test 2!!", true)

                    )
                ),
                Task("Testing two!!")
            )
        )
        recyclerView.adapter = adapter
    }

    companion object {

        fun newInstance() = TasksListFragment()
    }

}
</code>```

TaskView

```<code>class TaskView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 1) :
    ConstraintLayout(context, attrs, defStyleAttr) {

    lateinit var task: Task

    fun initView(task: Task) {
        this.task = task

        titleView.text = task.title
        task.todos.forEach {

                todo ->
            val todoView =
                (LayoutInflater.from(context).inflate(R.layout.view_todo, todoContainer, false) as TodoView).apply {
                    initView(todo) {
                        if (isTaskcomplete()) {
                            createstrikeThrough()
                        } else {
                            removeStrikeThrough()
                        }

                    }
                }

            todoContainer.addView(todoView)

        }
    }

    fun isTaskcomplete(): Boolean = task.todos.filter { !it.isComplete }.isEmpty()

    private fun createstrikeThrough() {
        titleView.apply {
            paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        }

    }

    private fun removeStrikeThrough() {
        titleView.apply {
            paintFlags = paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
        }

    }
}
</code>```

For further classes, all code is pushed to GitHub.

答:
The problem is here:

```<code>if (holder is TaskAdapter.AddButtonViewHolder) { // <--- problematic line
    holder.onBind(Unit)
} else {
    (holder as BaseViewHolder<T>).onBind(masterList[position - 1])
}
</code>```

You have two different subclasses of BaseRecyclerAdapter: your TaskAdapter and your NotesAdapter. When this is called for position 0 for your NotesAdapter, the if (holder is ...) check will fail, because the type is NotesAdapter.AddButtonViewHolder.

This will cause execution to fall into the else case, and your masterList[position - 1] logic will wind up querying for index -1.

To work around this, use the view type instead of checking the subclass with is. The base RecyclerView.ViewHolder class has a getItemViewType() method that will return to you whatever you returned from your adapter. Since the view type logic is defined in your base adapter class, this will be the same regardless of which concrete implementation type is being used.

```<code>if (holder.itemViewType == TYPE_ADD_BUTTON) {
    (holder as AddButtonViewHolder).onBind(Unit)
} else {
    (holder as BaseViewHolder<T>).onBind(masterList[position - 1])
}
</code>```

Body:
The app has a bottomnavigation of two tabs one for tasks and one for notes.

I get no errror on the start as it starts by loding the tasks. but when I press the notes tab it crashes.

have subtracted 1 from the position of the masterlist as I have added a button to the top (1st position in the array) thinking this would correct it.

BaseRecyclerAdapter class

abstract class BaseRecyclerAdapter<T>(
    protected val masterList: MutableList<T> = mutableListOf()
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    override fun getItemCount(): Int = masterList.size + 1

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is TaskAdapter.AddButtonViewHolder) {
            holder.onBind(Unit)
        } else {
            (holder as BaseViewHolder<T>).onBind(masterList[position - 1])
        }
    }

    override fun getItemViewType(position: Int): Int =
        if (position == 0) {
            TYPE_ADD_BUTTON
        } else {
            TYPE_INFO
        }

    abstract class BaseViewHolder<E>(val view: View) : RecyclerView.ViewHolder(view) {
        abstract fun onBind(data: E)
    }

    abstract class AddButtonViewHolder(view: View) : BaseViewHolder<Unit>(view)

    companion object {
        const val TYPE_ADD_BUTTON = 0
        const val TYPE_INFO = 1
    }
}

NotesAdapter

class NoteAdapter(notesList: MutableList<Note> = mutableListOf()) : BaseRecyclerAdapter<Note>(notesList) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =

        if(viewType == TYPE_ADD_BUTTON){
            AddButtonViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.view_add_button, parent, false))
        } else {
            NoteViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_note, parent, false))

        }

    override fun getItemViewType(position: Int): Int =
        if(position == 0){
            TYPE_ADD_BUTTON
        }else {
            TYPE_INFO
        }

    override fun getItemCount(): Int = masterList.size + 1

    class NoteViewHolder(view: View) :BaseViewHolder<Note>(view){

        override fun onBind(data: Note) {
            (view as NoteView).initView(data)
        }
    }

    class AddButtonViewHolder(view: View): BaseRecyclerAdapter.AddButtonViewHolder(view){
        override fun onBind(data: Unit) {
            view.buttonText.text = view.context.getText(R.string.add_button_note)
        }

    }
}

NoteListFragment

class NotesListFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_notes_list, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerViewNote.layoutManager = LinearLayoutManager(context)
        val adapter = NoteAdapter(mutableListOf(
            Note("Ben Mohammad", null),
            Note("Joesph and and Maria", null)
        ))
        recyclerViewNote.adapter = adapter
    }

    companion object {

        fun newInstance() = NotesListFragment()
    }

}

NoteView

class NoteView @JvmOverloads constructor (context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 1) :
    ConstraintLayout(context, attrs, defStyleAttr){

    fun initView(note: Note){
        description.text = note.description
  }
}

I've used Custom views nested That is what I'm trying to do....obviously trying to keep it very OOP style getting stuck with it...

class TaskAdapter(
    tasksList: MutableList<Task> = mutableListOf()
) : BaseRecyclerAdapter<Task>(tasksList) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =

        if (viewType == TYPE_INFO) {
            TaskViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_task, parent, false))
        } else {
            AddButtonViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.view_add_button, parent, false))
        }

    class TaskViewHolder(view: View) : BaseViewHolder<Task>(view) {

        override fun onBind(data: Task) {
            (view as TaskView).initView(data)

        }
    }

    class AddButtonViewHolder(view: View) : BaseRecyclerAdapter.AddButtonViewHolder(view) {
        override fun onBind(data: Unit) {
            view.buttonText.text = view.context.getText(R.string.add_button_task)
        }

    }

}

TasksListfragment

class TasksListFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_tasks_list, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recyclerView.layoutManager = LinearLayoutManager(context)
        val adapter = TaskAdapter(
            mutableListOf(
                Task(
                    "Testing one!!",
                    mutableListOf(
                        Todo("Test 1!!"),
                        Todo("Test 2!!", true)

                    )
                ),
                Task("Testing two!!")
            )
        )
        recyclerView.adapter = adapter
    }

    companion object {

        fun newInstance() = TasksListFragment()
    }

}

TaskView

class TaskView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 1) :
    ConstraintLayout(context, attrs, defStyleAttr) {

    lateinit var task: Task

    fun initView(task: Task) {
        this.task = task

        titleView.text = task.title
        task.todos.forEach {

                todo ->
            val todoView =
                (LayoutInflater.from(context).inflate(R.layout.view_todo, todoContainer, false) as TodoView).apply {
                    initView(todo) {
                        if (isTaskcomplete()) {
                            createstrikeThrough()
                        } else {
                            removeStrikeThrough()
                        }

                    }
                }

            todoContainer.addView(todoView)

        }
    }

    fun isTaskcomplete(): Boolean = task.todos.filter { !it.isComplete }.isEmpty()

    private fun createstrikeThrough() {
        titleView.apply {
            paintFlags = paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        }

    }

    private fun removeStrikeThrough() {
        titleView.apply {
            paintFlags = paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
        }

    }
}

For further classes, all code is pushed to GitHub.

Body:
The problem is here:

if (holder is TaskAdapter.AddButtonViewHolder) { // <--- problematic line
    holder.onBind(Unit)
} else {
    (holder as BaseViewHolder<T>).onBind(masterList[position - 1])
}

You have two different subclasses of BaseRecyclerAdapter: your TaskAdapter and your NotesAdapter. When this is called for position 0 for your NotesAdapter, the if (holder is ...) check will fail, because the type is NotesAdapter.AddButtonViewHolder.

This will cause execution to fall into the else case, and your masterList[position - 1] logic will wind up querying for index -1.

To work around this, use the view type instead of checking the subclass with is. The base RecyclerView.ViewHolder class has a getItemViewType() method that will return to you whatever you returned from your adapter. Since the view type logic is defined in your base adapter class, this will be the same regardless of which concrete implementation type is being used.

if (holder.itemViewType == TYPE_ADD_BUTTON) {
    (holder as AddButtonViewHolder).onBind(Unit)
} else {
    (holder as BaseViewHolder<T>).onBind(masterList[position - 1])
}


问:
Promise.all is finished before the promises that it's relying on
I have a list of API requests that only when all of them are finished I will return an answer. I used th Promise.all for that but it seems like the then of promise.all is being triggered before the promises he suppose to wait for.
I figured it happens because I have an get request inside of a post request. How can I make this work?

This a react-redux prject.

```<code>if (devices) {
    const APIArray = [];
    devices.forEach(device => {
        const data = {
            id: device.id,
        };
        dispatch({ type: EDIT_DEVICE, payload: data });
        APIArray.push(
            axios
                .post('/deploy/update', data)
                .then(res => {
                    ApiUtils.get(`/deploy/device?deviceId=${data.id}`).then(response => {
                        console.log('1');
                        dispatch({ type: EDIT_DEVICE_SUCCESS, payload: { device: response.data } });
                    });
                })
                .catch(error => {
                    dispatch({ type: EDIT_DEVICE_FAIL, payload: { device: data, error: error } });
                })
        );
    });

    return Promise.all(APIArray)
        .then(res => {
            console.log('2');
            dispatch({ type: UPDATE_DEVICES_SUCCESS, payload: res });
            return res;
        })
        .catch(err => {
            return err
        );
}

expected: console.log('1')
          console.log('1')
          console.log('2')
actual: console.log('2')
        console.log('1')
        console.log('1')
</code>```

答:
This is because the promises are the ones returned by Axios.post, but once you receive the post result you do another get into another promise.

```<code>APIArray.push(
        axios
            .post('/deploy/update', data)
            .then(res => {
                return ApiUtils.get(`/deploy/device?deviceId=${data.id}`).then(response => {
                    console.log('1');
                    dispatch({ type: EDIT_DEVICE_SUCCESS, payload: { device: response.data } });
                });
            })
            .catch(error => {
                dispatch({ type: EDIT_DEVICE_FAIL, payload: { device: data, error: error } });
            })
    );
</code>```

See in the then, I have added a return statement. That way the ApiUtils.get promise gets passed to the promise chain.

Body:
I have a list of API requests that only when all of them are finished I will return an answer. I used th Promise.all for that but it seems like the then of promise.all is being triggered before the promises he suppose to wait for.
I figured it happens because I have an get request inside of a post request. How can I make this work?

This a react-redux prject.

if (devices) {
    const APIArray = [];
    devices.forEach(device => {
        const data = {
            id: device.id,
        };
        dispatch({ type: EDIT_DEVICE, payload: data });
        APIArray.push(
            axios
                .post('/deploy/update', data)
                .then(res => {
                    ApiUtils.get(`/deploy/device?deviceId=${data.id}`).then(response => {
                        console.log('1');
                        dispatch({ type: EDIT_DEVICE_SUCCESS, payload: { device: response.data } });
                    });
                })
                .catch(error => {
                    dispatch({ type: EDIT_DEVICE_FAIL, payload: { device: data, error: error } });
                })
        );
    });

    return Promise.all(APIArray)
        .then(res => {
            console.log('2');
            dispatch({ type: UPDATE_DEVICES_SUCCESS, payload: res });
            return res;
        })
        .catch(err => {
            return err
        );
}

expected: console.log('1')
          console.log('1')
          console.log('2')
actual: console.log('2')
        console.log('1')
        console.log('1')

Body:
This is because the promises are the ones returned by Axios.post, but once you receive the post result you do another get into another promise.

APIArray.push(
        axios
            .post('/deploy/update', data)
            .then(res => {
                return ApiUtils.get(`/deploy/device?deviceId=${data.id}`).then(response => {
                    console.log('1');
                    dispatch({ type: EDIT_DEVICE_SUCCESS, payload: { device: response.data } });
                });
            })
            .catch(error => {
                dispatch({ type: EDIT_DEVICE_FAIL, payload: { device: data, error: error } });
            })
    );

See in the then, I have added a return statement. That way the ApiUtils.get promise gets passed to the promise chain.


答:
You have to return the inner promise to the outer chain:

```<code> return ApiUtils.get(`/deploy/device?deviceId=${data.id}`).then(/*...*/);
</code>```

By returning it, the promise returned by the outer .then will be chained of that.

Title: Promise.all is finished before the promises that it's relying on

Body:
You have to return the inner promise to the outer chain:

 return ApiUtils.get(`/deploy/device?deviceId=${data.id}`).then(/*...*/);

By returning it, the promise returned by the outer .then will be chained of that.


问:
convert List of List to a single column in Dataframe
I have a pandas dataframe as below:

```<code>comments         tags
===============================
Hello I am fine  #askfine #tag1
How are you ?    #ask # tag2
</code>```

I have the below list of lists:

```<code>[['Hello', 'I', 'am', 'fine'], ['How', 'are', 'you', '?']]
</code>```

Now, I wanted to append the below list of lists as a single column to the original dataframe.

```<code>comments         tags             processed_comments
==============================================================
Hello I am fine  #askfine #tag1   ['Hello', 'I', 'am', 'fine']
How are you ?    #ask # tag2      ['How', 'are', 'you', '?']
</code>```

How do I do?

df['processed_comments'] = listOfList is not working.

Thanks

答:
```<code>l = [['Hello', 'I', 'am', 'fine'], ['How', 'are', 'you', '?']]
</code>```

You can just use:

```<code>df['processed_comments'] = l
df
    comments         processed_comments
0   Hello I am fine [Hello, I, am, fine]
1   How are you ?   [How, are, you, ?]
</code>```

Each list element is considered a value of the row. So make sure that the length of the list, i.e., the lists inside the list, is equal to the number of rows.

Body:
I have a pandas dataframe as below:

comments         tags
===============================
Hello I am fine  #askfine #tag1
How are you ?    #ask # tag2

I have the below list of lists:

[['Hello', 'I', 'am', 'fine'], ['How', 'are', 'you', '?']]

Now, I wanted to append the below list of lists as a single column to the original dataframe.

comments         tags             processed_comments
==============================================================
Hello I am fine  #askfine #tag1   ['Hello', 'I', 'am', 'fine']
How are you ?    #ask # tag2      ['How', 'are', 'you', '?']

How do I do?

df['processed_comments'] = listOfList is not working.

Thanks

Body:
l = [['Hello', 'I', 'am', 'fine'], ['How', 'are', 'you', '?']]

You can just use:

df['processed_comments'] = l
df
    comments         processed_comments
0   Hello I am fine [Hello, I, am, fine]
1   How are you ?   [How, are, you, ?]

Each list element is considered a value of the row. So make sure that the length of the list, i.e., the lists inside the list, is equal to the number of rows.


问:
focus issue using a JComboBox as a cell editor in a JTable
I'm having issues with the following code, where I use a JComboBox to change a String value in a table cell.  The JComboBox works fine, but if I click in the box and then click away without selecting anything the JComboBox's dropdown remains visible, even if I delete the row.  Clicking on another Swing component like a JButton often causes it to go away, but not always.

```<code>
    TableColumn col = myTable.getColumnModel().getColumn(0);
    JComboBox eq = new JComboBox();
    eq.addItem("==");
    eq.addItem("!=");
    DefaultCellEditor editor = new DefaultCellEditor(eq);
    col.setCellEditor(editor);</code>```

Edit:
I had neglected to mention that earlier I set:

```<code>
    myTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
</code>```

If I comment this line out or set it false, then clicking on other Swing components does NOT cause the box to vanish.  With it in, clicking on anything that takes focus causes the box to go away, making the problem less annoying but possibly masking the cause of the behavior.

Am I doing something wrong here, or forgetting a step?  Alternately, is there a way to force it to close itself?

Thanks!

答:
To understand this you'll need to understand what goes on with an editable table. A short bit of theory:

Every cell has a potential renderer and editor. The renderer just tells the cell how to draw and does not interact with events. The editor however is a component that can interact with events. When an event happens that triggers an edit, the editor component is added on top of the table. When the edit finishes, the component is removed.

In order to get the component to go away, you'll have to make sure the cell is not still in the "editing" state. This is why terminateEditOnFocusLast causes the JComboBox to vanish. If you want other things to get the box to go, you'll need to probably call removeEditor() in response to certain events, possibly focus, or cell selection.

To really get a handle on what happens I'd recommend having a quick look at the source code to removeEditor(), editCellAt() etc., and maybe step through once in a debugger. It's possible you've overridden some of the event handling code, or are calling it when you shouldn't. The editor/event handling code in JTable is fairly fragile, and it's quite easy by accident to get calls to happen in the wrong order with funny side effects.

Also, Java very subtly changed the event and focus behaviour of JTable between versions once, I think it was between 1.4 and 1.5, when the focus handling for swing changed. So the first thing I'd recommend trying is your code with a different Java version. The bug may have been caused by Sun (some of our complicated editor code had to be changed) and if it differs between releases it is easier to report to Sun.

Body:
I'm having issues with the following code, where I use a JComboBox to change a String value in a table cell.  The JComboBox works fine, but if I click in the box and then click away without selecting anything the JComboBox's dropdown remains visible, even if I delete the row.  Clicking on another Swing component like a JButton often causes it to go away, but not always.

    TableColumn col = myTable.getColumnModel().getColumn(0);
    JComboBox eq = new JComboBox();
    eq.addItem("==");
    eq.addItem("!=");
    DefaultCellEditor editor = new DefaultCellEditor(eq);
    col.setCellEditor(editor);

Edit:
I had neglected to mention that earlier I set:

    myTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

If I comment this line out or set it false, then clicking on other Swing components does NOT cause the box to vanish.  With it in, clicking on anything that takes focus causes the box to go away, making the problem less annoying but possibly masking the cause of the behavior.

Am I doing something wrong here, or forgetting a step?  Alternately, is there a way to force it to close itself?

Thanks!

LastEditorDisplayName: JMurphy

OwnerDisplayName: Nick Fortescue


问:
PHP code in viewing a pdf file from a mysql database
How to view .pdf file in a webpage using PHP? The pdf file is in a mysql database. Thanks.</p>

答:
The pdf file is in a mysql database

Shocking! They are rarely good results in saving files in a database. Directories are better storing places for files.

```<code>header('Content-type: application/pdf');
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Disposition: inline;filename='document.pdf'");
header("Content-length: ".strlen($binary_contents_from_database));

echo $binary_contents_from_database;
</code>```

If a PDF plug-in is available for the browser, then the document will be displayed inline, otherwise it will be given as a download.

Body:
The pdf file is in a mysql database

Shocking! They are rarely good results in saving files in a database. Directories are better storing places for files.

header('Content-type: application/pdf');
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Disposition: inline;filename='document.pdf'");
header("Content-length: ".strlen($binary_contents_from_database));

echo $binary_contents_from_database;

If a PDF plug-in is available for the browser, then the document will be displayed inline, otherwise it will be given as a download.


问:
Pypandoc error , RuntimeError: Pandoc died with exitcode "47" during conversion: b'pdflatex not found
First time posting here,by the way, i've got an issue with this particular line of Python (3.6) code:

file_converted = pandoc.convert_file(PATH_TO_ODT, 'pdf', format="odt", outputfile=file_name + ".pdf", extra_args=['--pdf-engine=pdflatex'])

When i execute the script (to convert a .odt file to a .pdf file) , i encounter the following error :

RuntimeError: Pandoc died with exitcode "47" during conversion: b'pdflatex not found. Please select a different --pdf-engine or install pdflatex

Basically i understand that i need "pdflatex" , but after i've installed it via pip with the command

pip install pdflatex, the execution produce the same error message, what i should do or check?
thank you all.

答:
For pypandoc, which simply calls the pandoc commandline program, which in turn calls pdflatex, you should probably install LaTeX system-wide. On Ubuntu, that is:

```<code>sudo apt install texlive
</code>```

Body:
For pypandoc, which simply calls the pandoc commandline program, which in turn calls pdflatex, you should probably install LaTeX system-wide. On Ubuntu, that is:

sudo apt install texlive


问:
Is defining a default value for a Boolean input property in Angular bad practice?
I'm looking through an old Angular project and one component has an input property:

```<code>@Input()
isNotAdmin = true;
</code>```

Is directly assigning a value to the property within it's declaration like this considered bad practice? I understand that it depends on the context e.g. if we would like each of these components to have this property set to true if not stated, but I feel like boolean properties should be explicitly stated either way (true or false). Should the approach instead have a setter method as the input and a check to see if a value is passed, and if not, assign the property a default value?

答:
If you want to specify a default value if the input is not bound, what you wrote is a valid approach.

However, if you instead intend to provide a default value if the bound value is null or undefined, using a setter is the way to go:

```<code>private _isNotAdmin = true;

@Input()
set isNotAdmin(value: boolean) {
    if (value != null) {
        this._isNotAdmin = value;
    } else {
        this._isNotAdmin = true;
    }
}

get isNotAdmin(): boolean {
    return this._isNotAdmin;
}
</code>```

Body:
I'm looking through an old Angular project and one component has an input property:

@Input()
isNotAdmin = true;

Is directly assigning a value to the property within it's declaration like this considered bad practice? I understand that it depends on the context e.g. if we would like each of these components to have this property set to true if not stated, but I feel like boolean properties should be explicitly stated either way (true or false). Should the approach instead have a setter method as the input and a check to see if a value is passed, and if not, assign the property a default value?

Body:
If you want to specify a default value if the input is not bound, what you wrote is a valid approach.

However, if you instead intend to provide a default value if the bound value is null or undefined, using a setter is the way to go:

private _isNotAdmin = true;

@Input()
set isNotAdmin(value: boolean) {
    if (value != null) {
        this._isNotAdmin = value;
    } else {
        this._isNotAdmin = true;
    }
}

get isNotAdmin(): boolean {
    return this._isNotAdmin;
}


问:
How to open a URL in new window using WebBrowser control in c# Windows Forms application and read its header information (via regex etc)
As said, I would like to open a URL in a new window (not the default IE browser instance of WebBrowser control) and read the Header information in order to retrieve a token.
Currently, I am using the below code that opens in a new IE instance.

```<code>webBrowser1.Navigate(myLink, true);
</code>```

If I use the below code,

```<code>webBrowser1.Navigate(new Uri(myLink));
</code>```

it opens in the current window, I need it to open in a new WINDOW.

Any help would be greatly appreciated.

答:
u can use this code for open in a new window:

```<code>WebBrowser1.Navigate(url.SettingsValue, "_blank", post, headers);
</code>```

Parameter => url.SettingsValue = your url address

Parameter => "_blank" = for new blank

Parameter => post (your choice) = your token or password

Parameter => headers (your choice) = token header like => "Authorization: Basic " + auth + "\r\n";

Body:
As said, I would like to open a URL in a new window (not the default IE browser instance of WebBrowser control) and read the Header information in order to retrieve a token.
Currently, I am using the below code that opens in a new IE instance.

webBrowser1.Navigate(myLink, true);

If I use the below code,

webBrowser1.Navigate(new Uri(myLink));

it opens in the current window, I need it to open in a new WINDOW.

Any help would be greatly appreciated.

Body:
u can use this code for open in a new window:

WebBrowser1.Navigate(url.SettingsValue, "_blank", post, headers);

Parameter => url.SettingsValue = your url address

Parameter => "_blank" = for new blank

Parameter => post (your choice) = your token or password

Parameter => headers (your choice) = token header like => "Authorization: Basic " + auth + "\r\n";


问:
is there a way to prevent a form to show multiple times in #c?
so I have this program, and I want to prevent it from opening multiple times but can seem to get the hang of it =/

```<code>    private void button1_Click(object sender, EventArgs e)
    {

        if (forge.Checked)
        {
            successfully_injected openForm = new successfully_injected();
            openForm.Show();
            this.Close();
        }
        else if (!forge.Checked)
        {
            select_option openForm = new select_option();
            openForm.Show();
        }

    }
</code>```

I only want to be able to click the button once and then it stops showing more windows, but the result I get right now is that I can click it and it will just keep opening windows every time I click so yeh =/

答:
You could check the collection OpenForms from the Application object</p>

```<code>if(forge.Checked)
{
   successfully_injected openForm = Application.OpenForms.OfType<successfully_injected>().FirstOrDefault();
   if(openForm == null)
       openForm = new successfully_injected();
   openForm.Show();
}
else
{
   select_option openForm = Application.OpenForms.OfType<select_option>().FirstOrDefault();
   if(openForm == null)
       openForm = new select_option();
   openForm.Show();
}
this.Close();
</code>```

Body:
so I have this program, and I want to prevent it from opening multiple times but can seem to get the hang of it =/

    private void button1_Click(object sender, EventArgs e)
    {

        if (forge.Checked)
        {
            successfully_injected openForm = new successfully_injected();
            openForm.Show();
            this.Close();
        }
        else if (!forge.Checked)
        {
            select_option openForm = new select_option();
            openForm.Show();
        }

    }

I only want to be able to click the button once and then it stops showing more windows, but the result I get right now is that I can click it and it will just keep opening windows every time I click so yeh =/

Body:
You could check the collection OpenForms from the Application object

if(forge.Checked)
{
   successfully_injected openForm = Application.OpenForms.OfType<successfully_injected>().FirstOrDefault();
   if(openForm == null)
       openForm = new successfully_injected();
   openForm.Show();
}
else
{
   select_option openForm = Application.OpenForms.OfType<select_option>().FirstOrDefault();
   if(openForm == null)
       openForm = new select_option();
   openForm.Show();
}
this.Close();


问:
How to send long SMS in Android?
I'm using RSA Encryption with a key of 1024bit , the ciphered text's length will be more than 160 bytes , and on sending an SMS of more than 160bytes it gives exception and after using sendmultisms() and divide the message , at the receiver side gets unprintable characters and also I will have a problem of how to concatandenate the SMSs.</p>

答: You could use data-sms which supports true 8bit, whereass a normal sms only takes 7bit. This is why you get garbage on the other side without any further encoding efforts.</p>

Title: How to send long SMS in Android?


问:
Should the Eigen-unsupported modules be avoided?
The popular linear algebra library Eigen comes with a long list of so-called "unsupported" modules, for example modules for FFT, numerical differentiation or Euler angles.

In the Eigen documentation, it is clearly stated:

These modules are contributions from various users. They are provided "as is", without any support.

Unfortunately, there is no statement in the documentation about potential discontinuation of unsupported modules, requirements to the quality of implementation, level of testing, and so on.

This leaves me with the following question:

Should I be using Eigen unsupported modules at all, if I want my software to be stable for a few years (and at least to be compatible with future major/minor Eigen releases). Example: in particular, I would like to avoid the situation that an unsupported module I am using drops away when upgrading from Eigen 3.7.x to 3.8.x, for instance.

Are there any experiences or opinions out there regarding the stability and availability of the unsupported modules?

(Just for completeness: the particular unsupported module I am considering is the EulerAngles module).

答:
Generally, I suggest trying out the unsupported modules and give feedback about their usefulness, bugs, suggestions for API-changes etc. That is the most likely way that a currently unsupported module will eventually get moved to the standard modules.

You need to be prepared to change parts of your source if the API changes or if the module becomes stable (ideally, this requires just changing an #include) -- of course this could be more complicated if you want to be compatible to old and new Eigen versions.

I'd say the EulerAngles module is pretty stable and well-tested and already integrates well into the Geometry module -- but it is likely not used a lot (we don't have statistics about the usage of individual modules).

In contrast the Tensor module (mentioned by @datell), is used heavily (e.g., by TensorFlow), but in my opinion is not well-integrated yet into the rest of Eigen (e.g., documentation is mostly a single .md which is not completely in-sync with the current API): http://eigen.tuxfamily.org/dox-devel/unsupported/eigen_tensors.html

N.B.: I'm one of the Eigen maintainers.


问:
How to get all unique paths between two nodes?
I'm using trek and mountaineering routing database and I try to find all possible routes between Darjeeling and Sandakphu.

That is not a problem - here is query for that:

```<code>MATCH allPaths=(town:town{name:'Darjeeling'})-[*]->(peak:peak{name:'Sandakphu'})
RETURN allPaths
</code>```

But this query returns same routes multiple times, for example:

```<code>╒══════════════════════════════════════════════════════════════════════╕
│"allPaths"                                                            │
╞══════════════════════════════════════════════════════════════════════╡
│[{"name":"Darjeeling"},{"name":"Darjeeling-Rimbik","winter":"true","di│
│stance":15,"summer":"true"},{"name":"Rimbik"},{"name":"Rimbik"},{"name│
│":"Rimbik-Sirikhola","winter":"true","distance":4,"summer":"true"},{"n│
│ame":"Sirikhola"},{"name":"Sirikhola"},{"name":"Sirikhola-Gurdum","win│
│ter":"true","distance":6,"summer":"true"},{"name":"Gurdum"},{"name":"G│
│urdum"},{"name":"Gurdum-Sandakphu","winter":"true","distance":12,"summ│
│er":"true"},{"name":"Sandakphu","altitude":"12400 ft"}]               │
├──────────────────────────────────────────────────────────────────────┤
│[{"name":"Darjeeling"},{"name":"Darjeeling-Rimbik","winter":"true","di│
│stance":15,"summer":"true"},{"name":"Rimbik"},{"name":"Rimbik"},{"name│
│":"Rimbik-Sirikhola","winter":"true","distance":4,"summer":"true"},{"n│
│ame":"Sirikhola"},{"name":"Sirikhola"},{"name":"Sirikhola-Gurdum","win│
│ter":"true","distance":6,"summer":"true"},{"name":"Gurdum"},{"name":"G│
│urdum"},{"name":"Gurdum-Sandakphu","winter":"true","distance":12,"summ│
│er":"true"},{"name":"Sandakphu","altitude":"12400 ft"}]               │
├──────────────────────────────────────────────────────────────────────┤
</code>```

I've tried to use DISTINCT on RETURN as it is mentioned in documentation

```<code>MATCH allPaths=(town:town{name:'Darjeeling'})-[*]->(peak:peak{name:'Sandakphu'})
RETURN DISTINCT allPaths
</code>```

but unfortunately it doesn't work.

答:
Neo4j can't return the same route multiple times, that shouldn't be possible. The paths should be distinct, and the same result set when using RETURN DISTINCT allPaths proves it.

EDIT

Using the same data set I recreated this. The paths are distinct. What's throwing you off is that that there are multiple relationships between the same sets of nodes (for example, between Tumbling and Gairibus there are 3 relationships, of types :trek, :road, and :twowheeler) which all have the same properties.

In the Neo4j browser, when displaying the textual data of a relationship only the relationship properties are outputted, not the type or id, so simply doing a visual inspection of the relationship results (such as the relationships present in the path) makes it seem as if the paths are identical, but they are not.

The actual code results (if you were using a driver to call into Neo4j and fetch query results) would include ids and relationship type information, so it's just the browser's visual display that omitting the info that would differentiate the results.

There are 156 distinct paths you could use, but these will mostly be through the same nodes, just using permutations of different possible relationships to traverse the nodes.

If you want paths that ignore these relationship choices, then confine your query to :trek relationships, as these are always present when two nodes are connected:

```<code>MATCH path=(town:town{name:'Darjeeling'})-[:trek*]->(peak:peak{name:'Sandakphu'})
RETURN path
</code>```

This returns only 6 possible paths.

Body:
I'm using trek and mountaineering routing database and I try to find all possible routes between Darjeeling and Sandakphu.

That is not a problem - here is query for that:

MATCH allPaths=(town:town{name:'Darjeeling'})-[*]->(peak:peak{name:'Sandakphu'})
RETURN allPaths

But this query returns same routes multiple times, for example:

╒══════════════════════════════════════════════════════════════════════╕
│"allPaths"                                                            │
╞══════════════════════════════════════════════════════════════════════╡
│[{"name":"Darjeeling"},{"name":"Darjeeling-Rimbik","winter":"true","di│
│stance":15,"summer":"true"},{"name":"Rimbik"},{"name":"Rimbik"},{"name│
│":"Rimbik-Sirikhola","winter":"true","distance":4,"summer":"true"},{"n│
│ame":"Sirikhola"},{"name":"Sirikhola"},{"name":"Sirikhola-Gurdum","win│
│ter":"true","distance":6,"summer":"true"},{"name":"Gurdum"},{"name":"G│
│urdum"},{"name":"Gurdum-Sandakphu","winter":"true","distance":12,"summ│
│er":"true"},{"name":"Sandakphu","altitude":"12400 ft"}]               │
├──────────────────────────────────────────────────────────────────────┤
│[{"name":"Darjeeling"},{"name":"Darjeeling-Rimbik","winter":"true","di│
│stance":15,"summer":"true"},{"name":"Rimbik"},{"name":"Rimbik"},{"name│
│":"Rimbik-Sirikhola","winter":"true","distance":4,"summer":"true"},{"n│
│ame":"Sirikhola"},{"name":"Sirikhola"},{"name":"Sirikhola-Gurdum","win│
│ter":"true","distance":6,"summer":"true"},{"name":"Gurdum"},{"name":"G│
│urdum"},{"name":"Gurdum-Sandakphu","winter":"true","distance":12,"summ│
│er":"true"},{"name":"Sandakphu","altitude":"12400 ft"}]               │
├──────────────────────────────────────────────────────────────────────┤

I've tried to use DISTINCT on RETURN as it is mentioned in documentation

MATCH allPaths=(town:town{name:'Darjeeling'})-[*]->(peak:peak{name:'Sandakphu'})
RETURN DISTINCT allPaths

but unfortunately it doesn't work.

Body:
Neo4j can't return the same route multiple times, that shouldn't be possible. The paths should be distinct, and the same result set when using RETURN DISTINCT allPaths proves it.

EDIT

Using the same data set I recreated this. The paths are distinct. What's throwing you off is that that there are multiple relationships between the same sets of nodes (for example, between Tumbling and Gairibus there are 3 relationships, of types :trek, :road, and :twowheeler) which all have the same properties.

In the Neo4j browser, when displaying the textual data of a relationship only the relationship properties are outputted, not the type or id, so simply doing a visual inspection of the relationship results (such as the relationships present in the path) makes it seem as if the paths are identical, but they are not.

The actual code results (if you were using a driver to call into Neo4j and fetch query results) would include ids and relationship type information, so it's just the browser's visual display that omitting the info that would differentiate the results.

There are 156 distinct paths you could use, but these will mostly be through the same nodes, just using permutations of different possible relationships to traverse the nodes.

If you want paths that ignore these relationship choices, then confine your query to :trek relationships, as these are always present when two nodes are connected:

MATCH path=(town:town{name:'Darjeeling'})-[:trek*]->(peak:peak{name:'Sandakphu'})
RETURN path

This returns only 6 possible paths.


问:
Finding the array with the lowest max value of element
I have an arraylist of int[] arrays and I'm trying to find the array with the lowest max element.

For an example, from arrays [1,2,5], [0,1,2], [8,0,0] it would be the array [0,1,2] because the max element is 2.

However, my code is not working correctly. Could you help me fix my code? Thanks!

```<code>int min = Integer.MAX_VALUE;
for (int i=0; i<list.size(); i++) {
    for (int j=0; j<list.get(i).length; j++) {
        if (list.get(i)[j]<min) {
            min = list.get(i)[i];
            minIndex = i; //index of the array in arraylist
        }
    }
}
</code>```

答:
You can try this for example:

```<code>import java.util.Arrays;
import java.util.Comparator;

public class MaxMinArray {

    public static int[]  maxMinFromArray(int[][] arrays){
       return  Arrays.stream(arrays).min(Comparator.comparingInt(x -> Arrays.stream(x).max().orElse(0))).orElse(null);
    }
}
</code>```

I've tested it with your example :) :

```<code>import org.junit.Test;

import static org.junit.Assert.*;

public class MaxMinArrayTest {

    @Test
    public void testMaxMinArray(){
        int[][] arrays = new int[][] {{1,2,5}, {0,1,2}, {8,0,0}};
        int[] result = MaxMinArray.maxMinFromArray(arrays);
        assertArrayEquals(new int[]{0,1,2}, result);
    }
}
</code>```

Body:
I have an arraylist of int[] arrays and I'm trying to find the array with the lowest max element.

For an example, from arrays [1,2,5], [0,1,2], [8,0,0] it would be the array [0,1,2] because the max element is 2.

However, my code is not working correctly. Could you help me fix my code? Thanks!

int min = Integer.MAX_VALUE;
for (int i=0; i<list.size(); i++) {
    for (int j=0; j<list.get(i).length; j++) {
        if (list.get(i)[j]<min) {
            min = list.get(i)[i];
            minIndex = i; //index of the array in arraylist
        }
    }
}

Body:
You can try this for example:

import java.util.Arrays;
import java.util.Comparator;

public class MaxMinArray {

    public static int[]  maxMinFromArray(int[][] arrays){
       return  Arrays.stream(arrays).min(Comparator.comparingInt(x -> Arrays.stream(x).max().orElse(0))).orElse(null);
    }
}

I've tested it with your example :) :

import org.junit.Test;

import static org.junit.Assert.*;

public class MaxMinArrayTest {

    @Test
    public void testMaxMinArray(){
        int[][] arrays = new int[][] {{1,2,5}, {0,1,2}, {8,0,0}};
        int[] result = MaxMinArray.maxMinFromArray(arrays);
        assertArrayEquals(new int[]{0,1,2}, result);
    }
}


问:
How can my site be able for mobile device
I wanna to make my logo(KP advisory) and text responsive when resize the browser in full width, but unfortunately just mi background image resize. Maybe it's not hard to do but i don't know where is the problem. Also need to be able for mobile devices. Please help.

HTML

```<code><div class="container">
        <div class="banner">
                <img src="logo1.png" class="logo" width="650px" height="215px">
                    <h4 class="heading mt-100">KP business & financial<br>advisory services d.o.o.
                Beograd<br><br>Resavska 23,<br>1100 Beograd, Srbija<br><br>
                <a href="mailto:office@kp-advisory.com " class="link">office@kp-advisory.com</a>
            </div>
    </div>
</code>```

CSS

```<code>.link {
    color:white;
}

html {
    background: fixed;
}

body {
    margin: 0;
    height: 100%;
    background: url('pozadina.png') no-repeat fixed;
    background-size: cover;
    align-content: center;
    width: 100%;
    /* overflow: hidden; */
}
.container {
    display: flex;
    justify-content: center; /* align horizontal */
    align-items: center;
    height: 100vh;
}
.mt-100 {
    margin-top: 80p;
    font-size: 22px;
    align-content: center;
    font-family: 'Open Sans', sans-serif;
    font-weight: 100;
    height: 100%;

}
.banner {
    text-align: center;
    color: white;
    margin-top: -190px;
    overflow: hidden;
}

.logo {
  margin-top: 330px;
  background-size: cover;
    width: auto;
}
</code>```

答:
Use the media queries, in css: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

EDIT:
In your situation (example):

.banner {
    text-align: center;
    color: black;
    background-color: green;
}

@media only screen and (max-width: 600px) {
  .banner {
    color: red;
    background-color: yellow;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="banner">
  Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
</div></code>```

If your window browser has a maximum 600px - you see red font and yellow background.

Body:
I wanna to make my logo(KP advisory) and text responsive when resize the browser in full width, but unfortunately just mi background image resize. Maybe it's not hard to do but i don't know where is the problem. Also need to be able for mobile devices. Please help.

HTML

KP business & financial
advisory services d.o.o.
                Beograd

Resavska 23,
1100 Beograd, Srbija

                office@kp-advisory.com

CSS

.link {
    color:white;
}

html {
    background: fixed;
}

body {
    margin: 0;
    height: 100%;
    background: url('pozadina.png') no-repeat fixed;
    background-size: cover;
    align-content: center;
    width: 100%;
    /* overflow: hidden; */
}
.container {
    display: flex;
    justify-content: center; /* align horizontal */
    align-items: center;
    height: 100vh;
}
.mt-100 {
    margin-top: 80p;
    font-size: 22px;
    align-content: center;
    font-family: 'Open Sans', sans-serif;
    font-weight: 100;
    height: 100%;

}
.banner {
    text-align: center;
    color: white;
    margin-top: -190px;
    overflow: hidden;
}

.logo {
  margin-top: 330px;
  background-size: cover;
    width: auto;
}

Body:
Use the media queries, in css: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

EDIT:
In your situation (example):

.banner {
    text-align: center;
    color: black;
    background-color: green;
}

@media only screen and (max-width: 600px) {
  .banner {
    color: red;
    background-color: yellow;
  }
}

<div class="banner">
  Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum
</div>

If your window browser has a maximum 600px - you see red font and yellow background.


问:
setTimeOut() solution on Twitter
I was reading John resig's blogpost: http://ejohn.org/blog/learning-from-twitter/ and I did not understand the problem with setTimeOut()  there.

Question 1:

Johh shared this code:

```<code>var outerPane = $details.find(".details-pane-outer"),
    didScroll = false;

$(window).scroll(function() {
    didScroll = true;
});

setInterval(function() {
    if ( didScroll ) {
        didScroll = false;
        // Check your page position and then
        // Load in more results
    }
}, 250);
</code>```

Where is caching used here? I assume when didScroll is true, then outerPane variable will be used instead of re-searching the DOM, am I right?

Question 2:

In the comment section Michael shared a code:

```<code>var timer = 0;

$(window).scroll(function () {
if (timer) {
clearTimeout(timer);
}

// Use a buffer so we don't call myCallback too often.
timer = setTimeout(myCallback, 100);
});
</code>```

and said: "Instead of setting up an interval, the callback is only ever fired when it needs to be. Saves a few extra calls to the callback, and any overhead from the extra logic inside the scroll handler should be fairly minimal."

My question is: setTimeOut() will return a timerID which will be used by clearTimeOut to clear. Now with this setTimeout(myCallback, 100) function after every 100 mili second myCallBack function will be used, isn't it? Moreover, when the scroll event will fire the timer will be cleared and never set again, so what is the purpose of using it?

Sorry for my confusions. Have a nice day.

答:
Question 1:

outerPane is only ever fetched once, regardless of any other value.  The commented out lines would be where this variable would be used.  His point is simply that $(selector) multiple times will always be slower just reusing the result and calling that only once.  The code above will always have the outerPane variable anywhere that needs it, and it will be super fast.

Question 2:

Well, this code is kind of wrong.  Let me fix it:

```<code>var timer = null;

$(window).scroll(function () {
  if (timer) {
    clearTimeout(timer);
  }

  timer = setTimeout(function() {
    timer = null; // Added this line.
    mycallback();
  }, 100);
});
</code>```

The point of this is to only execute your big chunk of JavaScript (in mycallback()) when the user has actually stopped scrolling.  mycallback() will only get called when no scroll events have happened for 100ms.

So when a scroll happens, first it checks to see if there is a an unfired timeout, and if there is cancel it.  This will happen if multiple scroll events happen less than 100ms apart.  Then it sets a new timer to fire 100ms from now, which will clear out timer and fire mycallback().

This prevents mycallback() from running until no scroll events happen for 100ms.  The advantage is that if mycallback() takes a long time, it will never interrupt the smooth scrolling of the browser.

However, in the case of Twitter (like Resig is explaining) this approach won't work.  In Twitter's case they need to move things around the screen on every scroll event because they reposition things on the screen as you scroll.  So they do need to that calculation every single time the scroll event is fired in order to keep the window looking right as you scroll down.  But also when you it this way, you have to make sure your JS is super fast because it will be executed many times over and over while the user scrolls around (Hence the explanation of jQuery element caching).

Title: setTimeOut() solution on Twitter

Body:
I was reading John resig's blogpost: http://ejohn.org/blog/learning-from-twitter/ and I did not understand the problem with setTimeOut()  there.

Question 1:

Johh shared this code:

var outerPane = $details.find(".details-pane-outer"),
    didScroll = false;

$(window).scroll(function() {
    didScroll = true;
});

setInterval(function() {
    if ( didScroll ) {
        didScroll = false;
        // Check your page position and then
        // Load in more results
    }
}, 250);

Where is caching used here? I assume when didScroll is true, then outerPane variable will be used instead of re-searching the DOM, am I right?

Question 2:

In the comment section Michael shared a code:

var timer = 0;

$(window).scroll(function () {
if (timer) {
clearTimeout(timer);
}

// Use a buffer so we don't call myCallback too often.
timer = setTimeout(myCallback, 100);
});

and said: "Instead of setting up an interval, the callback is only ever fired when it needs to be. Saves a few extra calls to the callback, and any overhead from the extra logic inside the scroll handler should be fairly minimal."

My question is: setTimeOut() will return a timerID which will be used by clearTimeOut to clear. Now with this setTimeout(myCallback, 100) function after every 100 mili second myCallBack function will be used, isn't it? Moreover, when the scroll event will fire the timer will be cleared and never set again, so what is the purpose of using it?

Sorry for my confusions. Have a nice day.

Body:
Question 1:

outerPane is only ever fetched once, regardless of any other value.  The commented out lines would be where this variable would be used.  His point is simply that $(selector) multiple times will always be slower just reusing the result and calling that only once.  The code above will always have the outerPane variable anywhere that needs it, and it will be super fast.

Question 2:

Well, this code is kind of wrong.  Let me fix it:

var timer = null;

$(window).scroll(function () {
  if (timer) {
    clearTimeout(timer);
  }

  timer = setTimeout(function() {
    timer = null; // Added this line.
    mycallback();
  }, 100);
});

The point of this is to only execute your big chunk of JavaScript (in mycallback()) when the user has actually stopped scrolling.  mycallback() will only get called when no scroll events have happened for 100ms.

So when a scroll happens, first it checks to see if there is a an unfired timeout, and if there is cancel it.  This will happen if multiple scroll events happen less than 100ms apart.  Then it sets a new timer to fire 100ms from now, which will clear out timer and fire mycallback().

This prevents mycallback() from running until no scroll events happen for 100ms.  The advantage is that if mycallback() takes a long time, it will never interrupt the smooth scrolling of the browser.

However, in the case of Twitter (like Resig is explaining) this approach won't work.  In Twitter's case they need to move things around the screen on every scroll event because they reposition things on the screen as you scroll.  So they do need to that calculation every single time the scroll event is fired in order to keep the window looking right as you scroll down.  But also when you it this way, you have to make sure your JS is super fast because it will be executed many times over and over while the user scrolls around (Hence the explanation of jQuery element caching).


问:
Is there a way to score a list that have its members in another list?
I have two lists. The phrase list contain both words and phrases while the check list contains only words. I want to confirm if any member of the check list is a part or in the phrase list. I will give each string in the phrase list a score depending on its membership in the check list.

In the example below, information retrieval yields 0.5 because only one word ("information") out of two is in the check list. On the other hand, wave transformation yields 1 because both "wave" and "transformation" appear in check.

I have looked for how to do it but none has worked

```<code>score = []
phrase = ['information retrieval', 'wave transformation', 'information', 'services', 'gold coast village']
check = ['information', 'wave', 'transformation', 'village', 'services']
</code>```

I expect the score list to contain the score for each member of the phrase list.

```<code>phrase = ['information retrieval', 'wave transformation', 'information', 'services', 'gold coast village']
score = [0.5, 1, 1, 1, 0.33]
</code>```

答:
```<code>[sum(word in check for word in elem.split()) / len(elem.split()) for elem in phrase]
</code>```

Will return:

[0.5, 1.0, 1.0, 1.0, 0.3333333333333333]

Body:
I have two lists. The phrase list contain both words and phrases while the check list contains only words. I want to confirm if any member of the check list is a part or in the phrase list. I will give each string in the phrase list a score depending on its membership in the check list.

In the example below, information retrieval yields 0.5 because only one word ("information") out of two is in the check list. On the other hand, wave transformation yields 1 because both "wave" and "transformation" appear in check.

I have looked for how to do it but none has worked

score = []
phrase = ['information retrieval', 'wave transformation', 'information', 'services', 'gold coast village']
check = ['information', 'wave', 'transformation', 'village', 'services']

I expect the score list to contain the score for each member of the phrase list.

phrase = ['information retrieval', 'wave transformation', 'information', 'services', 'gold coast village']
score = [0.5, 1, 1, 1, 0.33]

Body:
[sum(word in check for word in elem.split()) / len(elem.split()) for elem in phrase]

Will return:

[0.5, 1.0, 1.0, 1.0, 0.3333333333333333]