问:
Setting timeout limit on Windows
I have a function that should not take too long to run. I would like to set a timeout limit on it. I can find one proposed solutions on the internet. See the following SO post. Timeout on a function call

The solution uses signals, which is not available on Windows. There is a similar use of signals for making a ticker, which has a windows port as explained on this SO post: python: windows equivalent of SIGALRM this is not an answer to the timeout directly, but could be adapted to work for timeouts. It is written for python 2.7 though.

Since the answers are roughly 10 years old, my question is: Is there any more modern python (e.g. python 3.7) way to create a context manager/decorator/similar wrapper do make a "normal function" into a timeout-limited function on a windows system?

答:
Here's a way to convert @Praveenkumar's answer into an easy-to-use decorator, which it seems you now would like to know:</p>

```<code>import time
import concurrent.futures as futures

def timeout(timelimit):
    def decorator(func):
        def decorated(*args, **kwargs):
            with futures.ThreadPoolExecutor(max_workers=1) as executor:
                future = executor.submit(func, *args, **kwargs)
                try:
                    result = future.result(timelimit)
                except futures.TimeoutError:
                    print('Timedout!')
                    raise TimeoutError from None
                else:
                    print(result)
                executor._threads.clear()
                futures.thread._threads_queues.clear()
                return result
        return decorated
    return decorator

@timeout(3)
def test(n):
    print(f'Sleeping for {n} seconds')
    time.sleep(n)
    # Real code here.
    return 'Done'

test(2)  # OK
test(5)  # -> Causes timeout.
</code>```

Title: Setting timeout limit on Windows

Body:
Here's a way to convert @Praveenkumar's answer into an easy-to-use decorator, which it seems you now would like to know:

import time
import concurrent.futures as futures

def timeout(timelimit):
    def decorator(func):
        def decorated(*args, **kwargs):
            with futures.ThreadPoolExecutor(max_workers=1) as executor:
                future = executor.submit(func, *args, **kwargs)
                try:
                    result = future.result(timelimit)
                except futures.TimeoutError:
                    print('Timedout!')
                    raise TimeoutError from None
                else:
                    print(result)
                executor._threads.clear()
                futures.thread._threads_queues.clear()
                return result
        return decorated
    return decorator

@timeout(3)
def test(n):
    print(f'Sleeping for {n} seconds')
    time.sleep(n)
    # Real code here.
    return 'Done'

test(2)  # OK
test(5)  # -> Causes timeout.


来源: stackexchange

问:
case-insensitive queries for a Socrata SoQL
I trying to find all the mixed case results.

For example 'Abee' will only return is searching that exact case.

I've looked in the like '...' option and tried upper (but it appears to be for the return not the query).

This is working query I'm passing.

https://data.nasa.gov/resource/gh4g-9sfh.json?$where=name%20like%20%27%25Abee%25%27

In my React app this is the function:

App.js

```<code>onChangeSearch = async (e) => {
    e.preventDefault();
    const name = e.target.elements.name.value;
    console.log('name: '+ name);
    const url = `${API_URL}?$limit=${API_LIMIT}&$where=name like %27%25${name}%25%27`;
    this.getData(url, 'meteorite');
  }
</code>```

Form.js

```<code>const Form = props => (
    <form onSubmit={props.onChangeSearch}>
        <input type="text" name="name" placeholder="Name..." />
        <button>Search</button>
    </form>
);
</code>```

I would the query itself to setup regardless if the user inputs 'ABEE', 'abee', or 'aBee'.

答:
First make your query uppercase

const nameUpper = name.toUpperCase();

Then use upper() on the name parameter, so the search is performed on the name properties while they are uppercase.

```<code>    const name = e.target.elements.name.value.toUpperCase();

    const url = `${API_URL}?$limit=${API_LIMIT}&$where=upper(name) like%27%25${name}%25%27`;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I trying to find all the mixed case results.

For example 'Abee' will only return is searching that exact case.

I've looked in the like '...' option and tried upper (but it appears to be for the return not the query).

This is working query I'm passing.

https://data.nasa.gov/resource/gh4g-9sfh.json?$where=name%20like%20%27%25Abee%25%27

In my React app this is the function:

App.js

onChangeSearch = async (e) => {
    e.preventDefault();
    const name = e.target.elements.name.value;
    console.log('name: '+ name);
    const url = `${API_URL}?$limit=${API_LIMIT}&$where=name like %27%25${name}%25%27`;
    this.getData(url, 'meteorite');
  }

Form.js

const Form = props => (
    <form onSubmit={props.onChangeSearch}>
        <input type="text" name="name" placeholder="Name..." />
        <button>Search</button>
    </form>
);

I would the query itself to setup regardless if the user inputs 'ABEE', 'abee', or 'aBee'.

Body:
First make your query uppercase

const nameUpper = name.toUpperCase();

Then use upper() on the name parameter, so the search is performed on the name properties while they are uppercase.

    const name = e.target.elements.name.value.toUpperCase();

    const url = `${API_URL}?$limit=${API_LIMIT}&$where=upper(name) like%27%25${name}%25%27`;


问:
Using a subquery in a hibernate FullTextEntityManager query
I am trying to modify some code using a hibernate FullTextEntityManager query.  Essentially it works currently but I would like to constrain the results to a subset of records in a table (the most recent of a given type).

So for example the underlying query of data to search might be something along these lines (for demonstration only, I haven't parsed this!)

```<code>SELECT name, address
FROM Persons p
WHERE p.name = sq.name
FROM
(SELECT name, max(datemodified)
 FROM Persons
  GROUP BY name) sq
</code>```

Currently the java code is just selecting from the raw table (essentially this is what the forEntity option does I think)

```<code>FullTextEntityManager ftem = Search.getFullTextEntityManager(getEntityManager());

SearchFactory sf= ftem.getSearchFactory();
QueryContextBuilder qcb = sf.buildQueryBuilder();
QueryBuilder qb= qcb.forEntity(entityClass).get();

//processSearchExpression builds a lucene style full text search
org.apache.lucene.search.Query q= processSearchExpression();

FullTextQuery ftq= ftem.createFullTextQuery(q, entityClass);
</code>```

So essentially I think I've put the essentials in there quite faithfully.  What I can't quite work out is how to add a sub query or something producing similar functionality so that I can just query the most recent records of each type ?

答:
At the moment the easiest solution to combine ORM queries with Search queries is to add a clause to you search query to filter by id.

FullTextEntityManager ftem = Search.getFullTextEntityManager(getEntityManager());

SearchFactory sf= ftem.getSearchFactory();
QueryBuilder qb= sf.buildQueryBuilder().forEntity(entityClass).get();

BooleanJunction<?> idJunction = qb.bool();
for (Long id : listIdsYouWant()) {
   idJunction.must(qb.match().onField("id").matching(id).createQuery());
}

org.apache.lucene.search.Query q = qb.bool()
   //processSearchExpression builds a lucene style full text search
    .must(processSearchExpression())
    .filteredBy(idJunction.createQuery)
    .createQuery();

FullTextQuery ftq= ftem.createFullTextQuery(q, entityClass);
```

If that is not an option, you should look for a way to index the data you need to reproduce the SQL query using a full-text query.

In your case, you seem to be using a custom-built versioning system.

One solution would be to use Hibernate Envers instead, which last time I checked was fully compatible with Hibernate Search. See http://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#envers

Another solution would be to assign the same document ID to all persons that you consider identical. That way, there would only ever be a single person in the index: the last that was modified. See https://docs.jboss.org/hibernate/search/5.11/reference/en-US/html_single/#id-annotation
You may however run into some trouble when fetching the entity matching a given document, since multiple entities would match. That's why using Envers would be a better idea.

Body:
I am trying to modify some code using a hibernate FullTextEntityManager query.  Essentially it works currently but I would like to constrain the results to a subset of records in a table (the most recent of a given type).

So for example the underlying query of data to search might be something along these lines (for demonstration only, I haven't parsed this!)

SELECT name, address
FROM Persons p
WHERE p.name = sq.name
FROM
(SELECT name, max(datemodified)
 FROM Persons
  GROUP BY name) sq

Currently the java code is just selecting from the raw table (essentially this is what the forEntity option does I think)

FullTextEntityManager ftem = Search.getFullTextEntityManager(getEntityManager());

SearchFactory sf= ftem.getSearchFactory();
QueryContextBuilder qcb = sf.buildQueryBuilder();
QueryBuilder qb= qcb.forEntity(entityClass).get();

//processSearchExpression builds a lucene style full text search
org.apache.lucene.search.Query q= processSearchExpression();

FullTextQuery ftq= ftem.createFullTextQuery(q, entityClass);

So essentially I think I've put the essentials in there quite faithfully.  What I can't quite work out is how to add a sub query or something producing similar functionality so that I can just query the most recent records of each type ?

Body:
At the moment the easiest solution to combine ORM queries with Search queries is to add a clause to you search query to filter by id.

FullTextEntityManager ftem = Search.getFullTextEntityManager(getEntityManager());

SearchFactory sf= ftem.getSearchFactory();
QueryBuilder qb= sf.buildQueryBuilder().forEntity(entityClass).get();

BooleanJunction<?> idJunction = qb.bool();
for (Long id : listIdsYouWant()) {
   idJunction.must(qb.match().onField("id").matching(id).createQuery());
}

org.apache.lucene.search.Query q = qb.bool()
   //processSearchExpression builds a lucene style full text search
    .must(processSearchExpression())
    .filteredBy(idJunction.createQuery)
    .createQuery();

FullTextQuery ftq= ftem.createFullTextQuery(q, entityClass);

If that is not an option, you should look for a way to index the data you need to reproduce the SQL query using a full-text query.

In your case, you seem to be using a custom-built versioning system.

One solution would be to use Hibernate Envers instead, which last time I checked was fully compatible with Hibernate Search. See http://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#envers

Another solution would be to assign the same document ID to all persons that you consider identical. That way, there would only ever be a single person in the index: the last that was modified. See https://docs.jboss.org/hibernate/search/5.11/reference/en-US/html_single/#id-annotation
You may however run into some trouble when fetching the entity matching a given document, since multiple entities would match. That's why using Envers would be a better idea.


问:
PHP DateInterval does not return 31th day of a month
Using DateInterval in PHP for 1 day period from 01 to 31 days in a month that have 31th day does not return 31 day in result.

Why this happens?

```<code><?php

$days_list = array();

$days_period = new DatePeriod(
    new DateTime('2019-05-01'),
    new DateInterval('P1D'),
    new DateTime('2019-05-31')
);

foreach ($days_period as $key => $value) {
    $days_list[] = $value->format('D, d M');
}

foreach ($days_list as $day) {
    echo $day.'<br>';
}
</code>```

This display days from 01 May to 30 May of 2019. Why 31 May 2019 is not here?

答: Because DatePeriod does not include the last date specified.</p>

Body:
Using DateInterval in PHP for 1 day period from 01 to 31 days in a month that have 31th day does not return 31 day in result.

Why this happens?

<?php

$days_list = array();

$days_period = new DatePeriod(
    new DateTime('2019-05-01'),
    new DateInterval('P1D'),
    new DateTime('2019-05-31')
);

foreach ($days_period as $key => $value) {
    $days_list[] = $value->format('D, d M');
}

foreach ($days_list as $day) {
    echo $day.'
';
}

This display days from 01 May to 30 May of 2019. Why 31 May 2019 is not here?


问:
Can't share PDF file with WhatsApp or email (Only IOS)
I use react-native-share package

https://www.npmjs.com/package/react-native-share

i try to share base64 in this way:

```<code>import Share from 'react-native-share'
//
const base64File = //base64 file
const pdf = "data:application/pdf;base64," + base64File
const options = { title: 'Share via', url: pdf };
Share.open(options)
</code>```

It works in android but not in IOS, when i try to share tiff file it works in IOS but not pdf

When i try this informs me - this file cannot be shared

答:
I had similar problem in react native share. Then i use react-native-share for sharing my pdf file

```<code>Share.open({
            title: "Pdf file",
            message: "my Text:",
            url: "file:///storage/../../test.pdf",
            subject: "PDF",
        })
</code>```

Hope this will help you

Body:
I use react-native-share package

https://www.npmjs.com/package/react-native-share

i try to share base64 in this way:

import Share from 'react-native-share'
//
const base64File = //base64 file
const pdf = "data:application/pdf;base64," + base64File
const options = { title: 'Share via', url: pdf };
Share.open(options)

It works in android but not in IOS, when i try to share tiff file it works in IOS but not pdf

When i try this informs me - this file cannot be shared

Body:
I had similar problem in react native share. Then i use react-native-share for sharing my pdf file

Share.open({
            title: "Pdf file",
            message: "my Text:",
            url: "file:///storage/../../test.pdf",
            subject: "PDF",
        })

Hope this will help you


问:
Mongoose, update values in array of objects
Is there a way to update values in an object?

```<code>{
  _id: 1,
  name: 'John Smith',
  items: [{
     id: 1,
     name: 'item 1',
     value: 'one'
  },{
     id: 2,
     name: 'item 2',
     value: 'two'
  }]
}
</code>```

Lets say I want to update the name and value items for item where id = 2;

I have tried the following w/ mongoose:

```<code>var update = {name: 'updated item2', value: 'two updated'};
Person.update({'items.id': 2}, {'$set':  {'items.$': update}}, function(err) { ...
</code>```

Problem with this approach is that it updates/sets the entire object, therefore in this case I lose the id field.

Is there a better way in mongoose to set certain values in an array but leave other values alone?

I have also queried for just the Person:

```<code>Person.find({...}, function(err, person) {
  person.items ..... // I might be able to search through all the items here and find item with id 2 then update the values I want and call person.save().
});
</code>```

答:
There is one thing to remember, when you are searching the object in array on the basis of more than one condition then use $elemMatch

```<code>Person.update(
   {
     _id: 5,
     grades: { $elemMatch: { grade: { $lte: 90 }, mean: { $gt: 80 } } }
   },
   { $set: { "grades.$.std" : 6 } }
)
</code>```

here is the docs

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to update values in an object?

{
  _id: 1,
  name: 'John Smith',
  items: [{
     id: 1,
     name: 'item 1',
     value: 'one'
  },{
     id: 2,
     name: 'item 2',
     value: 'two'
  }]
}

Lets say I want to update the name and value items for item where id = 2;

I have tried the following w/ mongoose:

var update = {name: 'updated item2', value: 'two updated'};
Person.update({'items.id': 2}, {'$set':  {'items.$': update}}, function(err) { ...

Problem with this approach is that it updates/sets the entire object, therefore in this case I lose the id field.

Is there a better way in mongoose to set certain values in an array but leave other values alone?

I have also queried for just the Person:

Person.find({...}, function(err, person) {
  person.items ..... // I might be able to search through all the items here and find item with id 2 then update the values I want and call person.save().
});

Body:
There is one thing to remember, when you are searching the object in array on the basis of more than one condition then use $elemMatch

Person.update(
   {
     _id: 5,
     grades: { $elemMatch: { grade: { $lte: 90 }, mean: { $gt: 80 } } }
   },
   { $set: { "grades.$.std" : 6 } }
)

here is the docs


问:
Why does a switch statement on an enum throw 'not comparable to type' error?
While doing a Lynda tutorial on Typescript ( https://www.lynda.com/Visual-Studio-tutorials/TypeScript-types-part-2/543000/565613-4.html#tab ), I hit a snag. The sample code illustrates how switch statements work in TypeScript but the code that seems to work fine for the instructor throws a Type 'x' is not comparable to type 'y' error. Here's the code:

```<code>enum temperature{
    cold,
    hot
}

let temp = temperature.cold;

switch (temp) {
    case temperature.cold:
        console.log("Brrr....");
        break;
    case temperature.hot:
        console.log("Yikes...")
        break;
}
</code>```

I get an error and squiggles under case temperature.hot: saying:

Type 'temperature.hot' is not comparable to type 'temperature.cold'
```

What gives?

答:
Another possible reason could be if you check if the enum variable is not null but this also triggers if enumVal is 0. This only holds true if the enum has the default numeric values (so first item gets the value of 0)

```<code>if (!!enumVal) {
    switch (enumVal) {
         case EnumClass.First // the if clause automatically excludes the first item
</code>```

Body:
While doing a Lynda tutorial on Typescript ( https://www.lynda.com/Visual-Studio-tutorials/TypeScript-types-part-2/543000/565613-4.html#tab ), I hit a snag. The sample code illustrates how switch statements work in TypeScript but the code that seems to work fine for the instructor throws a Type 'x' is not comparable to type 'y' error. Here's the code:

enum temperature{
    cold,
    hot
}

let temp = temperature.cold;

switch (temp) {
    case temperature.cold:
        console.log("Brrr....");
        break;
    case temperature.hot:
        console.log("Yikes...")
        break;
}

I get an error and squiggles under case temperature.hot: saying:

Type 'temperature.hot' is not comparable to type 'temperature.cold'

What gives?

Body:
Another possible reason could be if you check if the enum variable is not null but this also triggers if enumVal is 0. This only holds true if the enum has the default numeric values (so first item gets the value of 0)

if (!!enumVal) {
    switch (enumVal) {
         case EnumClass.First // the if clause automatically excludes the first item


问:
Linq Multiple Orderby Query in one Listing with multiple conditions
```<code>var result = await projectRepo.GetPagedListAsync(x => new ProjectApiModel
            {
                ProjectId = x.Id,
                ProjectKey = x.ProjectKey,
                ProjectName = x.ProjectName,
                ProjectStatus = x.ProjectStatus,
                Tasks = x.Tasks.Where(z => /*z.AgentId == referenceId &&*/ z.Status == true && (z.TaskStatus == null || z.TaskStatus.StatusName != "Closed")).Select(y => new TaskApiModel
                {
                    TaskId = y.Id,
                    TaskName = y.TaskName,
                    ProjectId = y.ProjectId,
                    TaskTypeName = y.TaskType.TypeName,
                    TaskPriority = y.TaskPriorityId == null ? null : new PriorityModel { Name = y.TaskPriority.Name, Color = y.TaskPriority.Color, Id = y.TaskPriority.Id, Scale = y.TaskPriority.Scale },
                    TaskStatus = y.TaskStatusId == null ? null : new StatusModel { StatusName = y.TaskStatus.StatusName, Color = y.TaskStatus.Color, Scale = y.TaskStatus.Scale, StatusId = y.TaskStatus.Id, Status = y.TaskStatus.Status },
                    Deadline=y.EndDateUTC
                }).ToList()
            },orderBy: orders => orders.OrderBy(o => o.ProjectName));
</code>```

This is what I am using for sorting my project list with the project name and its going well. Now I want to change the orderby by conditions as see below.

First want to show all the projects which contain TaskPriority as "urgent"
In any one of the tasks(Every project has tasklist).

rest all projects want to show an ascending order.

If any project name starting with numeric should be in last.

I tried the code

```<code>orderBy: orders => orders.OrderBy(o => o.Tasks.Any(s=>s.TaskPriority.Name.ToLower()== "urgent")).ThenBy(i=>i.ProjectName));
</code>```

答:
I hope I understood your question correctly. The reason why your query didn't work was when ordering booleans, False is ordered first.

What you need to do is Order By Descending in the first condition.

```<code>orders.OrderByDescending(o => o.Tasks.Any(s=>s.TaskPriority.Name.ToLower()== "urgent"))
       .ThenBy(i=>i.ProjectName));
</code>```

For Example, mock your scenario with simpler version of your classes

```<code>public class Project
{
    public long ProjectId{get;set;}
    public string ProjectName{get;set;}
    public IEnumerable<ProjectTask> Task{get;set;}
}

public class ProjectTask
{
    public long TaskId{get;set;}
    public string TaskPriority{get;set;}
}
</code>```

Client Code

```<code>var project1 = new Project
{
    ProjectId=1,
    ProjectName = "abc",
    Task = new []
    {
        new ProjectTask{TaskId=1,TaskPriority="urgent"},
        new ProjectTask{TaskId=1,TaskPriority="moderate"},
    }
};

var project2 = new Project
{
    ProjectId=2,
    ProjectName = "aaa",
    Task = new []
    {
        new ProjectTask{TaskId=1,TaskPriority="moderate"},
        new ProjectTask{TaskId=1,TaskPriority="moderate"},
    }
};

var project3 = new Project
{
    ProjectId=2,
    ProjectName = "abb",
    Task = Enumerable.Empty<ProjectTask>()
};

var project4 = new Project
{
    ProjectId=2,
    ProjectName = "abaa",
    Task = new []
    {
        new ProjectTask{TaskId=1,TaskPriority="moderate"},
        new ProjectTask{TaskId=1,TaskPriority="moderate"},
    }
};

var listOfProjects = new [] {project1,project2,project3,project4};

var r = listOfProjects.OrderByDescending(o => o.Task.Any(s=>s.TaskPriority.ToLower()== "urgent"))
                      .ThenBy(i=>i.ProjectName);
</code>```

Sample Output

Body:
var result = await projectRepo.GetPagedListAsync(x => new ProjectApiModel
            {
                ProjectId = x.Id,
                ProjectKey = x.ProjectKey,
                ProjectName = x.ProjectName,
                ProjectStatus = x.ProjectStatus,
                Tasks = x.Tasks.Where(z => /*z.AgentId == referenceId &&*/ z.Status == true && (z.TaskStatus == null || z.TaskStatus.StatusName != "Closed")).Select(y => new TaskApiModel
                {
                    TaskId = y.Id,
                    TaskName = y.TaskName,
                    ProjectId = y.ProjectId,
                    TaskTypeName = y.TaskType.TypeName,
                    TaskPriority = y.TaskPriorityId == null ? null : new PriorityModel { Name = y.TaskPriority.Name, Color = y.TaskPriority.Color, Id = y.TaskPriority.Id, Scale = y.TaskPriority.Scale },
                    TaskStatus = y.TaskStatusId == null ? null : new StatusModel { StatusName = y.TaskStatus.StatusName, Color = y.TaskStatus.Color, Scale = y.TaskStatus.Scale, StatusId = y.TaskStatus.Id, Status = y.TaskStatus.Status },
                    Deadline=y.EndDateUTC
                }).ToList()
            },orderBy: orders => orders.OrderBy(o => o.ProjectName));

This is what I am using for sorting my project list with the project name and its going well. Now I want to change the orderby by conditions as see below.

First want to show all the projects which contain TaskPriority as "urgent"
In any one of the tasks(Every project has tasklist).

rest all projects want to show an ascending order.

If any project name starting with numeric should be in last.

I tried the code

orderBy: orders => orders.OrderBy(o => o.Tasks.Any(s=>s.TaskPriority.Name.ToLower()== "urgent")).ThenBy(i=>i.ProjectName));

Body:
I hope I understood your question correctly. The reason why your query didn't work was when ordering booleans, False is ordered first.

What you need to do is Order By Descending in the first condition.

orders.OrderByDescending(o => o.Tasks.Any(s=>s.TaskPriority.Name.ToLower()== "urgent"))
       .ThenBy(i=>i.ProjectName));

For Example, mock your scenario with simpler version of your classes

public class Project
{
    public long ProjectId{get;set;}
    public string ProjectName{get;set;}
    public IEnumerable<ProjectTask> Task{get;set;}
}

public class ProjectTask
{
    public long TaskId{get;set;}
    public string TaskPriority{get;set;}
}

Client Code

var project1 = new Project
{
    ProjectId=1,
    ProjectName = "abc",
    Task = new []
    {
        new ProjectTask{TaskId=1,TaskPriority="urgent"},
        new ProjectTask{TaskId=1,TaskPriority="moderate"},
    }
};

var project2 = new Project
{
    ProjectId=2,
    ProjectName = "aaa",
    Task = new []
    {
        new ProjectTask{TaskId=1,TaskPriority="moderate"},
        new ProjectTask{TaskId=1,TaskPriority="moderate"},
    }
};

var project3 = new Project
{
    ProjectId=2,
    ProjectName = "abb",
    Task = Enumerable.Empty<ProjectTask>()
};

var project4 = new Project
{
    ProjectId=2,
    ProjectName = "abaa",
    Task = new []
    {
        new ProjectTask{TaskId=1,TaskPriority="moderate"},
        new ProjectTask{TaskId=1,TaskPriority="moderate"},
    }
};

var listOfProjects = new [] {project1,project2,project3,project4};

var r = listOfProjects.OrderByDescending(o => o.Task.Any(s=>s.TaskPriority.ToLower()== "urgent"))
                      .ThenBy(i=>i.ProjectName);

Sample Output


问:
Icons not visible on Xamarin.UWP
I'm creating Xamarin.Forms application. I'm facing some issue of icons who are not visible on Xamarin.UWP. I've shared my code block which contains icons.
If anyone has any idea regarding this then please let me know. Thanks.</p>

```<code>    <TabbedPage.Children>
        <NavigationPage Title="Neuigkeiten" Icon="Neuigkeiten.png">
            <x:Arguments>
                <views:TestPage/>
            </x:Arguments>
        </NavigationPage>
        <NavigationPage Title="Mitarbeiter" Icon="Mitarbeiter.png">
            <x:Arguments>
                <views:TestPage/>
            </x:Arguments>
        </NavigationPage>
        <NavigationPage Title="Zusammenarbeit" Icon="Zusammenarbeit.png">
            <x:Arguments>
                <views:TestPage/>
            </x:Arguments>
        </NavigationPage>
    </TabbedPage.Children>
</code>```

答:
You have to set TabbedPage.HeaderIconsEnabled attached property to true on UWP to display the icon: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/platform/windows/tabbedpage-icons

Here is the code sample:

```<code><TabbedPage ...
            xmlns:windows="clr-namespace:Xamarin.Forms.PlatformConfiguration.WindowsSpecific;assembly=Xamarin.Forms.Core"
            windows:TabbedPage.HeaderIconsEnabled="true">
    <windows:TabbedPage.HeaderIconsSize>
        <Size>
            <x:Arguments>
                <x:Double>24</x:Double>
                <x:Double>24</x:Double>
            </x:Arguments>
        </Size>
    </windows:TabbedPage.HeaderIconsSize>
    <NavigationPage Title="Neuigkeiten" Icon="Neuigkeiten.png">
        <x:Arguments>
            <views:TestPage/>
        </x:Arguments>
    </NavigationPage>
        ...
</TabbedPage>
</code>```

Title: Icons not visible on Xamarin.UWP

Body:
I'm creating Xamarin.Forms application. I'm facing some issue of icons who are not visible on Xamarin.UWP. I've shared my code block which contains icons.
If anyone has any idea regarding this then please let me know. Thanks.

    <TabbedPage.Children>
        <NavigationPage Title="Neuigkeiten" Icon="Neuigkeiten.png">
            <x:Arguments>
                <views:TestPage/>
            </x:Arguments>
        </NavigationPage>
        <NavigationPage Title="Mitarbeiter" Icon="Mitarbeiter.png">
            <x:Arguments>
                <views:TestPage/>
            </x:Arguments>
        </NavigationPage>
        <NavigationPage Title="Zusammenarbeit" Icon="Zusammenarbeit.png">
            <x:Arguments>
                <views:TestPage/>
            </x:Arguments>
        </NavigationPage>
    </TabbedPage.Children>

Body:
You have to set TabbedPage.HeaderIconsEnabled attached property to true on UWP to display the icon: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/platform/windows/tabbedpage-icons

Here is the code sample:

<TabbedPage ...
            xmlns:windows="clr-namespace:Xamarin.Forms.PlatformConfiguration.WindowsSpecific;assembly=Xamarin.Forms.Core"
            windows:TabbedPage.HeaderIconsEnabled="true">
    <windows:TabbedPage.HeaderIconsSize>
        <Size>
            <x:Arguments>
                <x:Double>24</x:Double>
                <x:Double>24</x:Double>
            </x:Arguments>
        </Size>
    </windows:TabbedPage.HeaderIconsSize>
    <NavigationPage Title="Neuigkeiten" Icon="Neuigkeiten.png">
        <x:Arguments>
            <views:TestPage/>
        </x:Arguments>
    </NavigationPage>
        ...
</TabbedPage>


问:
Is there a SciPy method to autocrop an image, i. e. trim zeros from a 2d `numpy.ndarray`?
For 1d numpy.ndarray there is numpy.trim_zeros. Which method from numpy or scipy can I use to trim zeros for 2d arrays?

```<code>>>> import numpy as np
>>> a = np.array([[0, 0, 0, 0], [4, 1, 2, 0], [0, 3, 6, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
>>> a
array([[0, 0, 0, 0],
       [4, 1, 2, 0],
       [0, 3, 6, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])
</code>```

The result I'd like to get:

```<code>array([[4, 1, 2],
       [0, 3, 6]])
</code>```

答:
I would search for position of leftmost, rightmost, topmost and bottommost nonzeros and then slice that array following way:

```<code>import numpy as np
a = np.array([[0, 0, 0, 0], [4, 1, 2, 0], [0, 3, 6, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
nzero = np.nonzero(a)
top,bottom = np.min(nzero[0]),np.max(nzero[1])
left,right = np.min(nzero[1]),np.max(nzero[1])
out = a[top:bottom+1,left:right+1] # +1 as second argument is exclusive
print(out)
</code>```

Output:

```<code>[[4 1 2]
 [0 3 6]]
</code>```

Note that this method might be easily adopted also to 3D arrays by adding nearest and farthest, which would be respectively np.min and np.max of nzero[2]

Body:
For 1d numpy.ndarray there is numpy.trim_zeros. Which method from numpy or scipy can I use to trim zeros for 2d arrays?

>>> import numpy as np
>>> a = np.array([[0, 0, 0, 0], [4, 1, 2, 0], [0, 3, 6, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
>>> a
array([[0, 0, 0, 0],
       [4, 1, 2, 0],
       [0, 3, 6, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])

The result I'd like to get:

array([[4, 1, 2],
       [0, 3, 6]])

Body:
I would search for position of leftmost, rightmost, topmost and bottommost nonzeros and then slice that array following way:

import numpy as np
a = np.array([[0, 0, 0, 0], [4, 1, 2, 0], [0, 3, 6, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
nzero = np.nonzero(a)
top,bottom = np.min(nzero[0]),np.max(nzero[1])
left,right = np.min(nzero[1]),np.max(nzero[1])
out = a[top:bottom+1,left:right+1] # +1 as second argument is exclusive
print(out)

Output:

[[4 1 2]
 [0 3 6]]

Note that this method might be easily adopted also to 3D arrays by adding nearest and farthest, which would be respectively np.min and np.max of nzero[2]


问:
Token Mismatch Exception in VerifyCsrfToken.php
I am getting this error on submit button click.

I already tried to put following code in form tag :

```<code><input type="hidden" name="_token" value="{{ csrf_token() }}">
</code>```

session.php

```<code><div class="title">
    Laravel Session Tutorial

   <form action="about.php" method="post">

       {{ csrf_field() }}
       <input type="text" name="name" value="">
       <button type="submit" name="button">Enter</button>
   </form>
</div>
</code>```

I am just passing input string to another web page. For example, if I input name in textbox. In return, it gives me that input name in another web page like  "Hello , (name)".

答:
You have to write

@csrf or {{ csrf_field() }}

instead of

<input type="hidden" name="_token" value="{{ csrf_token() }}">
```

<p>And then run following.</p>

<pre class="lang-php prettyprint-override"><code>php artisan make:auth
php artisan optimize
</code>```

Body:
I am getting this error on submit button click.

I already tried to put following code in form tag :

<input type="hidden" name="_token" value="{{ csrf_token() }}">

session.php

    Laravel Session Tutorial

   <form action="about.php" method="post">

       {{ csrf_field() }}
       <input type="text" name="name" value="">
       <button type="submit" name="button">Enter</button>
   </form>

I am just passing input string to another web page. For example, if I input name in textbox. In return, it gives me that input name in another web page like  "Hello , (name)".

Body:
You have to write

@csrf or {{ csrf_field() }}

instead of

<input type="hidden" name="_token" value="{{ csrf_token() }}">

And then run following.

php artisan make:auth
php artisan optimize


问:
Python compare list of dictionaries with another dictionary in loop
I am working on a python code to update list of dictionaries if input exists in list of dictionaries. If input doesn't exist in list of dictionaries it should print "value doesn't exist in entire list" or do some other operation. Below is the code I have written

```<code>a = [{'main_color': 'red', 'second_color': 'blue'},
 {'main_color': 'yellow', 'second_color': 'green'},
 {'main_color': 'blue', 'second_color': 'blue1'}]

conType = input('Enter main color: ')
color=input('Enter secondary color :')

conType1= input('Enter another main color: ')
color1=input('Enter another secondary color: ')

valueDict={}

if conType:
    valueDict[conType]=color

if conType1:
    valueDict[conType1]=color1

print(valueDict)

for d in a:

    for i,j in valueDict.items():

        if d['main_color'] == i:

            print('matched')

            d['second_color'] = j
            break
    else:

        print('no value')

print(a)
</code>```

Below is the output When I tried to execute above code

```<code>Enter main color: red

Enter secondary color :black

Enter another main color: yellow

Enter another secondary color: white

{'red': 'black', 'yellow': 'white'}

matched

matched

no value

[{'main_color': 'red', 'second_color': 'black'}, {'main_color': 'yellow', 'second_color': 'white'}, {'main_color': 'blue', 'second_color': 'blue1'}]
</code>```

Issue here is 'no value' is getting printed.
In my use case no value shouldn't be printed at all.

I have been through Searching array reports "not found" even though it's found and https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

I am not sure why "no value" is getting printed. I am looking for a way to avoid executing else block if all inputs are present in list of dictionaries.
Please help.

答:
Did I throw the baby out with the bathwater?

```<code>a = {'red': 'blue', 'yellow': 'green', 'blue': 'blue1'}
b = {'red': 'black', 'yellow': 'white'}

for i, j in b.items():
    if i in a:
        a[i] = j
print(a)
</code>```

In Python 3.5 or greater this code (for loop) can be reduced to:

a = {**a, **b}

Body:
I am working on a python code to update list of dictionaries if input exists in list of dictionaries. If input doesn't exist in list of dictionaries it should print "value doesn't exist in entire list" or do some other operation. Below is the code I have written

a = [{'main_color': 'red', 'second_color': 'blue'},
 {'main_color': 'yellow', 'second_color': 'green'},
 {'main_color': 'blue', 'second_color': 'blue1'}]

conType = input('Enter main color: ')
color=input('Enter secondary color :')

conType1= input('Enter another main color: ')
color1=input('Enter another secondary color: ')

valueDict={}

if conType:
    valueDict[conType]=color

if conType1:
    valueDict[conType1]=color1

print(valueDict)

for d in a:

    for i,j in valueDict.items():

        if d['main_color'] == i:

            print('matched')

            d['second_color'] = j
            break
    else:

        print('no value')

print(a)

Below is the output When I tried to execute above code

Enter main color: red

Enter secondary color :black

Enter another main color: yellow

Enter another secondary color: white

{'red': 'black', 'yellow': 'white'}

matched

matched

no value

[{'main_color': 'red', 'second_color': 'black'}, {'main_color': 'yellow', 'second_color': 'white'}, {'main_color': 'blue', 'second_color': 'blue1'}]

Issue here is 'no value' is getting printed.
In my use case no value shouldn't be printed at all.

I have been through Searching array reports "not found" even though it's found and https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

I am not sure why "no value" is getting printed. I am looking for a way to avoid executing else block if all inputs are present in list of dictionaries.
Please help.

Body:
Did I throw the baby out with the bathwater?

a = {'red': 'blue', 'yellow': 'green', 'blue': 'blue1'}
b = {'red': 'black', 'yellow': 'white'}

for i, j in b.items():
    if i in a:
        a[i] = j
print(a)

In Python 3.5 or greater this code (for loop) can be reduced to:

a = {**a, **b}


问:
Question Qtip through iFrame - With JQUERY LIVE
I'd like to find a fay to use Qtip in an iFrame on my page. I found a way to use QTIP on an iframe, but not with JQUERY LIVE....

qTip through an iFrame: http://craigsworks.com/projects/forums/thread-question-qtip-through-iframe

Any ideas on how to apply JQUERY Live to that?

My current code:

```<code>$('iframe').load(function(){
  $(this).qtip(
  {
    content: 'My first Qtip! Look mom!',
    show: {
      when : {
         target: $(this).contents().find('.tipoff') // Element within the iframe
      }
    },
    hide: {
      when : {
         target: $(this).contents().find('.tipoff') // Element within the iframe
      }
    }
  });
});
</code>```

Thanks

答:
I know this is nearly a year old but I was just looking to do something similar and thought I'd post my findings. I'm not completely sure what you were after and it might be different to what I have, but I am assuming you wanted to apply a qTip to some elements in a dynamically loaded  as I did.

It doesn't address the live() problem, even though according to Adding a row to a table in an iFrame with jQuery (live?) it should work, but here is what I ended up with:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Title</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style type="text/css">
        iframe {
            border:1px dashed red;
        }
    </style>
    <link rel="stylesheet" type="text/css" href="jquery.qtip.min.css"/>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script src="jquery.qtip.min.js"></script>
    <script type="text/javascript">

        $(function() {
            $('p a.tip').qtip({
                content: 'foo'
            });

            $('iframe').load(function() {
                var position = $(this).position();
                var top = position.top;
                var left = position.left;
                $(this.contentDocument).find('p a.tip').qtip({
                    content: 'bar',
                    position: { adjust: { x:left, y:top } }
                });
            });

            $('#click').click(function(){
                $('iframe').attr('src', 'test.html');
                return false;
            });
        });

    </script>
</head>
<body>
    <p><a class="tip" href="#">Lorem ipsum dolor</a> sit amet, consectetur adipiscing elit.</a></p>
    <iframe></iframe>
    <p><a href="#" id="click">Load iFrame</a></p>
</body>
</html>
</code>```

where test.html contains:

```<code><p><a class="tip" href="#">Duis massa metus</a>, convallis vitae, mollis vel, feugiat vitae, nunc.</p>
</code>```

and you can get jquery.qtip.min.css and jquery.qtip.min.js from qTip2.

Edit: Make sure the page is loaded in your browser from a web server (not just loaded as a local file) to avoid the Same origin policy.

Hope this is useful to someone! :-)

ContentLicense: CC BY-SA 2.5

Body:
I'd like to find a fay to use Qtip in an iFrame on my page. I found a way to use QTIP on an iframe, but not with JQUERY LIVE....

qTip through an iFrame: http://craigsworks.com/projects/forums/thread-question-qtip-through-iframe

Any ideas on how to apply JQUERY Live to that?

My current code:

$('iframe').load(function(){
  $(this).qtip(
  {
    content: 'My first Qtip! Look mom!',
    show: {
      when : {
         target: $(this).contents().find('.tipoff') // Element within the iframe
      }
    },
    hide: {
      when : {
         target: $(this).contents().find('.tipoff') // Element within the iframe
      }
    }
  });
});

Thanks

Body:
I know this is nearly a year old but I was just looking to do something similar and thought I'd post my findings. I'm not completely sure what you were after and it might be different to what I have, but I am assuming you wanted to apply a qTip to some elements in a dynamically loaded <iframe> as I did.

It doesn't address the live() problem, even though according to Adding a row to a table in an iFrame with jQuery (live?) it should work, but here is what I ended up with:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Title</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style type="text/css">
        iframe {
            border:1px dashed red;
        }
    </style>
    <link rel="stylesheet" type="text/css" href="jquery.qtip.min.css"/>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script src="jquery.qtip.min.js"></script>
    <script type="text/javascript">

        $(function() {
            $('p a.tip').qtip({
                content: 'foo'
            });

            $('iframe').load(function() {
                var position = $(this).position();
                var top = position.top;
                var left = position.left;
                $(this.contentDocument).find('p a.tip').qtip({
                    content: 'bar',
                    position: { adjust: { x:left, y:top } }
                });
            });

            $('#click').click(function(){
                $('iframe').attr('src', 'test.html');
                return false;
            });
        });

    </script>
</head>
<body>
    <p><a class="tip" href="#">Lorem ipsum dolor</a> sit amet, consectetur adipiscing elit.</a></p>
    <iframe></iframe>
    <p><a href="#" id="click">Load iFrame</a></p>
</body>
</html>

where test.html contains:

<p><a class="tip" href="#">Duis massa metus</a>, convallis vitae, mollis vel, feugiat vitae, nunc.</p>

and you can get jquery.qtip.min.css and jquery.qtip.min.js from qTip2.

Edit: Make sure the page is loaded in your browser from a web server (not just loaded as a local file) to avoid the Same origin policy.

Hope this is useful to someone! :-)


问:
How to get axios error response INTO the redux saga catch method
With axios the code is:

```<code>export const createBlaBla = (payload) => {
  return axios.post('/some-url', payload)
    .then(response => response)
    .catch(err => err);
}
</code>```

And then I'm using this with redux-saga like this:

```<code>function* createBlaBlaFlow(action) {
  try {
    const response = yield call(createBlaBla, action.payload);
    if (response) {
      yield put({
        type: CREATE_BLA_BLA_SUCCESS
      });
    }
  } catch (err) {
    // I need the error data here ..
    yield put({
      type: CREATE_BLA_BLA_FAILURE,
      payload: 'failed to create bla-bla'
    });
  }
}
</code>```

In case of some error on the backend - like invalid data send to the backend - it returns a 400 response with some data:

```<code>{
  "code":"ERR-1000",
  "message":"Validation failed because ..."
  "method":"POST",
  "errorDetails":"..."
}
</code>```

But I don't receive this useful data in the catch statement inside the saga. I can console.log() the data in the axios catch statement, also I can get it inside the try statement in the saga, but it never arrives in the catch.

Probably I need to do something else? ... Or the server shouldn't return 400 response in this case?

答:
In your API call you can do the following:

const someAPICall = (action) => {
  return axios.put(`some/path/to/api`, data, {
    withCredentials: true,
    validateStatus: (status) => {
      return (status == 200 || status === 403);
    }
  });
};
```

<p>Please note the <code>validateStatus()</code> part - this way when axios will encounter <code>200</code> or <code>403</code> response, it will not throw Error and you will be able to process the response after</p>

<pre class="lang-js prettyprint-override"><code>const response = yield call(someAPICall, action);
if (response.status === 200) {
  // Proceed further
} else if (response.status === 403) {
  // Inform user about error
} else {
  ...
}
</code>```

Body:
With axios the code is:

export const createBlaBla = (payload) => {
  return axios.post('/some-url', payload)
    .then(response => response)
    .catch(err => err);
}

And then I'm using this with redux-saga like this:

function* createBlaBlaFlow(action) {
  try {
    const response = yield call(createBlaBla, action.payload);
    if (response) {
      yield put({
        type: CREATE_BLA_BLA_SUCCESS
      });
    }
  } catch (err) {
    // I need the error data here ..
    yield put({
      type: CREATE_BLA_BLA_FAILURE,
      payload: 'failed to create bla-bla'
    });
  }
}

In case of some error on the backend - like invalid data send to the backend - it returns a 400 response with some data:

{
  "code":"ERR-1000",
  "message":"Validation failed because ..."
  "method":"POST",
  "errorDetails":"..."
}

But I don't receive this useful data in the catch statement inside the saga. I can console.log() the data in the axios catch statement, also I can get it inside the try statement in the saga, but it never arrives in the catch.

Probably I need to do something else? ... Or the server shouldn't return 400 response in this case?

Body:
In your API call you can do the following:

const someAPICall = (action) => {
  return axios.put(`some/path/to/api`, data, {
    withCredentials: true,
    validateStatus: (status) => {
      return (status == 200 || status === 403);
    }
  });
};

Please note the validateStatus() part - this way when axios will encounter 200 or 403 response, it will not throw Error and you will be able to process the response after

const response = yield call(someAPICall, action);
if (response.status === 200) {
  // Proceed further
} else if (response.status === 403) {
  // Inform user about error
} else {
  ...
}


问:
Lombok SLF4J impl inheritance issues
I'm facing an issue with Lombok in my multimodule maven project. I have two classes :

```<code>@Slf4j
public class Parent {}

@Slf4j
public class Child extends Parent {
    public void m() {
        log.debug("hello");
    }
}
</code>```

There is also a parent maven project in which the lombok dependency is defined. And a child maven project in which I define the parent project as maven parent.

When I use generated log instance in Child class, compilation error occurs :

```<code>[ERROR] log has private access in <Child class>
</code>```

I could resolved the issue in two ways:

I create myself the private field named "log" by hand.

I define the Lombok dependency in the child maven project.

Why so? Any workaround / best way to define the lombok dependency ?

Thanks for your help.

Using :

lombok 1.16.18

JDK 1.8

Maven 3.5.3

答: I found why, the Lombok dependency in the dependencies tree of the child project was in provided scope. I added Lombok in dependency and the field was correctly generated then.</p>

Title: Lombok SLF4J impl inheritance issues

Body:
I'm facing an issue with Lombok in my multimodule maven project. I have two classes :

@Slf4j
public class Parent {}

@Slf4j
public class Child extends Parent {
    public void m() {
        log.debug("hello");
    }
}

There is also a parent maven project in which the lombok dependency is defined. And a child maven project in which I define the parent project as maven parent.

When I use generated log instance in Child class, compilation error occurs :

[ERROR] log has private access in <Child class>

I could resolved the issue in two ways:

I create myself the private field named "log" by hand.

I define the Lombok dependency in the child maven project.

Why so? Any workaround / best way to define the lombok dependency ?

Thanks for your help.

Using :

lombok 1.16.18

JDK 1.8

Maven 3.5.3


问:
How to check view scrollable position when scrollview scroll
We have implemented sticky out stream Ad functionality by using text view. When text view scroll we have show added one view in mid of text view text. And when textview scroll and added view is going out from view. then we have show another view with same content of added view. It works perfect. But now my new requirement is when user scroll the text view and added view appears. Then we need to show the second added view according to view appearance. like added view is only 50% appear on screen then we need to show the second view. Now my problem is how to detect the view appearance according to scroll position. for hide or show view.
Thanks in Advance</p>

答:
You have to use scrollViewDidScroll delegate method for that.
You can try with following:

```<code>func scrollViewDidScroll(_ scrollView: UIScrollView) {

    // Table View Scroll Image
    let viewContentOffset = textview.contentOffset
    let viewContentSize = textview.contentSize
    let viewBounds = textview.bounds.size

    // Use Alpha value to manipulation
    let bottomOffset = scrollView.contentSize.height - scrollView.bounds.size.height
    let alpha = (scrollView.contentOffset.y / bottomOffset) * 2
}
</code>```

Add Image to TextView using NSAttributtedString:

```<code>textView.text = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda."
let image = UIImage(named: "sampleImage.png");
let attachment = NSTextAttachment()
attachment.image = image
let attString = NSAttributedString(attachment: attachment)
textView.textStorage.insert(attString, at: textView.text.count/2)
</code>```

Body:
You have to use scrollViewDidScroll delegate method for that.
You can try with following:

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    // Table View Scroll Image
    let viewContentOffset = textview.contentOffset
    let viewContentSize = textview.contentSize
    let viewBounds = textview.bounds.size

    // Use Alpha value to manipulation
    let bottomOffset = scrollView.contentSize.height - scrollView.bounds.size.height
    let alpha = (scrollView.contentOffset.y / bottomOffset) * 2
}

Add Image to TextView using NSAttributtedString:

textView.text = "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda."
let image = UIImage(named: "sampleImage.png");
let attachment = NSTextAttachment()
attachment.image = image
let attString = NSAttributedString(attachment: attachment)
textView.textStorage.insert(attString, at: textView.text.count/2)


问:
How to delete document from index by it's path in Whoosh
First i add documents to index like this:

```<code>writer.add_document(title=doc_path.split(os.sep)[-1], path=doc_path, content=text, textdata=text)
</code>```

And then i just need to delete one of them completely from index by it's path. Documentation says there are few no low level method to do this:

delete_by_term(fieldname, termtext)

Deletes any documents where the given (indexed) field contains the
  given term. This is mostly useful for ID or KEYWORD fields.

delete_by_query(query)

Deletes any documents that match the given query.

but i can't find suitable and very convenient method for me where i can specify path of the document and just remove it. There is some low level method where i can specify internal doc_number, which i supposed to get somehow.
Can anyone give me advice how it's better to accomplish this task?

答:
```<code>ix = open_dir('/my_index_dir_path/..')
writer = ix.writer()
writer.delete_by_term('path', doc_path)
writer.commit()
</code>```

delete_by_term

method does exactly what i need. Note, that first argument is a text string 'path', and them goes the actual path. My mistake was to put an actual path instead of attribute name.

Body:
First i add documents to index like this:

writer.add_document(title=doc_path.split(os.sep)[-1], path=doc_path, content=text, textdata=text)

And then i just need to delete one of them completely from index by it's path. Documentation says there are few no low level method to do this:

delete_by_term(fieldname, termtext)

Deletes any documents where the given (indexed) field contains the
  given term. This is mostly useful for ID or KEYWORD fields.

delete_by_query(query)

Deletes any documents that match the given query.

but i can't find suitable and very convenient method for me where i can specify path of the document and just remove it. There is some low level method where i can specify internal doc_number, which i supposed to get somehow.
Can anyone give me advice how it's better to accomplish this task?

Body:
ix = open_dir('/my_index_dir_path/..')
writer = ix.writer()
writer.delete_by_term('path', doc_path)
writer.commit()

delete_by_term

method does exactly what i need. Note, that first argument is a text string 'path', and them goes the actual path. My mistake was to put an actual path instead of attribute name.


答:
You have to add 1 sec to end date

```<code>$days_list   = [];
$days_period = new DatePeriod(
    new DateTime('2019-05-01'),
    new DateInterval('P1D'),
    (new DateTime('2019-05-31'))->modify("+1 second")
);
foreach ($days_period as $key => $value) {
    $days_list[] = $value->format('D, d M');
}
foreach ($days_list as $day) {
    echo $day . '<br>';
}
</code>```

EDIT

As per your requirement, I made changes in above code, please see inline doc for explanation

```<code>$temp = '';
// I am considering snippet for 1 month
foreach ($days_period as $key => $value) {
    // check if empty assign temp as current month's value
    if (empty($temp)) {
        $temp = $value->format("M");
    }
    // if any changes in iterator not matched with current month then break
    if ($temp != $value->format("M")) {
        break;
    }
    $days_list[] = $value->format('D, d M');
}
foreach ($days_list as $day) {
    echo $day . '<br>';
}
</code>```

Title: PHP DateInterval does not return 31th day of a month

Body:
Using DateInterval in PHP for 1 day period from 01 to 31 days in a month that have 31th day does not return 31 day in result.

Why this happens?

<?php

$days_list = array();

$days_period = new DatePeriod(
    new DateTime('2019-05-01'),
    new DateInterval('P1D'),
    new DateTime('2019-05-31')
);

foreach ($days_period as $key => $value) {
    $days_list[] = $value->format('D, d M');
}

foreach ($days_list as $day) {
    echo $day.'
';
}

This display days from 01 May to 30 May of 2019. Why 31 May 2019 is not here?

Body:
You have to add 1 sec to end date

$days_list   = [];
$days_period = new DatePeriod(
    new DateTime('2019-05-01'),
    new DateInterval('P1D'),
    (new DateTime('2019-05-31'))->modify("+1 second")
);
foreach ($days_period as $key => $value) {
    $days_list[] = $value->format('D, d M');
}
foreach ($days_list as $day) {
    echo $day . '<br>';
}

EDIT

As per your requirement, I made changes in above code, please see inline doc for explanation

$temp = '';
// I am considering snippet for 1 month
foreach ($days_period as $key => $value) {
    // check if empty assign temp as current month's value
    if (empty($temp)) {
        $temp = $value->format("M");
    }
    // if any changes in iterator not matched with current month then break
    if ($temp != $value->format("M")) {
        break;
    }
    $days_list[] = $value->format('D, d M');
}
foreach ($days_list as $day) {
    echo $day . '<br>';
}


问:
How to show the set of remaining items in array when next button is clicked?
I have 12 cameras in total, when i select 4 cameras option from a drop down box it show only 4 cameras. Now when i click on the next button i need to display the remaining cameras in the selected layout format. How will it work?

```<code><button class="butn" ng-click="previous_view()">Previous</button>
    <button class="butn" id="next_button" ng-click="next_view()">Next</button>
    <label class="head">Layout :</label>
    <select class="layout_lst" ng-model="size" ng-change="setSize()">
        <option ng-repeat="priority in sizeLst" value="{{priority.type}}">{{priority.name}} />
    </select>
    <div layout-wrap flex-wrap>
        <iframe ng-repeat="item in camerasList | limitTo : size" ng-class="size" oncontextmenu="ShowContextMenu()" src={{item.url}} width="337" height="177" allow=loop />
    </div>
</button>
</code>```

//js code

```<code> $scope.sizeLst = [
 {
     "name": "2x2",
     "type": "fourscreen"
 }, {
      "name": "3x2",
      "type": "sixscreen"
 }, {
      "name": "4x2",
      "type": "eightscreen"
 }, {
      "name": "3x3",
      "type": "ninescreen"
 }, {
      "name": "3x4",
      "type": "twelvescreen"
 }
 ];

 $scope.camerasList = [
 {
     "name": "camera 1",
     "url": "assets/Nature Beautiful short video 720p HD.mp4",
     "type": "2screen"
  }, {
     "name": "camera 2",
     "url": "assets/videoplayback.mp4",
     "type": "2screen"
   }, {
      "name": "camera 3",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "4screen"
   }, {
      "name": "camera 4",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "4screen"
   }, {
      "name": "camera 5",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "6screen",
   }, {
      "name": "camera 6",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "6screen"
   }, {
      "name": "camera 7",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "8screen"
   }, {
      "name": "camera 8",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "8screen"
   }, {
      "name": "camera 9",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "8screen"
   }, {
      "name": "camera 10",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "8screen"
   }, {
      "name": "camera 11",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "8screen"
   }, {
      "name": "camera 12",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "8screen"
   }

    let videoLst = $scope.camerasList;
    console.log(videoLst);

    $scope.setSize = () => {
        // if ($scope.size == "1x2") {
        //     $scope.camerasList = videoLst.slice(0, 2);
        //     console.log($scope.camerasList)
        // }
        if ($scope.size === "fourscreen") {
            $scope.camerasList = videoLst.slice(0, 4);
            console.log($scope.camerasList)
        }
        if ($scope.size === "sixscreen") {
            $scope.camerasList = videoLst.slice(0, 6);
            console.log($scope.camerasList)
        }
        if ($scope.size === "eightscreen") {
            $scope.camerasList = videoLst.slice(0, 8);
            console.log($scope.camerasList)
        }
        if ($scope.size === "ninescreen") {
            $scope.camerasList = videoLst.slice(0, 9);
            console.log($scope.camerasList)
        }
        if ($scope.size === "twelvescreen") {
            $scope.camerasList = videoLst.slice(0, 12);
            console.log($scope.camerasList)
        }
    }
</code>```

when next button is clicked i need to display the next set of cameras from the array in consider with the layout. Please me with the code.

答:
You can use .slice(start, stop) in your next_view()

When you show the first 4 .slice(0, 4) you are getting index 0, 1, 2, 3 ( first 4 items )

If you want to get the next set you will do .slice(4, 8) then .slice(8, 12)

You can do this using an index.

first time click on next_view()

```<code> index = 1;
 totalShow = 4;
 start = totalShow * index;
 end = start + totalShow
 .slice(start, end)
</code>```

Then Increase the index by 1 every-time you go to the next set and reset it when changing view.

Here's some more info on slice https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Body:
I have 12 cameras in total, when i select 4 cameras option from a drop down box it show only 4 cameras. Now when i click on the next button i need to display the remaining cameras in the selected layout format. How will it work?

<button class="butn" ng-click="previous_view()">Previous</button>
    <button class="butn" id="next_button" ng-click="next_view()">Next</button>
    Layout :
    <select class="layout_lst" ng-model="size" ng-change="setSize()">
        <option ng-repeat="priority in sizeLst" value="{{priority.type}}">{{priority.name}} />
    </select>

</button>

//js code

 $scope.sizeLst = [
 {
     "name": "2x2",
     "type": "fourscreen"
 }, {
      "name": "3x2",
      "type": "sixscreen"
 }, {
      "name": "4x2",
      "type": "eightscreen"
 }, {
      "name": "3x3",
      "type": "ninescreen"
 }, {
      "name": "3x4",
      "type": "twelvescreen"
 }
 ];

 $scope.camerasList = [
 {
     "name": "camera 1",
     "url": "assets/Nature Beautiful short video 720p HD.mp4",
     "type": "2screen"
  }, {
     "name": "camera 2",
     "url": "assets/videoplayback.mp4",
     "type": "2screen"
   }, {
      "name": "camera 3",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "4screen"
   }, {
      "name": "camera 4",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "4screen"
   }, {
      "name": "camera 5",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "6screen",
   }, {
      "name": "camera 6",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "6screen"
   }, {
      "name": "camera 7",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "8screen"
   }, {
      "name": "camera 8",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "8screen"
   }, {
      "name": "camera 9",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "8screen"
   }, {
      "name": "camera 10",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "8screen"
   }, {
      "name": "camera 11",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "8screen"
   }, {
      "name": "camera 12",
      "url": "assets/Nature Beautiful short video 720p HD.mp4",
      "type": "8screen"
   }

    let videoLst = $scope.camerasList;
    console.log(videoLst);

    $scope.setSize = () => {
        // if ($scope.size == "1x2") {
        //     $scope.camerasList = videoLst.slice(0, 2);
        //     console.log($scope.camerasList)
        // }
        if ($scope.size === "fourscreen") {
            $scope.camerasList = videoLst.slice(0, 4);
            console.log($scope.camerasList)
        }
        if ($scope.size === "sixscreen") {
            $scope.camerasList = videoLst.slice(0, 6);
            console.log($scope.camerasList)
        }
        if ($scope.size === "eightscreen") {
            $scope.camerasList = videoLst.slice(0, 8);
            console.log($scope.camerasList)
        }
        if ($scope.size === "ninescreen") {
            $scope.camerasList = videoLst.slice(0, 9);
            console.log($scope.camerasList)
        }
        if ($scope.size === "twelvescreen") {
            $scope.camerasList = videoLst.slice(0, 12);
            console.log($scope.camerasList)
        }
    }

when next button is clicked i need to display the next set of cameras from the array in consider with the layout. Please me with the code.

Body:
You can use .slice(start, stop) in your next_view()

When you show the first 4 .slice(0, 4) you are getting index 0, 1, 2, 3 ( first 4 items )

If you want to get the next set you will do .slice(4, 8) then .slice(8, 12)

You can do this using an index.

first time click on next_view()

 index = 1;
 totalShow = 4;
 start = totalShow * index;
 end = start + totalShow
 .slice(start, end)

Then Increase the index by 1 every-time you go to the next set and reset it when changing view.

Here's some more info on slice https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice


问:
Need some help positioning a header and sub heading
heres my code: https://codepen.io/anon/pen/dEqJLr#anon-login
heres what I'm trying to do: https://imgur.com/a/NxvyHAC
basically I want the sub header ("helpthistext") to be above my header and I'm not sure how to achieve this..

body,
html {
  font-family: 'Montserrat';
  margin: 0;
  height: 100%;
}

body {
  background-color: red;
}

.newtest {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 75%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="newtest">
  <span class="sub-head">helpthistext</span>
  <h1 class="main-head">title one & another one</h1>
</div></code>```

答:
flex-direction:column is what you are after

body,
html {
  font-family: 'Montserrat';
  margin: 0;
  height: 100%;
}

body {
  background-color: red;
text-align:Center;
}

.newtest {
  display: inline-flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  height: 75%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="newtest">
  <span class="sub-head">helpthistext</span>
  <h1 class="main-head">title one & another one</h1>
</div></code>```

Body:
heres my code: https://codepen.io/anon/pen/dEqJLr#anon-login
heres what I'm trying to do: https://imgur.com/a/NxvyHAC
basically I want the sub header ("helpthistext") to be above my header and I'm not sure how to achieve this..

body,
html {
  font-family: 'Montserrat';
  margin: 0;
  height: 100%;
}

body {
  background-color: red;
}

.newtest {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 75%;
}

  helpthistext

title one & another one

Body:
flex-direction:column is what you are after

body,
html {
  font-family: 'Montserrat';
  margin: 0;
  height: 100%;
}

body {
  background-color: red;
text-align:Center;
}

.newtest {
  display: inline-flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  height: 75%;
}

<div class="newtest">
  <span class="sub-head">helpthistext</span>
  <h1 class="main-head">title one & another one</h1>
</div>


问:
FileStream to save file then immediately unlock in .NET?
I have this code that saves a pdf file.

```<code>FileStream fs = new FileStream(SaveLocation, FileMode.Create);
fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);
fs.Flush();
fs.Close();
</code>```

It works fine. However sometimes it does not release the lock right away and that causes file locking exceptions with functions run after this one run.

Is there a ideal way to release the file lock right after the fs.Close()

答:
Just had the same issue when I closed a FileStream and opened the file immediately in another class. The using statement was not a solution since the FileStream had been created at another place and stored in a list. Clearing the list was not enough.

It looks like the stream needs to be freed by the garbage collector before the file can be reused. If the time between closing and opening is too short, you can use

```<code>GC.Collect();
</code>```

right after you closed the stream. This worked for me.

I guess the solutions of Ian Mercer to put the thread to sleep might have the same effect, giving the GC time to free the resources.

Body:
I have this code that saves a pdf file.

FileStream fs = new FileStream(SaveLocation, FileMode.Create);
fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);
fs.Flush();
fs.Close();

It works fine. However sometimes it does not release the lock right away and that causes file locking exceptions with functions run after this one run.

Is there a ideal way to release the file lock right after the fs.Close()

Body:
Just had the same issue when I closed a FileStream and opened the file immediately in another class. The using statement was not a solution since the FileStream had been created at another place and stored in a list. Clearing the list was not enough.

It looks like the stream needs to be freed by the garbage collector before the file can be reused. If the time between closing and opening is too short, you can use

GC.Collect();

right after you closed the stream. This worked for me.

I guess the solutions of Ian Mercer to put the thread to sleep might have the same effect, giving the GC time to free the resources.


问:
How to check if a List<List<int>> contains a List<int>
I have a List<List<int>> in which I would like to insert a new List<int>. I would like to check before adding the new List<int> if it already exists in the List<List<int>>.

For e.g.

```<code>List<List<int>> MasterList = new List<List<int>>();
List<int> childList = new List<int>();
</code>```

I have already tried

```<code>MaterList.Contains, MasterList.Any
</code>```

but nothing is helping

e.g.

```<code>MasterList(1)=1,2,3
MasterList(2)=4,5
</code>```

but when I see 1,2,3 or 4,5 is coming again then do not want to enter it as they are already there somewhere in MasterList

答:
You could use SequenceEqual of Linq</p>

```<code>if (MasterList.Any(c => c.SequenceEqual(childList)))
{
    //contains

}
</code>```

Body:
I have a List<List<int>> in which I would like to insert a new List<int>. I would like to check before adding the new List<int> if it already exists in the List<List<int>>.

For e.g.

List<List<int>> MasterList = new List<List<int>>();
List<int> childList = new List<int>();

I have already tried

MaterList.Contains, MasterList.Any

but nothing is helping

e.g.

MasterList(1)=1,2,3
MasterList(2)=4,5

but when I see 1,2,3 or 4,5 is coming again then do not want to enter it as they are already there somewhere in MasterList

Body:
You could use SequenceEqual of Linq

if (MasterList.Any(c => c.SequenceEqual(childList)))
{
    //contains

}


问:
How to get the result of a js function called with ';
             echo $timer;
         }
```

<p>And my js function :</p>

```function timer(){
          var running = false;
          var time_in_minutes = 0.3;
          var current_time = Date.parse(new Date());
          var deadline = new Date(current_time + time_in_minutes*60*1000);
          function run_clock(id,endtime){
            var clock = document.getElementById(id);
            function update_clock(){
                          function time_remaining(endtime){
                             var t = Date.parse(endtime) - Date.parse(new Date());
                             var seconds = Math.floor( (t/1000) % 60 );
                             var minutes = Math.floor( (t/1000/60) % 60 );
                             var hours = Math.floor( (t/(1000*60*60)) % 24 );
                             var days = Math.floor( t/(1000*60*60*24) );
                             return {'total':t, 'days':days, 'hours':hours, 'minutes':minutes, 'seconds':seconds};
                          }
        var t = time_remaining(endtime);
        clock.innerHTML = 'minutes: '+t.minutes+'
seconds: '+t.seconds;
        if(t.total<=0){
                  clearInterval(timeinterval);
                  clock.innerHTML = 'Temps écoulé';
                  running = true;
                 }
    }
    update_clock(); // run function once at first to avoid delay
    var timeinterval = setInterval(update_clock,1000);
}
          run_clock('clockdiv',deadline);
          return running;
}
```

答:
Try below code

```<code><body>
<div class="body">
    <?php
        if($type=='t'){
            $timer = false;
    ?>
        <div id="clockdiv"></div>
        <script language="javascript">timer = setInterval(timer(), 10000)</script>
    <?php
            echo $timer;
        }
    ?>
</div>
</code>```

Title: How to get the result of a js function called with <script>?

Body:
I am currently working on a quizz page with code people have already done before. I have to add a timer and when the timer is done, I have to send a form.
I have decided to make my function a boolean to get the result directly with the return. When it's true, then the timer is over. But the problem is
I call a js function in the html and I don't know how to get the return result.

This is the part of the code I need help on :

echo '

';
       if($type=='t'){
             $timer = false;
             echo '

';
             echo '';
             echo $timer;
         }

And my js function :

function timer(){
          var running = false;
          var time_in_minutes = 0.3;
          var current_time = Date.parse(new Date());
          var deadline = new Date(current_time + time_in_minutes*60*1000);
          function run_clock(id,endtime){
            var clock = document.getElementById(id);
            function update_clock(){
                          function time_remaining(endtime){
                             var t = Date.parse(endtime) - Date.parse(new Date());
                             var seconds = Math.floor( (t/1000) % 60 );
                             var minutes = Math.floor( (t/1000/60) % 60 );
                             var hours = Math.floor( (t/(1000*60*60)) % 24 );
                             var days = Math.floor( t/(1000*60*60*24) );
                             return {'total':t, 'days':days, 'hours':hours, 'minutes':minutes, 'seconds':seconds};
                          }
        var t = time_remaining(endtime);
        clock.innerHTML = 'minutes: '+t.minutes+'
seconds: '+t.seconds;
        if(t.total<=0){
                  clearInterval(timeinterval);
                  clock.innerHTML = 'Temps écoulé';
                  running = true;
                 }
    }
    update_clock(); // run function once at first to avoid delay
    var timeinterval = setInterval(update_clock,1000);
}
          run_clock('clockdiv',deadline);
          return running;
}

Body:
Try below code

<body>
<div class="body">
    <?php
        if($type=='t'){
            $timer = false;
    ?>
        <div id="clockdiv"></div>
        <script language="javascript">timer = setInterval(timer(), 10000)</script>
    <?php
            echo $timer;
        }
    ?>
</div>


问:
How to convert the column to numeric in python for sorting
I am new to python (learner). Please check my question and help me to resolve the issue.

I have csv file with the below content

```<code>test,cycle,date,status
func,2,09/07/17,pass
func,10,09/08/17,fail
func,3,09/08/17,pass
func,1,09/08/17,no run
func,22,09/08/17,in progress
func,11,09/08/17,on hold
</code>```

when i sort 2nd column (cycle) it shows the below output

```<code>['func', '1', '09/08/17', 'no run']
['func', '10', '09/08/17', 'fail']
['func', '11', '09/08/17', 'on hold']
['func', '2', '09/07/17', 'pass']
['func', '22', '09/08/17', 'in progress']
['func', '3', '09/08/17', 'pass']
</code>```

Problem I faced here is it is sorting as string, due to this it shows the output as 1, 10, 11, 2, 22, 3. but i want to get the output in sorted by numeric (int/float) so that i will get the output 1, 2, 3, 10, 11, 22.

Below is the small script i have. could you help me to modify the script to change the column it to numeric before sort?

```<code>with open ('C:\Automation\sample.csv') as csvfile:
</code>```

readCSVfile = csv.reader(csvfile, delimiter=',')

```<code>for row in readCSVfile:
sort = sorted(readCSVfile, key=operator.itemgetter(1), reverse = False)
 for eachline in sort:
print eachline`
</code>```

答:
As other answers has stated, either you can

using another function than operator.itemgetter to convert value to int when sorting

or using a for loop to convert the array data before sorting.

But if you working with tabular data like this often, it's better to use pandas. You need to install it, but again: if you do this often, it's worth it.

```<code>import pandas as pd

df = pd.read_csv('sample.csv')

df['cycle'] = df['cycle'].astype(int)

print(df.sort_values(by='cycle'))

# or reverse
print(df.sort_values(by='cycle', ascending=False))
</code>```

Body:
I am new to python (learner). Please check my question and help me to resolve the issue.

I have csv file with the below content

test,cycle,date,status
func,2,09/07/17,pass
func,10,09/08/17,fail
func,3,09/08/17,pass
func,1,09/08/17,no run
func,22,09/08/17,in progress
func,11,09/08/17,on hold

when i sort 2nd column (cycle) it shows the below output

['func', '1', '09/08/17', 'no run']
['func', '10', '09/08/17', 'fail']
['func', '11', '09/08/17', 'on hold']
['func', '2', '09/07/17', 'pass']
['func', '22', '09/08/17', 'in progress']
['func', '3', '09/08/17', 'pass']

Problem I faced here is it is sorting as string, due to this it shows the output as 1, 10, 11, 2, 22, 3. but i want to get the output in sorted by numeric (int/float) so that i will get the output 1, 2, 3, 10, 11, 22.

Below is the small script i have. could you help me to modify the script to change the column it to numeric before sort?

with open ('C:\Automation\sample.csv') as csvfile:

readCSVfile = csv.reader(csvfile, delimiter=',')

for row in readCSVfile:
sort = sorted(readCSVfile, key=operator.itemgetter(1), reverse = False)
 for eachline in sort:
print eachline`

Body:
As other answers has stated, either you can

using another function than operator.itemgetter to convert value to int when sorting

or using a for loop to convert the array data before sorting.

But if you working with tabular data like this often, it's better to use pandas. You need to install it, but again: if you do this often, it's worth it.

import pandas as pd

df = pd.read_csv('sample.csv')

df['cycle'] = df['cycle'].astype(int)

print(df.sort_values(by='cycle'))

# or reverse
print(df.sort_values(by='cycle', ascending=False))


问:
Pending call using axios on express
Im trying to do a really simple call to an api using axios with express and have no idea why its always pending on browser

This is my route

```<code>var express = require("express");
var router = express.Router();
const controller = require("../../controllers/issues.controller");
/* GET ALL ISSUES */
router
  .route('/')
  .get(controller.getAllIssues);
</code>```

This is my controller

```<code>var axios = require("axios");
const url = "https://redmine-mock-api.herokuapp.com/api/v1/issues?after=2019-04-13T12:00";

exports.getAllIssues = () => {
  const res = axios.get(url)
    .then(res => console.log(res.data))
    .catch(err => console.log("Axios err: ", err));
}
</code>```

This is the app.js

```<code>var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./src/api/routes/v1/index');
var usersRouter = require('./src/api/routes/v1/users');
var issuesRouter = require('./src/api/routes/v1/issues');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/v1/users', usersRouter);
app.use('/v1/issues', issuesRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
</code>```

On the browser its always pending and I already trying from .then to await/async and have no idea what im doing wrong. When i had the route and controller on the same file it was working. Anyone with a tip please?

答:
I believe the issue is with the controller. Since you never run the res variable function (just define it), nothing happens and since the response is not sent back... it is hanging.

```<code>exports.getAllIssues = (req, res) => {
  axios.get(url)
    .then(axRes => {
        console.log(axRes.data)
        // this below line is what closes the loop on waiting for the controller
        res.json(axRes.data);
    })
    .catch(res.json);
}
</code>```

An async approach would look very similar

```<code>exports.getAllIssues = async (req, res) => {
   try {
      const axRes = await axios.get(url);
      res.json(axRes.data);
   } catch(err) {
      res.send(err);
   }
}
</code>```

You can read about different express res.send methods etc here http://expressjs.com/en/api.html#res.json

Title: Pending call using axios on express

Body:
Im trying to do a really simple call to an api using axios with express and have no idea why its always pending on browser

This is my route

var express = require("express");
var router = express.Router();
const controller = require("../../controllers/issues.controller");
/* GET ALL ISSUES */
router
  .route('/')
  .get(controller.getAllIssues);

This is my controller

var axios = require("axios");
const url = "https://redmine-mock-api.herokuapp.com/api/v1/issues?after=2019-04-13T12:00";

exports.getAllIssues = () => {
  const res = axios.get(url)
    .then(res => console.log(res.data))
    .catch(err => console.log("Axios err: ", err));
}

This is the app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./src/api/routes/v1/index');
var usersRouter = require('./src/api/routes/v1/users');
var issuesRouter = require('./src/api/routes/v1/issues');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/v1/users', usersRouter);
app.use('/v1/issues', issuesRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

On the browser its always pending and I already trying from .then to await/async and have no idea what im doing wrong. When i had the route and controller on the same file it was working. Anyone with a tip please?

Body:
I believe the issue is with the controller. Since you never run the res variable function (just define it), nothing happens and since the response is not sent back... it is hanging.

exports.getAllIssues = (req, res) => {
  axios.get(url)
    .then(axRes => {
        console.log(axRes.data)
        // this below line is what closes the loop on waiting for the controller
        res.json(axRes.data);
    })
    .catch(res.json);
}

An async approach would look very similar

exports.getAllIssues = async (req, res) => {
   try {
      const axRes = await axios.get(url);
      res.json(axRes.data);
   } catch(err) {
      res.send(err);
   }
}

You can read about different express res.send methods etc here http://expressjs.com/en/api.html#res.json


问:
Getting Strange message when creating a browser instance
I am using JxBrowser (6.23.1) on windows 10 and using the 64-bit library. however, when i startup the demo application I get the following Log message.

SEVERE: [0528/084716.632:ERROR:browser_process_stub.cpp(279)] NOT IMPLEMENTED

Can anyone shed light on this and whether this is an issue?

I have tried to find anything in relation to above error code, but did not find anything.

答: The browser_process_stub.cpp(279)] NOT IMPLEMENTED message means that Chromium engine tries to get access to the specific code of JxBrowser which is not implemented at the moment due to the fact that this functionality is not supported by JxBrowser at the moment. This method does not affect the existing JxBrowser functionality, so you can safely ignore this error message.


问:
how to avoid the explicit-construction anti-pattern and still keep indentation/callbacks low
Lets say we have a function, that calls a fair amount of async functions like so:

```<code>downloadAndAssemble = () =>
  new Promise(async (resolve, reject) => {

    if (!(await checkAvailableDiskSpace())) {
      resolve(false);
      return;
    }

    try {
      // Download all
      let files  = await this.downloadAll();

      // Assemble File from downloaded snippets.
      const assembledFile = await buildFile(files).catch(error => reject(error));

      // Save assembled file.
      resolve(true);
    } catch (err) {
      reject(err);
    } finally {
      const dirExists = await fs.exists(tmpFolderPath);
      if (dirExists) await fs.unlink(tmpFolderPath);
    }
  });
</code>```

The first problem I see is new Promise(async (resolve, reject) => { which is an anti pattern according to this SO article.

The general Idea I got from that article is to reuse Promises if available, and not create new ones.

If I follow the suggestions in this SO answer I should use .then and .catch in the logic flow of the function to utilize the existing Promises.

But this would result in more indentations (i.e. one per promise used), which I thought Promises should help eliminate.

As you can see from .catch(error => reject(error)) the code is not very consistent with handling errors thrown by Promises contained within it.

答:
```<code>  downloadAndAssemble = async () =>  {
    if (!(await checkAvailableDiskSpace())) {
      return false;
    }

     try {
       // Download all
       let files  = await this.downloadAll();

       // Assemble File from downloaded snippets.
       const assembledFile = await buildFile(files);

      // Save assembled file.
      return true;
    } finally {
       const dirExists = await fs.exists(tmpFolderPath);
       if (dirExists) await fs.unlink(tmpFolderPath);
    }
};
</code>```

If you call an async function, it will implicitly create a promise under the hood for you, that resolves if you return and rejects if you throw, so there is no need to create and manage a promise "manually".

.catch(error => reject(error)) makes little sense as awaiting a promise automatically lets the errors bubble up. In your code this bypasses the try { ... } catch { ... } which is probably not wanted.

The same applies to } catch (err) {  reject(err); }, await is all you need.

Body:
Lets say we have a function, that calls a fair amount of async functions like so:

downloadAndAssemble = () =>
  new Promise(async (resolve, reject) => {

    if (!(await checkAvailableDiskSpace())) {
      resolve(false);
      return;
    }

    try {
      // Download all
      let files  = await this.downloadAll();

      // Assemble File from downloaded snippets.
      const assembledFile = await buildFile(files).catch(error => reject(error));

      // Save assembled file.
      resolve(true);
    } catch (err) {
      reject(err);
    } finally {
      const dirExists = await fs.exists(tmpFolderPath);
      if (dirExists) await fs.unlink(tmpFolderPath);
    }
  });

The first problem I see is new Promise(async (resolve, reject) => { which is an anti pattern according to this SO article.

The general Idea I got from that article is to reuse Promises if available, and not create new ones.

If I follow the suggestions in this SO answer I should use .then and .catch in the logic flow of the function to utilize the existing Promises.

But this would result in more indentations (i.e. one per promise used), which I thought Promises should help eliminate.

As you can see from .catch(error => reject(error)) the code is not very consistent with handling errors thrown by Promises contained within it.

Body:
  downloadAndAssemble = async () =>  {
    if (!(await checkAvailableDiskSpace())) {
      return false;
    }

     try {
       // Download all
       let files  = await this.downloadAll();

       // Assemble File from downloaded snippets.
       const assembledFile = await buildFile(files);

      // Save assembled file.
      return true;
    } finally {
       const dirExists = await fs.exists(tmpFolderPath);
       if (dirExists) await fs.unlink(tmpFolderPath);
    }
};

If you call an async function, it will implicitly create a promise under the hood for you, that resolves if you return and rejects if you throw, so there is no need to create and manage a promise "manually".

.catch(error => reject(error)) makes little sense as awaiting a promise automatically lets the errors bubble up. In your code this bypasses the try { ... } catch { ... } which is probably not wanted.

The same applies to } catch (err) {  reject(err); }, await is all you need.


问:
variables in the flash scope don't stay alive in Google Chrome
When a user tries to access a page in the administration controllers (mostly CRUD stuff), he is being redirected to the login page. And, if the credentials is correct and he is indeed an administrator, he is begin redirected to the page he wanted to access in the previous request.

Whenever someone tries to access a forbidden page he is being redirected to the following controller:

```<code>    public static void login(String returnUrl) throws Throwable {
    Http.Cookie remember = request.cookies.get("rememberme");
    flash.put("url",returnUrl);
    if (remember != null && remember.value.indexOf("-") > 0) {
        String sign = remember.value.substring(0, remember.value.indexOf("-"));
        String username = remember.value.substring(remember.value.indexOf("-") + 1);
        if (Crypto.sign(username).equals(sign)) {
            session.put("username", username);
            redirectToOriginalURL(returnUrl);
        }
    }
    flash.keep();
    render();
}
</code>```

Which executes the authenticte(...) method:

```<code>public static void authenticate(@Required String username, String password, boolean remember, String returnUrl) throws Throwable {
    // Check tokens
    Boolean allowed = false;
    // This is the official method name
    allowed = (Boolean) Security.invoke("authenticate", username, password);
    if (validation.hasErrors() || !allowed) {
        flash.keep("url");
        flash.error("secure.error");
        params.flash();
        login(returnUrl);
    }
    // Mark user as connected
    session.put("username", username);
    // Remember if needed
    if (remember) {
        response.setCookie("rememberme", Crypto.sign(username) + "-" + username, "30d");
    }
    // Redirect to the original URL (or /)
    flash.keep("url");
    redirectToOriginalURL(returnUrl);
}
</code>```

Note the String returnUrl in the parameter list. This controller is always called in the view with the response.url value.

The redirectToOriginalURL() is a method that receives a returnUrl in the parameter or in the flash scope.

```<code>static void redirectToOriginalURL(String returnUrl) throws Throwable {
    if(returnUrl==null) returnUrl = flash.get("url");
    if (returnUrl == null) {
        returnUrl = "/";
    }
    redirect(returnUrl);
}
</code>```

This works fine in Firefox and Internet Explorer. But when I try to execute this in Google Chrome, the returnUrl is null. Is this a known issue, or am I doing something terribly wrong?

There are no special requests or anything. The url, when redirected from the unaccessible page (localhost:9000/admin) is http://localhost:9000/account?returnUrl=%2Fadmin. So nothing wrong there...

The error must therefore lie withing the authenticate controller, that seems to be unable to pass arguments to the redirectToOriginalURL method. But, then again, only in Google Chrome.

Suggestions?

答:
I noticed this line of code in login:

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

That calling the method with no arguments, but the redirectToOriginalURL you show has a parameter String. Could it be this is part of the issue?

Body:
When a user tries to access a page in the administration controllers (mostly CRUD stuff), he is being redirected to the login page. And, if the credentials is correct and he is indeed an administrator, he is begin redirected to the page he wanted to access in the previous request.

Whenever someone tries to access a forbidden page he is being redirected to the following controller:

    public static void login(String returnUrl) throws Throwable {
    Http.Cookie remember = request.cookies.get("rememberme");
    flash.put("url",returnUrl);
    if (remember != null && remember.value.indexOf("-") > 0) {
        String sign = remember.value.substring(0, remember.value.indexOf("-"));
        String username = remember.value.substring(remember.value.indexOf("-") + 1);
        if (Crypto.sign(username).equals(sign)) {
            session.put("username", username);
            redirectToOriginalURL(returnUrl);
        }
    }
    flash.keep();
    render();
}

Which executes the authenticte(...) method:

public static void authenticate(@Required String username, String password, boolean remember, String returnUrl) throws Throwable {
    // Check tokens
    Boolean allowed = false;
    // This is the official method name
    allowed = (Boolean) Security.invoke("authenticate", username, password);
    if (validation.hasErrors() || !allowed) {
        flash.keep("url");
        flash.error("secure.error");
        params.flash();
        login(returnUrl);
    }
    // Mark user as connected
    session.put("username", username);
    // Remember if needed
    if (remember) {
        response.setCookie("rememberme", Crypto.sign(username) + "-" + username, "30d");
    }
    // Redirect to the original URL (or /)
    flash.keep("url");
    redirectToOriginalURL(returnUrl);
}

Note the String returnUrl in the parameter list. This controller is always called in the view with the response.url value.

The redirectToOriginalURL() is a method that receives a returnUrl in the parameter or in the flash scope.

static void redirectToOriginalURL(String returnUrl) throws Throwable {
    if(returnUrl==null) returnUrl = flash.get("url");
    if (returnUrl == null) {
        returnUrl = "/";
    }
    redirect(returnUrl);
}

This works fine in Firefox and Internet Explorer. But when I try to execute this in Google Chrome, the returnUrl is null. Is this a known issue, or am I doing something terribly wrong?

There are no special requests or anything. The url, when redirected from the unaccessible page (localhost:9000/admin) is http://localhost:9000/account?returnUrl=%2Fadmin. So nothing wrong there...

The error must therefore lie withing the authenticate controller, that seems to be unable to pass arguments to the redirectToOriginalURL method. But, then again, only in Google Chrome.

Suggestions?

Body:
I noticed this line of code in login:

 redirectToOriginalURL();

That calling the method with no arguments, but the redirectToOriginalURL you show has a parameter String. Could it be this is part of the issue?


答:
That's because same-value console.logs are grouped together in browsers' consoles.

This can usually be disabled, i.e. in Chrome & Opera:

In Firefox it's in console's settings (press F1 while using console)

Another option is to write more data along with the value, eg.:

```<code>      console.log(i, j, map[i][j]);
</code>```

Title: How to write out n*n Matrix values in JavaScript?

Body:
I'm new to JavaScript, so I decided to try to make a simple n*n Array. When I'm trying to write it out, I get, something starnge back.

var map = [

  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],

  [1, 2, 3, 0, 0, 0, 0, 0, 0, 1],

  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],

  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],

  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],

  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],

  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],

  [1, 0, 0, 0, 0, 0, 0, 0, 0, 1],

  [1, 0, 0, 0, 0, 0, 0, 0, 3, 1],

  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
];

function GoTh() {
  for (var i = 0; i < map.length; i++) {
    for (var j = 0; j < map[i].length; j++) {
      console.log(map[i][j]);
    }
  }
}
GoTh();

I expected it to write all 100 values, but it gives back this:
1 2 3 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 3 1

Body:
That's because same-value console.logs are grouped together in browsers' consoles.

This can usually be disabled, i.e. in Chrome & Opera:

In Firefox it's in console's settings (press F1 while using console)

Another option is to write more data along with the value, eg.:

      console.log(i, j, map[i][j]);