问:
Get index of searchresult in array
I have the following code:

var member_data_list = [
  ["adrian", "test", Number(9)],
  ["supler", "test", Number(2.3)],
  ["franz", "test", Number(2.5)],
  ["drucker", "test", Number(9.6)],
];

if (exists(member_data_list, "franz")) {
     //HERE I NEED TO GET THE INDEX OF MEMBER_DATA_LIST[?]
     //EXAMPLE: if (exists(member_data_list, "franz")) => RESULT => 2 (MEMBER_DATA_LIST[2])
     console.log("NAME IS IN ARRAY AT INDEX " + "?");
}

function exists(arr, search) {
   return arr.some(row => row.includes(search));
}```

How to get the index of the name in this array?

答:
You could create another function to get the index looping the array and using includes:

var member_data_list = [
  ["adrian", "test", Number(9)],
  ["supler", "test", Number(2.3)],
  ["franz", "test", Number(2.5)],
  ["drucker", "test", Number(9.6)],
];

if (exists(member_data_list, "franz")) {
     var index = findIndex(member_data_list, 'franz');
     console.log("NAME IS IN ARRAY AT INDEX " + index);
}

function exists(arr, search) {
   return arr.some(row => row.includes(search));
}

function findIndex(array, value) {
    for (var i = 0; i < array.length; i += 1) {
        if (array[i].includes(value)) {
            return i;
        }
    }
    return -1;
}```

Title: Get index of searchresult in array

Body:
I have the following code:

var member_data_list = [
  ["adrian", "test", Number(9)],
  ["supler", "test", Number(2.3)],
  ["franz", "test", Number(2.5)],
  ["drucker", "test", Number(9.6)],
];

if (exists(member_data_list, "franz")) {
     //HERE I NEED TO GET THE INDEX OF MEMBER_DATA_LIST[?]
     //EXAMPLE: if (exists(member_data_list, "franz")) => RESULT => 2 (MEMBER_DATA_LIST[2])
     console.log("NAME IS IN ARRAY AT INDEX " + "?");
}

function exists(arr, search) {
   return arr.some(row => row.includes(search));
}

How to get the index of the name in this array?


来源: stackexchange

问:
creating an alias for a function name in C#
I want to create an alias for a funcion name in C#.

Is there any way but function overloading?

```<code>public class Test
{
    public void A()
    {
        ...
    }
}
</code>```

I want to call B replace A same below.

```<code>var test = new Test();
test.B();
</code>```

答:
There have been several comments on this post as to why someone would ever want to do this.  I am currently implementing a Vector type for a graphics project, and the requirements document I am using refers to the Magnitude/Length of a Vector interchangeably.  For the sake of efficiency, I'd rather not wrap a Magnitude() method inside of a Length() method, but it seemed like it would be nice for the sake of readability if the structure understood both terms.

The delegate method referred to by Christian Davén is probably the most efficient way to do this that I can see, but it is probably best to simply add documentation to the  block of your method:

```<code>/// <summary>
/// Calculate the magnitude / length of a vector, including the W component.
/// </summary>
/// <remarks>
/// This calculation will break down if you try to take the magnitude of a point.
/// </remarks>
/// <returns>The magnitude / length of the vector.</returns>
public float Magnitude()
{
    return (float)Math.Sqrt(X * X + Y * Y + Z * Z + W * W);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to create an alias for a funcion name in C#.

Is there any way but function overloading?

public class Test
{
    public void A()
    {
        ...
    }
}

I want to call B replace A same below.

var test = new Test();
test.B();

Body:
There have been several comments on this post as to why someone would ever want to do this.  I am currently implementing a Vector type for a graphics project, and the requirements document I am using refers to the Magnitude/Length of a Vector interchangeably.  For the sake of efficiency, I'd rather not wrap a Magnitude() method inside of a Length() method, but it seemed like it would be nice for the sake of readability if the structure understood both terms.

The delegate method referred to by Christian Davén is probably the most efficient way to do this that I can see, but it is probably best to simply add documentation to the  block of your method:

/// <summary>
/// Calculate the magnitude / length of a vector, including the W component.
/// </summary>
/// <remarks>
/// This calculation will break down if you try to take the magnitude of a point.
/// </remarks>
/// <returns>The magnitude / length of the vector.</returns>
public float Magnitude()
{
    return (float)Math.Sqrt(X * X + Y * Y + Z * Z + W * W);
}

ContentLicense: CC BY-SA 4.0


答:
You can iterate the array and return the index of the nested array. In order to find if that name is available in any child array use includes or indexOf. Also suppose the array contains two child array with some content then the higher index will be returned

var member_data_list = [
  ["adrian", "test", Number(9)],
  ["supler", "test", Number(2.3)],
  ["franz", "test", Number(2.5)],
  ["drucker", "test", Number(9.6)],
];

function exists(arr, name) {
  let ind;
  arr.forEach((item, index) => {
    if (item.includes(name.toLowerCase())) {
      ind = index
    }
  })
  return ind;
}
let isExist = exists(member_data_list, "franz")
if (isExist) {
  console.log("NAME IS IN ARRAY AT INDEX " + isExist);
}```

Title: Get index of searchresult in array


问:
Unable to change Table Header Border Codeigniter Bootsrap
I have one site which is built with codeignitor and bootstrap. I have one page in which I have table with below class.

```<code><table class="table table-striped table-bordered" >
            <thead class="thead-dark">
                <tr>
                    <th>#</th>
                    <th>Image</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Gran Id</th>

                    <th>Action</th>
                </tr>
            </thead>
</code>```

I am trying to change color of table header with style adding in my html code like below

```<code><style>
th {
    background-color: blue;
    color: white;
}

</style>
</code>```

But its not working. I have tried lot but not able to do it. Let me know if someone can help me for solve the issue. Thanks!

Edit:
Solution of @failedCoder is changing color but its not useful for gradient background. Its looking like below image, Let me know if someone can improve it.

Thanks!

答:
Quick and dirty solution is to use inline styling

```<code><table class="table table-striped table-bordered" >
            <thead class="thead-dark">
                <tr>
                    // style attribute added
                    <th style="background-color: blue;color: white;">#</th>
                    <th>Image</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Gran Id</th>

                    <th>Action</th>
                </tr>
            </thead>
</code>```

You can also try to use !important to over-ride any other styling on the element

```<code>th {
    background-color: blue !important;
    color: white !important;
}
</code>```

Edit:

You can try to apply your styling to entire first row, instead of just targeting th element

```<code><table class="table table-striped table-bordered" >
            <thead class="thead-dark">
                <tr id="first-row"> // id added to first row
                    <th style="background-color: blue;color: white;">#</th>
                    <th>Image</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Gran Id</th>

                    <th>Action</th>
                </tr>
            </thead>
</code>```

CSS:

```<code>  #first-row   {
      ... do your stuff here
  }
</code>```

Body:
I have one site which is built with codeignitor and bootstrap. I have one page in which I have table with below class.

                    #
                    Image
                    First Name
                    Last Name
                    Gran Id

                    Action

I am trying to change color of table header with style adding in my html code like below

But its not working. I have tried lot but not able to do it. Let me know if someone can help me for solve the issue. Thanks!

Edit:
Solution of @failedCoder is changing color but its not useful for gradient background. Its looking like below image, Let me know if someone can improve it.

Thanks!

Body:
Quick and dirty solution is to use inline styling

<table class="table table-striped table-bordered" >
            <thead class="thead-dark">
                <tr>
                    // style attribute added
                    <th style="background-color: blue;color: white;">#</th>
                    <th>Image</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Gran Id</th>

                    <th>Action</th>
                </tr>
            </thead>

You can also try to use !important to over-ride any other styling on the element

th {
    background-color: blue !important;
    color: white !important;
}

Edit:

You can try to apply your styling to entire first row, instead of just targeting th element

<table class="table table-striped table-bordered" >
            <thead class="thead-dark">
                <tr id="first-row"> // id added to first row
                    <th style="background-color: blue;color: white;">#</th>
                    <th>Image</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Gran Id</th>

                    <th>Action</th>
                </tr>
            </thead>

CSS:

  #first-row   {
      ... do your stuff here
  }


问:
xml as3 problem
Getting this error when I try to test the xml as3 script:

```<code>TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at xml_images_fla::MainTimeline/processXML()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/onComplete()
</code>```

Can anyone see if the code is so far not working properly or is it somewhere esle?

```<code>import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Loader;

var columns:Number;

var my_x:Number;
var my_y:Number;
var my_thumb_width:Number;
var my_thumb_height:Number;
var my_images:XMLList;
var my_total:Number;
var container_mc:MovieClip;

var XMLLoader:URLLoader = new URLLoader();

XMLLoader.load(new URLRequest("gallery.xml"));

XMLLoader.addEventListener(Event.COMPLETE, processXML);

function processXML(e:Event):void{

    var myXML:XML = new XML(e.target.data);
    columns = myXML.@COLUMNS;
    my_x = myXML.@XPOSITION;
    my_y = myXML.@YPOSITION;
    my_thumb_width = myXML.@WIDTH;
    my_thumb_height = myXML.@HEIGHT;
    my_images = my_images.length();

    createContainer();
    callThumbs();

}

function createContainer():void{

    container_mc = new MovieClip();
    container_mc.x = my_x;
    container_mc.y = my_y;
    addChild(container_mc);

}

function callThumbs():void{

    for (var i:Number = 0; i < my_total; i++){
        var thumb_url = my_images[i].@THUMB;;
        var thumb_loader = new Loader();
        thumb_loader.load(new URLRequest(thumb_url));
        thumb_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbLoaded);

    }
}

function thumbLoaded(e:Event):void{

    var my_thumb:Loader = Loader(e.target.loader);
    container_mc.addChild(my_thumb);
}
</code>```

答:
```<code>my_images = my_images.length();
</code>```

That line is probably your issue. my_images isn't defined yet at this point.

Title: xml as3 problem

Body:
Getting this error when I try to test the xml as3 script:

TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at xml_images_fla::MainTimeline/processXML()
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/onComplete()

Can anyone see if the code is so far not working properly or is it somewhere esle?

import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.display.MovieClip;
import flash.events.Event;
import flash.display.Loader;

var columns:Number;

var my_x:Number;
var my_y:Number;
var my_thumb_width:Number;
var my_thumb_height:Number;
var my_images:XMLList;
var my_total:Number;
var container_mc:MovieClip;

var XMLLoader:URLLoader = new URLLoader();

XMLLoader.load(new URLRequest("gallery.xml"));

XMLLoader.addEventListener(Event.COMPLETE, processXML);

function processXML(e:Event):void{

    var myXML:XML = new XML(e.target.data);
    columns = myXML.@COLUMNS;
    my_x = myXML.@XPOSITION;
    my_y = myXML.@YPOSITION;
    my_thumb_width = myXML.@WIDTH;
    my_thumb_height = myXML.@HEIGHT;
    my_images = my_images.length();

    createContainer();
    callThumbs();

}

function createContainer():void{

    container_mc = new MovieClip();
    container_mc.x = my_x;
    container_mc.y = my_y;
    addChild(container_mc);

}

function callThumbs():void{

    for (var i:Number = 0; i < my_total; i++){
        var thumb_url = my_images[i].@THUMB;;
        var thumb_loader = new Loader();
        thumb_loader.load(new URLRequest(thumb_url));
        thumb_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbLoaded);

    }
}

function thumbLoaded(e:Event):void{

    var my_thumb:Loader = Loader(e.target.loader);
    container_mc.addChild(my_thumb);
}

Body:
my_images = my_images.length();

That line is probably your issue. my_images isn't defined yet at this point.


问:
About speedy mass deletion of users in Kentico10
I want to delete more than 1 million User information in Kentico10.

I tried to delete it with UserInfoProvider.DeleteUser (); (see the following documentation), but it is expected that it will take nearly one year with a simple calculation.
https://docs.kentico.com/api10/configuration/users#Users-Deletingauser

Because it's a simple calculation, I think it's actually a bit shorter, but it still takes time.
Is there any other way to delete users in a short time?

答:
Of course make sure you have a backup of your database before you do any of this.

Depending on the features you're using, you could get away with a SQL statement.  Due to the complexities of the references of a user to multiple other tables, the SQL statement can get pretty complex and you need to make sure you remove the other references before removing the actual user record.

I'd highly recommend an API approach and delete users through the API so it removes all the references for you automatically.  In your API calls make sure you wrap the delete action in the following so it stops the logging of the events and other labor-intensive activities not needed.

```<code>using (var context = new CMSActionContext())
{
    context.DisableAll();
    // delete your user
}
</code>```

In your code, I'd only select the top 100 or so at a time and delete them in batches.  Assuming you don't need this done all in one run, you could let the scheduled task run your custom code for a week and see where you're at.

If all else fails, figure out how to delete the user and the 70+ foreign key references and you'll be golden.

Body:
Of course make sure you have a backup of your database before you do any of this.

Depending on the features you're using, you could get away with a SQL statement.  Due to the complexities of the references of a user to multiple other tables, the SQL statement can get pretty complex and you need to make sure you remove the other references before removing the actual user record.

I'd highly recommend an API approach and delete users through the API so it removes all the references for you automatically.  In your API calls make sure you wrap the delete action in the following so it stops the logging of the events and other labor-intensive activities not needed.

using (var context = new CMSActionContext())
{
    context.DisableAll();
    // delete your user
}

In your code, I'd only select the top 100 or so at a time and delete them in batches.  Assuming you don't need this done all in one run, you could let the scheduled task run your custom code for a week and see where you're at.

If all else fails, figure out how to delete the user and the 70+ foreign key references and you'll be golden.


问:
get values from xml by sql query when several attributes
There is xml with several attributes "Num"

```<code>DECLARE @XML XML = '
<FileId global_id="1234">
  <file id="12aa">
  </file>
  <file id="12bb">
    <Number Num = "1"/>
    <Number Num = "2"/>
  </file>
</FileId>';
</code>```

With this sql query only one attribute can be get

```<code>SELECT F.[File].value(N'../@global_id','varchar(100)') as id_payment,
  F.[File].value('@id', 'varchar(4)') AS id,
  F.[File].value('(Number/@Num)[1]', 'int') as [Num]
FROM (VALUES (@XML)) V (X)
  CROSS APPLY V.X.nodes('/FileId/file') F([File])
</code>```

How to get all attributes -- Num = 1 and Num = 2.
Can be a variable amount of attributes.

```<code>id_payment  id      Num
1234        12aa    NULL
1234        12bb    1
1234        12bb    2
</code>```

答:
```<code>DECLARE @XML XML = '
<FileId global_id="1234">
  <file id="12aa">
  </file>
  <file id="12bb">
    <Number Num = "1"/>
    <Number Num = "2"/>
    <Number Num = "3"/>
    <Number Num = "4"/>
    <Number Num = "5"/>
    <Number Num = "6"/>
  </file>
</FileId>';

SELECT F.[File].value(N'../@global_id','varchar(100)') as id_payment,
  F.[File].value('@id', 'varchar(4)') AS id,
  F.[File].value('(Number/@Num)[1]', 'int') as [Num],
  n.num.value('(@Num)[1]', 'int') as [Numxyz]

FROM (VALUES (@XML)) V (X)
  CROSS APPLY V.X.nodes('/FileId/file') F([File])
  outer apply F.[File].nodes('Number') as n(num)
</code>```

Body:
There is xml with several attributes "Num"

DECLARE @XML XML = '
<FileId global_id="1234">
  <file id="12aa">
  </file>
  <file id="12bb">
    <Number Num = "1"/>
    <Number Num = "2"/>
  </file>
</FileId>';

With this sql query only one attribute can be get

SELECT F.[File].value(N'../@global_id','varchar(100)') as id_payment,
  F.[File].value('@id', 'varchar(4)') AS id,
  F.[File].value('(Number/@Num)[1]', 'int') as [Num]
FROM (VALUES (@XML)) V (X)
  CROSS APPLY V.X.nodes('/FileId/file') F([File])

How to get all attributes -- Num = 1 and Num = 2.
Can be a variable amount of attributes.

id_payment  id      Num
1234        12aa    NULL
1234        12bb    1
1234        12bb    2


问:
Factory referring to association in after create
I have a factory for an account that has a relationship with a product. When adding an after create callback it is referring to the product and not the account.

account factory

```<code>FactoryBot.define do
  factory :account do
    billing_method { 'monthly' }
    workflow_state { 'active' }
  end

  after :create, &:create_api_credential
end
</code>```

product factory

```<code>FactoryBot.define do
  factory :product do
    ...
    account
  end
end
</code>```

test

```<code>subject { create(:product) }
it 'has an account' do
  subject
  assert_not_nil(subject.account)
end
</code>```

the error

```<code> NoMethodError: undefined method `create_api_credential' for #<Product:0x00007fab7cefe2f8>
</code>```

create_api_credential exist on account not product

答:
Did you try to move:
after :create, &:create_api_credential to :account block?

```<code>factory :account do
  billing_method { 'monthly' }
  workflow_state { 'active' }

  after :create, &:create_api_credential
end
</code>```

Body:
I have a factory for an account that has a relationship with a product. When adding an after create callback it is referring to the product and not the account.

account factory

FactoryBot.define do
  factory :account do
    billing_method { 'monthly' }
    workflow_state { 'active' }
  end

  after :create, &:create_api_credential
end

product factory

FactoryBot.define do
  factory :product do
    ...
    account
  end
end

test

subject { create(:product) }
it 'has an account' do
  subject
  assert_not_nil(subject.account)
end

the error

 NoMethodError: undefined method `create_api_credential' for #<Product:0x00007fab7cefe2f8>

create_api_credential exist on account not product

Body:
Did you try to move:
after :create, &:create_api_credential to :account block?

factory :account do
  billing_method { 'monthly' }
  workflow_state { 'active' }

  after :create, &:create_api_credential
end


问:
Web Intelligence : double column parameter
I try to do something like that (it's a count of order between 2 price depending months) :

It works until I drag and drop my column "100-500" next to "0-100":

Is there a tips to do what I want ?

I work on Web Intelligence 4.2 Support Pack 4 Compilation : 14.2.4.2410

答:
I finally found a way to do that. I used my months two times in my table for my two differents interval.

And then I fusionned the two "January" and same thing for their values (select two column with ctrl+click and then right click "fusionate").


问:
how post props redux React
I would like to explain my problem of the day.

I can't post "this.props.total",
I do not understand how to post a props, can you help me pls?
currently the props works correctly.

```<code>import React, { Component } from 'react';
import { CardText, } from 'reactstrap';
import { connect } from 'react-redux'

class thisPropsFortotal extends Component {

handleSubmit = (e) => {
    e.preventDefault();
    const config = {
     method: "POST",
     headers: {
       "Content-Type": "application/json",
     },
     body: JSON.stringify({this.props.total}),
    };

     const url = entrypoint + "/alluserpls";
     fetch(url, config)
     .then(res => res.json())
     .then(res => {
       if (res.error) {
         alert(res.error);
       } else {
         alert(`ajouté avec l'ID ${res}!`);
       }
     }).catch(e => {
       console.error(e);

       }).finally(() => this.setState({ redirect: true }));
    }
   render() {
    return (
        <div>
            <form onSubmit={this.handleSubmit}>
  <button type="submit">Add</button>
  </form>
            <CardText>{this.props.total} € </CardText>
        </div>
    );
   }
 }
 const mapStateToProps = (state) => {
  return {
    total: state.addedItems.reduce((acc, item) => { return acc + (item.quantity *
  item.price) }, 0)
    //addedItems: state.addedItems
  }
  }

export default connect(mapStateToProps)(thisPropsFortotal)
</code>```

Do you have an idea of how to fix this? Neff

答:
You are attempting to stringify {this.props.total}, which is invalid syntax.

You can pass an object explicitely defining the total property like so:

```<code>body: JSON.stringify({total: this.props.total}),
</code>```

Or, simply stringify the this.props object itself:

```<code>body: JSON.stringify(this.props),
</code>```

Title: how post props redux React

Body:
I would like to explain my problem of the day.

I can't post "this.props.total",
I do not understand how to post a props, can you help me pls?
currently the props works correctly.

import React, { Component } from 'react';
import { CardText, } from 'reactstrap';
import { connect } from 'react-redux'

class thisPropsFortotal extends Component {

handleSubmit = (e) => {
    e.preventDefault();
    const config = {
     method: "POST",
     headers: {
       "Content-Type": "application/json",
     },
     body: JSON.stringify({this.props.total}),
    };

     const url = entrypoint + "/alluserpls";
     fetch(url, config)
     .then(res => res.json())
     .then(res => {
       if (res.error) {
         alert(res.error);
       } else {
         alert(`ajouté avec l'ID ${res}!`);
       }
     }).catch(e => {
       console.error(e);

       }).finally(() => this.setState({ redirect: true }));
    }
   render() {
    return (

            <form onSubmit={this.handleSubmit}>
  <button type="submit">Add</button>
  </form>
            <CardText>{this.props.total} € </CardText>

    );
   }
 }
 const mapStateToProps = (state) => {
  return {
    total: state.addedItems.reduce((acc, item) => { return acc + (item.quantity *
  item.price) }, 0)
    //addedItems: state.addedItems
  }
  }

export default connect(mapStateToProps)(thisPropsFortotal)

Do you have an idea of how to fix this? Neff

Body:
You are attempting to stringify {this.props.total}, which is invalid syntax.

You can pass an object explicitely defining the total property like so:

body: JSON.stringify({total: this.props.total}),

Or, simply stringify the this.props object itself:

body: JSON.stringify(this.props),


问:
JS generate random boolean
Simple question, but I'm interested in the nuances here.

I'm generating random booleans using the following method I came up with myself:

```<code>const rand = Boolean(Math.round(Math.random()));
</code>```

Whenever random() shows up, it seems there's always a pitfall - it's not truly random, it's compromised by something or other, etc.  So, I'd like to know:

a) Is the above the best-practice way to do it?

b) Am I overthinking things?

c) Am I underthinking things?

d) Is there a better/faster/elegant-er way I don't know of?

(Also somewhat interested if B and C are mutually exclusive.)

Update

If it makes a difference, I'm using this for movement of an AI character.

答:
Impressed a lot by Kelvin's answer I would like to suggest a fairly similar but slightly enhanced solution.

```<code>var randomBoolean = Math.random() < 0.5;
</code>```

This solution is a bit more obvious to read, because the number on the right-hand side of < tells you the probability of getting true rather than of getting false, which is more natural to comprehend. Also < is one symbol shorter than >=;

Title: JS generate random boolean

Body:
Simple question, but I'm interested in the nuances here.

I'm generating random booleans using the following method I came up with myself:

const rand = Boolean(Math.round(Math.random()));

Whenever random() shows up, it seems there's always a pitfall - it's not truly random, it's compromised by something or other, etc.  So, I'd like to know:

a) Is the above the best-practice way to do it?

b) Am I overthinking things?

c) Am I underthinking things?

d) Is there a better/faster/elegant-er way I don't know of?

(Also somewhat interested if B and C are mutually exclusive.)

Update

If it makes a difference, I'm using this for movement of an AI character.

Body:
Impressed a lot by Kelvin's answer I would like to suggest a fairly similar but slightly enhanced solution.

var randomBoolean = Math.random() < 0.5;

This solution is a bit more obvious to read, because the number on the right-hand side of < tells you the probability of getting true rather than of getting false, which is more natural to comprehend. Also < is one symbol shorter than >=;


问:
Batch file to unzip files and run Python script
I have a project where I need to unzip files containing a .xls file and then run a Python script to convert the file to .xlsx. I need to do this by executing a Windows Batch file through the Windows Task Scheduler. I found some code on Superuser to unzip the file, but it does not loop and you have to explicitly type the name of the file you want to unzip.

Here's the unzip code:

```<code>@echo off
setlocal
cd /d %~dp0
Call :UnZipFile "C:\Test Folder\" "C:\Test Folder\File1.zip"
exit /b

:UnZipFile <ExtractTo> <newzipfile>
IF "%~dp0"=="" GOTO Continue
set vbs="%temp%\_.vbs"
if exist %vbs% del /f /q %vbs%
>%vbs%  echo Set fso = CreateObject("Scripting.FileSystemObject")
>>%vbs% echo If NOT fso.FolderExists(%1) Then
>>%vbs% echo fso.CreateFolder(%1)
>>%vbs% echo End If
>>%vbs% echo set objShell = CreateObject("Shell.Application")
>>%vbs% echo set FilesInZip=objShell.NameSpace(%2).items
>>%vbs% echo objShell.NameSpace(%1).CopyHere(FilesInZip)
>>%vbs% echo Set fso = Nothing
>>%vbs% echo Set objShell = Nothing
cscript //nologo %vbs%
if exist %vbs% del /f /q %vbs%
</code>```

Here's my Python code:

```<code>import win32com.client as win32
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--sourcefilepath')
parser.add_argument('--sourcefilename')
args = parser.parse_args()

fname = r"{sourcefilepath}{sourcefilename}".format(sourcefilepath=args.sourcefilepath,sourcefilename=args.sourcefilename)

excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(fname)
wb.SaveAs(fname + "x", FileFormat = 56)

wb.Close()
excel.Application.Quit()
quit()
</code>```

Any help will be great.

答:
@echo off
setlocal
cd /d "%~dp0" || exit /b 1

for %%A in (*.zip) do (
    call :UnZipFile "%cd%\" "%%~fA"

    for %%B in (*.xls) do (
        echo python mypython.py --sourcefilepath "%cd%" --sourcefilename "%%~nxB"
        del "%%~B"
    )
)
exit /b

:UnZipFile <ExtractTo> <newzipfile>
if "%~dp0" == "" exit /b 1
set "vbs=%temp%\_.vbs"
if exist "%vbs%" del /f /q "%vbs%"

(
    echo Set fso = CreateObject("Scripting.FileSystemObject"^)
    echo If NOT fso.FolderExists("%~1"^) Then
    echo fso.CreateFolder("%~1"^)
    echo End If
    echo set objShell = CreateObject("Shell.Application"^)
    echo set FilesInZip=objShell.NameSpace("%~2"^).items
    echo objShell.NameSpace("%~1"^).CopyHere FilesInZip, 16
    echo Set fso = Nothing
    echo Set objShell = Nothing
) > "%vbs%"

cscript //nologo "%vbs%"
if exist "%vbs%" del /f /q "%vbs%"
```

<p>Just some minor fixes to special characters
needing escaping in the <code>echo</code> commands.
Replaced <code>goto continue</code> with <code>exit /b 1</code>.
Added simple <code>for</code> loop to get all zip filenames.</p>

<p>It will get xls files in the current directory
and delete the xls files once the python script
has done the SaveAs task.</p>

<p>Remove <code>echo</code> in front of python command if checked as OK.</p>

<hr>

<p>Or try this python code which does the
looping, unzipping, and xls to xlsx.</p>

<pre class="lang-python prettyprint-override"><code>import win32com.client as win32
import argparse
import glob
import os
import zipfile

def xls_to_xlsx(filename, filepath=None):
    if not filepath:
        filepath = os.getcwd()

    fname = os.path.join(filepath, filename)

    excel = win32.gencache.EnsureDispatch('Excel.Application')
    wb = excel.Workbooks.Open(fname)
    wb.SaveAs(fname + "x", FileFormat = 56)

    wb.Close()
    excel.Application.Quit()

if __name__ == '__main__':
    for zip_file in glob.iglob('*.zip'):
        with zipfile.ZipFile(zip_file) as r:
            r.extractall()

        for xls_file in glob.iglob('*.xls'):
            xls_to_xlsx(xls_file)
            os.remove(xls_file)
</code>```

It does not set current working directory
which Task Scheduler can set it, or you
can add it into the python script to set it.

Body:
I have a project where I need to unzip files containing a .xls file and then run a Python script to convert the file to .xlsx. I need to do this by executing a Windows Batch file through the Windows Task Scheduler. I found some code on Superuser to unzip the file, but it does not loop and you have to explicitly type the name of the file you want to unzip.

Here's the unzip code:

@echo off
setlocal
cd /d %~dp0
Call :UnZipFile "C:\Test Folder\" "C:\Test Folder\File1.zip"
exit /b

:UnZipFile <ExtractTo> <newzipfile>
IF "%~dp0"=="" GOTO Continue
set vbs="%temp%\_.vbs"
if exist %vbs% del /f /q %vbs%
>%vbs%  echo Set fso = CreateObject("Scripting.FileSystemObject")
>>%vbs% echo If NOT fso.FolderExists(%1) Then
>>%vbs% echo fso.CreateFolder(%1)
>>%vbs% echo End If
>>%vbs% echo set objShell = CreateObject("Shell.Application")
>>%vbs% echo set FilesInZip=objShell.NameSpace(%2).items
>>%vbs% echo objShell.NameSpace(%1).CopyHere(FilesInZip)
>>%vbs% echo Set fso = Nothing
>>%vbs% echo Set objShell = Nothing
cscript //nologo %vbs%
if exist %vbs% del /f /q %vbs%

Here's my Python code:

import win32com.client as win32
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--sourcefilepath')
parser.add_argument('--sourcefilename')
args = parser.parse_args()

fname = r"{sourcefilepath}{sourcefilename}".format(sourcefilepath=args.sourcefilepath,sourcefilename=args.sourcefilename)

excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(fname)
wb.SaveAs(fname + "x", FileFormat = 56)

wb.Close()
excel.Application.Quit()
quit()

Any help will be great.

Body:
@echo off
setlocal
cd /d "%~dp0" || exit /b 1

for %%A in (*.zip) do (
    call :UnZipFile "%cd%\" "%%~fA"

    for %%B in (*.xls) do (
        echo python mypython.py --sourcefilepath "%cd%" --sourcefilename "%%~nxB"
        del "%%~B"
    )
)
exit /b

:UnZipFile <ExtractTo> <newzipfile>
if "%~dp0" == "" exit /b 1
set "vbs=%temp%\_.vbs"
if exist "%vbs%" del /f /q "%vbs%"

(
    echo Set fso = CreateObject("Scripting.FileSystemObject"^)
    echo If NOT fso.FolderExists("%~1"^) Then
    echo fso.CreateFolder("%~1"^)
    echo End If
    echo set objShell = CreateObject("Shell.Application"^)
    echo set FilesInZip=objShell.NameSpace("%~2"^).items
    echo objShell.NameSpace("%~1"^).CopyHere FilesInZip, 16
    echo Set fso = Nothing
    echo Set objShell = Nothing
) > "%vbs%"

cscript //nologo "%vbs%"
if exist "%vbs%" del /f /q "%vbs%"

Just some minor fixes to special characters
needing escaping in the echo commands.
Replaced goto continue with exit /b 1.
Added simple for loop to get all zip filenames.

It will get xls files in the current directory
and delete the xls files once the python script
has done the SaveAs task.

Remove echo in front of python command if checked as OK.

Or try this python code which does the
looping, unzipping, and xls to xlsx.

import win32com.client as win32
import argparse
import glob
import os
import zipfile

def xls_to_xlsx(filename, filepath=None):
    if not filepath:
        filepath = os.getcwd()

    fname = os.path.join(filepath, filename)

    excel = win32.gencache.EnsureDispatch('Excel.Application')
    wb = excel.Workbooks.Open(fname)
    wb.SaveAs(fname + "x", FileFormat = 56)

    wb.Close()
    excel.Application.Quit()

if __name__ == '__main__':
    for zip_file in glob.iglob('*.zip'):
        with zipfile.ZipFile(zip_file) as r:
            r.extractall()

        for xls_file in glob.iglob('*.xls'):
            xls_to_xlsx(xls_file)
            os.remove(xls_file)

It does not set current working directory
which Task Scheduler can set it, or you
can add it into the python script to set it.


问:
Spacing in HTML emails
I am designing a little app that can email one of 6 design templates with common content.

What is the best (most consistent) way to maintain space and layout of the text (between lines etc.)

We were thinking about using simple
, but we could lose some flexibility compared to something else. It is a table based layout

Cheers

答:
The best way today is use a p element per line and style that with CSS.

And you should consider to replace most of the table based layout with divs and CSS styles (except where you need horizontal elements with the same height, obviously).

My answer would be better if you would state a specific problem like: "How can I achieve this <insert image here> with HTML?"

Title: Spacing in HTML emails


问:
What is wrong with my addbyAge() function, cause one person is missing somehow?
Output:

```<code> Anderson, 97
 Anfinsen, 79
 Banerjee, 59
 Bridgman, 78
</code>```

My desired output:

```<code> Anderson, 97
 Bishop, 84
 Anfinsen, 79
 Bridgman, 78
 Banerjee, 59
</code>```

My List class, with main function

```<code>package university.people;

import javax.tools.utilities.*;

public class PeopleList {
    private Node start;
    // Here is the issue: Person with the name Bishop does not get outputted
    public void addByAge(Node newNode) {
        if (start == null) {
            start = newNode;
        } else {
            Node temp = newNode;
            Node headTemp = start;
            while (headTemp.getNext() != null) {
                if (temp.getAge() > headTemp.getAge()) {
                    headTemp = temp;
                    break;
                } else {
                    headTemp = headTemp.getNext();
                }
            }
            headTemp.setNext(temp);
        }
    }

    // Create a reference of my List class and add some dummy data sorted by age
    public static void main(String[] args) {
        PeopleList people = new PeopleList();
        people.addByAge(new Node(97, "Anderson"));
        people.addByAge(new Node(79, "Anfinsen"));
        people.addByAge(new Node(59, "Banerjee"));
        people.addByAge(new Node(84, "Bishop"));
        people.addByAge(new Node(78, "Bridgman"));
        people.printPeopleList();
    }

    // Output the list
    private void printPeopleList() {
        Node temp = start;
        while (temp != null) {
            System.out.println(temp.getLastName() + ", " + temp.getAge());
            temp = temp.getNext();
        }
    }
}
</code>```

Here's the Node class for every element inside the List class

```<code>package javax.tools.utilities;

public class Node {
    private int number, age;
    private String lastName;
    private Node next, prev;

    // Constructor
    public Node(int a, String l) {
        this.age = a;
        this.lastName = l;
    }

    // Getter --- SETTER
    public int getNumber() {
        return number;
    }

    public Node getNext() {
        return next;
    }

    public Node getPrev() {
        return prev;
    }

    public void setNext(Node n) {
        this.next = n;
    }

    public void setPrev(Node n) {
        this.prev = n;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}
</code>```

答:
Change the definition of addByAge as follows:

```<code>public void addByAge(Node newNode) {
    if (start == null) {
        start = newNode;
    } else {
        Node headTemp = start;
        Node temp = null;
        while (headTemp.getNext() != null) {
            if (newNode.getAge() > headTemp.getAge() && temp != null) {
                temp.setNext(newNode);
                newNode.setNext(headTemp);
                break;
            } else {
                temp = headTemp;
                headTemp = temp.getNext();
            }
        }
        if (newNode.getAge() > headTemp.getAge()) {
            if (temp != null) {
                temp.setNext(newNode);
                newNode.setNext(headTemp);
            } else {
                start = newNode;
                newNode.setNext(headTemp);
            }

        } else {
            headTemp.setNext(newNode);
        }
    }
}
</code>```

Output after this change:

```<code>Anderson, 97
Bishop, 84
Anfinsen, 79
Bridgman, 78
Banerjee, 59
</code>```

[Update]

Based on OP's request to print the list again in reverse order once the end of the list is reached, given below is the updated program:

```<code>public class Main {
    private Node start;

    public void addByAge(Node newNode) {
        if (start == null) {
            start = newNode;
        } else {
            Node headTemp = start;
            Node temp = null;
            while (headTemp.getNext() != null) {
                if (newNode.getAge() > headTemp.getAge() && temp != null) {
                    temp.setNext(newNode);
                    newNode.setPrev(temp);
                    newNode.setNext(headTemp);
                    headTemp.setPrev(newNode);
                    break;
                } else {
                    temp = headTemp;
                    headTemp = temp.getNext();
                }
            }
            if (newNode.getAge() > headTemp.getAge()) {
                if (temp != null) {
                    temp.setNext(newNode);
                    newNode.setPrev(temp);
                    newNode.setNext(headTemp);
                    headTemp.setPrev(newNode);
                } else {
                    start = newNode;
                    newNode.setNext(headTemp);
                    headTemp.setPrev(newNode);
                }

            } else {
                headTemp.setNext(newNode);
                newNode.setPrev(headTemp);
            }
        }
    }

    // Create a reference of my List class and add some dummy data sorted by age
    public static void main(String[] args) {
        Main people = new Main();
        people.addByAge(new Node(97, "Anderson"));
        people.addByAge(new Node(100, "Andy"));
        people.addByAge(new Node(79, "Anfinsen"));
        people.addByAge(new Node(59, "Banerjee"));
        people.addByAge(new Node(84, "Bishop"));
        people.addByAge(new Node(78, "Bridgman"));
        people.printPeopleList();
    }

    // Print the list. Print again in reverse order once the end of the list is reached
    private void printPeopleList() {
        Node temp = start;
        while (temp.getNext() != null) {
            System.out.println(temp.getLastName() + ", " + temp.getAge());
            temp = temp.getNext();
        }
        System.out.println(temp.getLastName() + ", " + temp.getAge());
        while (temp != null) {
            System.out.println(temp.getLastName() + ", " + temp.getAge());
            temp = temp.getPrev();
        }
    }
}
</code>```

Output:

```<code>Andy, 100
Anderson, 97
Bishop, 84
Anfinsen, 79
Bridgman, 78
Banerjee, 59
Banerjee, 59
Bridgman, 78
Anfinsen, 79
Bishop, 84
Anderson, 97
Andy, 100
</code>```

Body:
Output:

 Anderson, 97
 Anfinsen, 79
 Banerjee, 59
 Bridgman, 78

My desired output:

 Anderson, 97
 Bishop, 84
 Anfinsen, 79
 Bridgman, 78
 Banerjee, 59

My List class, with main function

package university.people;

import javax.tools.utilities.*;

public class PeopleList {
    private Node start;
    // Here is the issue: Person with the name Bishop does not get outputted
    public void addByAge(Node newNode) {
        if (start == null) {
            start = newNode;
        } else {
            Node temp = newNode;
            Node headTemp = start;
            while (headTemp.getNext() != null) {
                if (temp.getAge() > headTemp.getAge()) {
                    headTemp = temp;
                    break;
                } else {
                    headTemp = headTemp.getNext();
                }
            }
            headTemp.setNext(temp);
        }
    }

    // Create a reference of my List class and add some dummy data sorted by age
    public static void main(String[] args) {
        PeopleList people = new PeopleList();
        people.addByAge(new Node(97, "Anderson"));
        people.addByAge(new Node(79, "Anfinsen"));
        people.addByAge(new Node(59, "Banerjee"));
        people.addByAge(new Node(84, "Bishop"));
        people.addByAge(new Node(78, "Bridgman"));
        people.printPeopleList();
    }

    // Output the list
    private void printPeopleList() {
        Node temp = start;
        while (temp != null) {
            System.out.println(temp.getLastName() + ", " + temp.getAge());
            temp = temp.getNext();
        }
    }
}

Here's the Node class for every element inside the List class

package javax.tools.utilities;

public class Node {
    private int number, age;
    private String lastName;
    private Node next, prev;

    // Constructor
    public Node(int a, String l) {
        this.age = a;
        this.lastName = l;
    }

    // Getter --- SETTER
    public int getNumber() {
        return number;
    }

    public Node getNext() {
        return next;
    }

    public Node getPrev() {
        return prev;
    }

    public void setNext(Node n) {
        this.next = n;
    }

    public void setPrev(Node n) {
        this.prev = n;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

Body:
Change the definition of addByAge as follows:

public void addByAge(Node newNode) {
    if (start == null) {
        start = newNode;
    } else {
        Node headTemp = start;
        Node temp = null;
        while (headTemp.getNext() != null) {
            if (newNode.getAge() > headTemp.getAge() && temp != null) {
                temp.setNext(newNode);
                newNode.setNext(headTemp);
                break;
            } else {
                temp = headTemp;
                headTemp = temp.getNext();
            }
        }
        if (newNode.getAge() > headTemp.getAge()) {
            if (temp != null) {
                temp.setNext(newNode);
                newNode.setNext(headTemp);
            } else {
                start = newNode;
                newNode.setNext(headTemp);
            }

        } else {
            headTemp.setNext(newNode);
        }
    }
}

Output after this change:

Anderson, 97
Bishop, 84
Anfinsen, 79
Bridgman, 78
Banerjee, 59

[Update]

Based on OP's request to print the list again in reverse order once the end of the list is reached, given below is the updated program:

public class Main {
    private Node start;

    public void addByAge(Node newNode) {
        if (start == null) {
            start = newNode;
        } else {
            Node headTemp = start;
            Node temp = null;
            while (headTemp.getNext() != null) {
                if (newNode.getAge() > headTemp.getAge() && temp != null) {
                    temp.setNext(newNode);
                    newNode.setPrev(temp);
                    newNode.setNext(headTemp);
                    headTemp.setPrev(newNode);
                    break;
                } else {
                    temp = headTemp;
                    headTemp = temp.getNext();
                }
            }
            if (newNode.getAge() > headTemp.getAge()) {
                if (temp != null) {
                    temp.setNext(newNode);
                    newNode.setPrev(temp);
                    newNode.setNext(headTemp);
                    headTemp.setPrev(newNode);
                } else {
                    start = newNode;
                    newNode.setNext(headTemp);
                    headTemp.setPrev(newNode);
                }

            } else {
                headTemp.setNext(newNode);
                newNode.setPrev(headTemp);
            }
        }
    }

    // Create a reference of my List class and add some dummy data sorted by age
    public static void main(String[] args) {
        Main people = new Main();
        people.addByAge(new Node(97, "Anderson"));
        people.addByAge(new Node(100, "Andy"));
        people.addByAge(new Node(79, "Anfinsen"));
        people.addByAge(new Node(59, "Banerjee"));
        people.addByAge(new Node(84, "Bishop"));
        people.addByAge(new Node(78, "Bridgman"));
        people.printPeopleList();
    }

    // Print the list. Print again in reverse order once the end of the list is reached
    private void printPeopleList() {
        Node temp = start;
        while (temp.getNext() != null) {
            System.out.println(temp.getLastName() + ", " + temp.getAge());
            temp = temp.getNext();
        }
        System.out.println(temp.getLastName() + ", " + temp.getAge());
        while (temp != null) {
            System.out.println(temp.getLastName() + ", " + temp.getAge());
            temp = temp.getPrev();
        }
    }
}

Output:

Andy, 100
Anderson, 97
Bishop, 84
Anfinsen, 79
Bridgman, 78
Banerjee, 59
Banerjee, 59
Bridgman, 78
Anfinsen, 79
Bishop, 84
Anderson, 97
Andy, 100


问:
Merge rows containing similar strings using dplyr
I have a table containing the following data:

```<code>df <- tibble(
  dose = seq(10, 50, 10),
  date = c("2007-12-15", "2007-10-13","2007-10-13","2007-09-30","2007-09-30"),
  response = c(45, 67, 66, 54, 55),
  name = c("Peter,Martin", "Gale,Rebecca", "Rebecca,Gale", "Jonathan,Smith", "Smith,Jonathan")
)
</code>```

The table:

```<code># A tibble: 5 x 4
   dose date       response name
  <dbl> <chr>         <dbl> <chr>
1    10 2007-12-15       45 Peter,Martin
2    20 2007-10-13       67 Gale,Rebecca
3    30 2007-10-13       66 Rebecca,Gale
4    40 2007-09-30       54 Jonathan,Smith
5    50 2007-09-30       55 Smith,Jonathan
</code>```

One of the columns called name either has a string "FirstName,LastName" or "LastName,FirstName". I wish to merge the rows that contain the same names if they are ordered either way. For example, the rows containing Rebecca,Gale and Gale,Rebecca should merge.

While merging, I wish to get the sums of the columns dose and response and want to keep the first of the date and name entries.

Expected outcome:

```<code># A tibble: 3 x 4
   dose date       response name
  <dbl> <chr>         <dbl> <chr>
1    10 2007-12-15       45 Peter,Martin
2    50 2007-10-13      133 Gale,Rebecca
3    90 2007-09-30      109 Jonathan,Smith
</code>```

Please note that I always want to merge using the name column and not the date column because even if the example contains the same dates, my bigger table has different dates for the same name.

答:
Here is one idea.</p>

```<code>library(tidyverse)

df2 <- df %>%
  mutate(date = as.Date(date)) %>%
  mutate(name = map_chr(name, ~toString(sort(str_split(.x, ",")[[1]])))) %>%
  group_by(name) %>%
  summarize(dose = sum(dose),
            response = sum(response),
            date = first(date)) %>%
  select(names(df)) %>%
  ungroup()
df2
# # A tibble: 3 x 4
#    dose date       response name
#   <dbl> <date>        <dbl> <chr>
# 1    50 2007-10-13      133 Gale, Rebecca
# 2    90 2007-09-30      109 Jonathan, Smith
# 3    10 2007-12-15       45 Martin, Peter
</code>```

Body:
I have a table containing the following data:

df <- tibble(
  dose = seq(10, 50, 10),
  date = c("2007-12-15", "2007-10-13","2007-10-13","2007-09-30","2007-09-30"),
  response = c(45, 67, 66, 54, 55),
  name = c("Peter,Martin", "Gale,Rebecca", "Rebecca,Gale", "Jonathan,Smith", "Smith,Jonathan")
)

The table:

# A tibble: 5 x 4
   dose date       response name
  <dbl> <chr>         <dbl> <chr>
1    10 2007-12-15       45 Peter,Martin
2    20 2007-10-13       67 Gale,Rebecca
3    30 2007-10-13       66 Rebecca,Gale
4    40 2007-09-30       54 Jonathan,Smith
5    50 2007-09-30       55 Smith,Jonathan

One of the columns called name either has a string "FirstName,LastName" or "LastName,FirstName". I wish to merge the rows that contain the same names if they are ordered either way. For example, the rows containing Rebecca,Gale and Gale,Rebecca should merge.

While merging, I wish to get the sums of the columns dose and response and want to keep the first of the date and name entries.

Expected outcome:

# A tibble: 3 x 4
   dose date       response name
  <dbl> <chr>         <dbl> <chr>
1    10 2007-12-15       45 Peter,Martin
2    50 2007-10-13      133 Gale,Rebecca
3    90 2007-09-30      109 Jonathan,Smith

Please note that I always want to merge using the name column and not the date column because even if the example contains the same dates, my bigger table has different dates for the same name.

Body:
Here is one idea.

library(tidyverse)

df2 <- df %>%
  mutate(date = as.Date(date)) %>%
  mutate(name = map_chr(name, ~toString(sort(str_split(.x, ",")[[1]])))) %>%
  group_by(name) %>%
  summarize(dose = sum(dose),
            response = sum(response),
            date = first(date)) %>%
  select(names(df)) %>%
  ungroup()
df2
# # A tibble: 3 x 4
#    dose date       response name
#   <dbl> <date>        <dbl> <chr>
# 1    50 2007-10-13      133 Gale, Rebecca
# 2    90 2007-09-30      109 Jonathan, Smith
# 3    10 2007-12-15       45 Martin, Peter


问:
Accessing view controller methods inside another class [Swift]
I am using UITableViewDiffableDataSource for my tableview's dataSource by creating a UITableViewDiffableDataSource class inside my ViewController (AnimalsVC). Whenever I try to get my ViewController's data array (or any other variables/functions) from inside my data source class I get this error:

Instance member 'animalsArray' of type 'AnimalsVC' cannot be used on an instance of nested type 'AnimalsVC.DataSource'

I am not sure why I'm getting this error because my DataSource class is inside my ViewController class. Here is my code:

```<code>class AnimalsVC: UIViewController {
   var animalsArray = []

   class DataSource: UITableViewDiffableDataSource<Int, Animal> {
      override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

         let items = animalsArray //<- This is where the error occurs

         return true
      }
   }

}
</code>```

答:
I am not sure why getting this error because my DataSource class is inside my ViewController class.

That makes no difference. Declaring one class inside of another merely namespaces the inner class, i.e. it is now called AnimalsVC.DataSource. It does not cause one instance of the inner class to be able to see magically inside an instance the outer class (and indeed it is completely unclear what instances we would be talking about).
Your nesting of class declarations is useless, so you might as well not do it.

Instead, if DataSource needs to see inside AnimalsVC, do what you would normally do: give your DataSource instance a reference to the AnimalsVC instance:

```<code>class AnimalsVC: UIViewController {
    var animalsArray = // ...
}

class DataSource: UITableViewDiffableDataSource<Int, Animal> {
    weak var vc : AnimalsVC?
    // ...
}
</code>```

When you create your DataSource instance, set its vc to self. Now the DataSource can consult the instance properties of the AnimalsVC instance.

(Actually, what I do in my own code is give my UITableViewDiffableDataSource subclass a custom designated initializer. That way, I can create the data source and hand it a reference to the view controller all in one move.)

Body:
I am using UITableViewDiffableDataSource for my tableview's dataSource by creating a UITableViewDiffableDataSource class inside my ViewController (AnimalsVC). Whenever I try to get my ViewController's data array (or any other variables/functions) from inside my data source class I get this error:

Instance member 'animalsArray' of type 'AnimalsVC' cannot be used on an instance of nested type 'AnimalsVC.DataSource'

I am not sure why I'm getting this error because my DataSource class is inside my ViewController class. Here is my code:

class AnimalsVC: UIViewController {
   var animalsArray = []

   class DataSource: UITableViewDiffableDataSource<Int, Animal> {
      override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

         let items = animalsArray //<- This is where the error occurs

         return true
      }
   }

}

Body:
I am not sure why getting this error because my DataSource class is inside my ViewController class.

That makes no difference. Declaring one class inside of another merely namespaces the inner class, i.e. it is now called AnimalsVC.DataSource. It does not cause one instance of the inner class to be able to see magically inside an instance the outer class (and indeed it is completely unclear what instances we would be talking about).
Your nesting of class declarations is useless, so you might as well not do it.

Instead, if DataSource needs to see inside AnimalsVC, do what you would normally do: give your DataSource instance a reference to the AnimalsVC instance:

class AnimalsVC: UIViewController {
    var animalsArray = // ...
}

class DataSource: UITableViewDiffableDataSource<Int, Animal> {
    weak var vc : AnimalsVC?
    // ...
}

When you create your DataSource instance, set its vc to self. Now the DataSource can consult the instance properties of the AnimalsVC instance.

(Actually, what I do in my own code is give my UITableViewDiffableDataSource subclass a custom designated initializer. That way, I can create the data source and hand it a reference to the view controller all in one move.)


问:
Return function data to django template
Was an error with the API. However, didn't throw back any errors.</p>

答:
As Django Docs suggest, it is better to extend / add custom data to context, rather than re-implementing it:

```<code>def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['test'] = event_notification(source, event)
    return context
</code>```

Also, as event_notification is callable, you need to resolve it and pass result of the function to template (or template can call callables, but without arguments; or you can use custom template tags).

Title: Return function data to django template

Body:
As Django Docs suggest, it is better to extend / add custom data to context, rather than re-implementing it:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['test'] = event_notification(source, event)
    return context

Also, as event_notification is callable, you need to resolve it and pass result of the function to template (or template can call callables, but without arguments; or you can use custom template tags).


问:
Keep a radio button checked after submit
I am trying to keep a radio button checked even after submission (in Angular).</p>

```<code><label class="container" *ngFor="let content of contents; let idx = index">
    <input type="radio"
       value={{content}}
       (change)="radioChangeHandler($event)"  name="radio">
       {{content}}
    <span class="checkmark"></span>
</label>
</code>```

答:
You could make a var to hold the selected value and with the checked attribute keep it checked if the selected value is the same as the button's content.</p>

```<code>selectedValue: any;

<label class="container" *ngFor="let content of contents; let idx = index">
  <input type="radio"
  value={{content}}
  [checked]="content === selectedValue"
  (change)="radioChangeHandler($event)"  name="radio">
  {{content}}
  <span class="checkmark"></span>
</label>

radioChangeHandler(event: any) {
  this.selectedValue = event.target.value;
}
</code>```

Body:
I am trying to keep a radio button checked even after submission (in Angular).

    <input type="radio"
       value={{content}}
       (change)="radioChangeHandler($event)"  name="radio">
       {{content}}

Body:
You could make a var to hold the selected value and with the checked attribute keep it checked if the selected value is the same as the button's content.

selectedValue: any;

<label class="container" *ngFor="let content of contents; let idx = index">
  <input type="radio"
  value={{content}}
  [checked]="content === selectedValue"
  (change)="radioChangeHandler($event)"  name="radio">
  {{content}}
  <span class="checkmark"></span>
</label>

radioChangeHandler(event: any) {
  this.selectedValue = event.target.value;
}


问:
Javascript prototype method "Cannot set property"
I'm always getting Cannot set property 'saySomething' of undefined but why?
Am I making a mistake somewhere?

```<code>var Person = new Object();

Person.prototype.saySomething = function ()
{
  console.log("hello");
};

Person.saySomething();
</code>```

答:
i was trying out some code thought of posting it, might help others. </p>

```<code><script>

        var MODULE = {};
        MODULE = (function (my) {
            my.anotherMethod = function () {
                console.log("hello ");
            };

            my.newMethod = function(){
                console.log("hi new method ");

            }
            return my;
        }(MODULE));

        MODULE.anotherMethod();
        MODULE.newMethod();

    </script>
</code>```

<p>And please not var MODULE ={}, if this is not initialized with {} then it give cannot set property. </p>

Body:
I'm always getting Cannot set property 'saySomething' of undefined but why?
Am I making a mistake somewhere?

var Person = new Object();

Person.prototype.saySomething = function ()
{
  console.log("hello");
};

Person.saySomething();

Body:
i was trying out some code thought of posting it, might help others.

<script>

        var MODULE = {};
        MODULE = (function (my) {
            my.anotherMethod = function () {
                console.log("hello ");
            };

            my.newMethod = function(){
                console.log("hi new method ");

            }
            return my;
        }(MODULE));

        MODULE.anotherMethod();
        MODULE.newMethod();

    </script>

And please not var MODULE ={}, if this is not initialized with {} then it give cannot set property.


问:
Docker .NET Core API connection to SQL Server through Kerberos
Someone have success to connect a Dockerized .NET Core API 2.2 with SQL Server located in external client cloud server through Kerberos?

Here we're facing these issues:

Scenario 1:

If we use a connection string like this:

Server=tcp:SERVER_IP_ADDRESS,1433; Database=DB_NAME; User Id=USER; Password=PASSWORD;

then, it takes a long time and throws the exception like this:

SqlException: A connection was successfully established with the server, but then an error occurred during the login process. (provider: TCP Provider, error: 0 - Success)

Scenario 2:

If we use a connection string like this:

Server=tcp:SERVER_IP_ADDRESS,1433; Database=DB_NAME; User Id=USER; Password=PASSWORD; Trusted_Connection=True;

then, the exception is:

SqlException: Cannot authenticate using Kerberos.

  Ensure Kerberos has been initialized on the client with 'kinit' and a Service Principal Name has been registered for the SQL Server to allow Kerberos authentication.

  ErrorCode=InternalError, Exception=Interop+NetSecurityNative+GssApiException: GSSAPI operation failed with error - Unspecified GSS failure.

Minor code may provide more information (SPNEGO cannot find mechanisms to negotiate).

So, our hands are tied and we don't know where to run.

Can u help us?

Thanks in advance.

答:
If you don't need strictly kerberos to authenthicate, just use sql user nad password.

To do that create a user on sql server only (not in windows, use ssms to do it or sql script) and use that user, not the windows one.

It seems that you don't use sql server authentication, at least you don't use sql server user but a windows one and sql server tries to authenthicate that user in AD instead authenticating it locally on sql server.

However if you want to use Windows auth, you probably would need to use windows containers and gMSA accounts, see https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-containers/gmsa-run-container


问:
Parsing Twitter API Datestamp
I'm using the twitter API to return a list of status updates and the times they were created. It's returning the creation date in the following format:

Fri Apr 09 12:53:54 +0000 2010

What's the simplest way (with PHP or Javascript) to format this like 09-04-2010?

答:
FYI, in Java it is:

```<code>SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);
Date d = sdf.parse(dateAsString);

sdf = new SimpleDateFormat("dd-MM-yyyy");
String s = sdf.format(d);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Parsing Twitter API Datestamp

Body:
FYI, in Java it is:

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);
Date d = sdf.parse(dateAsString);

sdf = new SimpleDateFormat("dd-MM-yyyy");
String s = sdf.format(d);


问:
How to exclude some data on a SQL query depending on it's different values?
I have the following 2 tables:

```<code>create table Director (

    id_director int,
    name varchar(255),
    primary key (id_director)
);

create table Movies (

    id_movie int,
    id_director int,
    title varchar(255),
    year int,
    primary key (id_movie),
    foreign key (id_director) references Director (id_director)
);
</code>```

Some data has been already inserted on this tables. Imagine the data is:

Table Director

```<code>id_director       name
-------------------------
   1               Charles
   2               Jack
   3               Katia
   4               David
</code>```

Table Movies

```<code>id_movie      id_director     title        year
------------------------------------------------
   1              2            title1      1999
   2              1            title2      2011
   3              1            title3      2019
   4              3            title4      2019
   5              4            title5      1968
   6              3            title6      2020
   7              2            title7      1977
   8              4            title8      2004
   9              1            title9      2020
</code>```

I want to execute a SELECT clause in order to filter the directors that it's first movie its from 2019. Note from the example that only the director with the id_director = 3 meets the requirement as has made 2 films, one on 2019 and the other one on 2020.

How can I do this?

The output I would like to get is:

```<code>id_director          name
------------------------------
    3                Katia
</code>```

I have tried this, but it's obviously wrong because some directors that made films before 2019, have also made films after 2019.

```<code>select director.id_director, director.name from director, movies
where director.id_director = movie.id_director and year = 2019
group by (name);
</code>```

I'm using MySQL and I'm supposing I can do this with an IN / NOT IN subquery (but how)?

答:
You can use correlated subquery : </p>

```<code>select d.*
from director d
where 2019 = (select min(m.year) from movies m where m.id_director = d.id_director);
</code>```

Body:
I have the following 2 tables:

create table Director (

    id_director int,
    name varchar(255),
    primary key (id_director)
);

create table Movies (

    id_movie int,
    id_director int,
    title varchar(255),
    year int,
    primary key (id_movie),
    foreign key (id_director) references Director (id_director)
);

Some data has been already inserted on this tables. Imagine the data is:

Table Director

id_director       name
-------------------------
   1               Charles
   2               Jack
   3               Katia
   4               David

Table Movies

id_movie      id_director     title        year
------------------------------------------------
   1              2            title1      1999
   2              1            title2      2011
   3              1            title3      2019
   4              3            title4      2019
   5              4            title5      1968
   6              3            title6      2020
   7              2            title7      1977
   8              4            title8      2004
   9              1            title9      2020

I want to execute a SELECT clause in order to filter the directors that it's first movie its from 2019. Note from the example that only the director with the id_director = 3 meets the requirement as has made 2 films, one on 2019 and the other one on 2020.

How can I do this?

The output I would like to get is:

id_director          name
------------------------------
    3                Katia

I have tried this, but it's obviously wrong because some directors that made films before 2019, have also made films after 2019.

select director.id_director, director.name from director, movies
where director.id_director = movie.id_director and year = 2019
group by (name);

I'm using MySQL and I'm supposing I can do this with an IN / NOT IN subquery (but how)?

Body:
You can use correlated subquery :

select d.*
from director d
where 2019 = (select min(m.year) from movies m where m.id_director = d.id_director);


问:
Stop the page refreshing when the session has not ended ASP.NET MVC C#
I wrote code to refresh the page when the page stays idle for 2 min (with stackoverflow help). The code works fine, but my problem is when the user is working on the page the application still refreshes when the session ends. I need help to reset the session in my code to stop the application resetting when the page is not idle.

Web.config

```<code><system.web>
   <sessionState timeout="2" />
</system.web>
</code>```

_Layout Page

```<code><script>
  //session end reset page
  var sessionTimeoutWarning = @Session.Timeout- 1;

  var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;

  setTimeout('SessionEnd()', sTimeout);

  function SessionEnd() {
    window.location = "/Home/SessionExpired";
  }
</script>
</code>```

Home Controller

```<code>public ActionResult SessionExpired()
{
    Session["conectionstring"] = null;
    Session["patientid"] = null;
    Session.Clear();
    Session.Abandon();
    return RedirectToAction("Index", "Home");
}
</code>```

答:
you can try slidingExpression=true in web.config file

<authentication mode="Forms">
  <forms loginUrl="login.aspx"
    name="loginPage"
    cookieless="UseCookies"
    slidingExpiration="true" />
</authentication>```

Body:
I wrote code to refresh the page when the page stays idle for 2 min (with stackoverflow help). The code works fine, but my problem is when the user is working on the page the application still refreshes when the session ends. I need help to reset the session in my code to stop the application resetting when the page is not idle.

Web.config

<system.web>
   <sessionState timeout="2" />
</system.web>

_Layout Page

Home Controller

public ActionResult SessionExpired()
{
    Session["conectionstring"] = null;
    Session["patientid"] = null;
    Session.Clear();
    Session.Abandon();
    return RedirectToAction("Index", "Home");
}


问:
Is there a way to count the number of products that have a title but no price?
I am trying to count the number of products that have a title but do not have a price, the database is a database full of products from a store and there are thousands of products in the database, I am trying to count all of the items that have a product title but also does not state the product price

If anyone understands this then any help would be appreciated

答:
You can try using $exists in mongo query, a query sample is shown below:

```
db.getCollection('your_products_collection').find({'product_title': { $exists: true}, 'product_price' : {$exists : false}}).count()
```

Replace your collection names and column names in the above query

Body:
You can try using $exists in mongo query, a query sample is shown below:

db.getCollection('your_products_collection').find({'product_title': { $exists: true}, 'product_price' : {$exists : false}}).count()

Replace your collection names and column names in the above query


问:
How do you access a Sequelize instance in a VueJS component?
I've an Electron/Vue app built with electron-vue, but I can't work out how to access a Sequelize instance which is initialised in main.js, in the component .vue files.

The src/renderer/main.js file contains the usual imports:

```<code>import Vue from 'vue'
import axios from 'axios'

import App from './App'
import router from './router'
import store from './store'

import { Sequelize } from 'sequelize'
import mysql2 from 'mysql2'

// create sequelize instance as normal
let db = new Sequelize(
  'database', 'user', 'password', {
    host: '1.2.3.4',
    dialect: 'mysql',
    dialectModule: mysql2
})

new Vue({
  components: { App },
  router,
  store,
  template: '<App/>'
}).$mount('#app')
</code>```

Now in a src/renderer/components/Settings.vue file I'd like to be able to make a database call, for example:

```<code><template>
...
  <button @click="testDatabaseConnection()">Test Database</button>
...
</template>

<script>
export default {
    name: 'Settings',
    methods: {
        navigate(route) {
            this.$router.push(route);
        },

        testDatabaseConnection() {
            // access the Sequelize instance
        }
    }
}
</script>
</code>```

Am I doing this in the right/wrong place?  How would you put the db variable into a scope that the Vue component can access?  Are there any best practices here that I should read up on?

答:
You can import Javascript files/vars/objects by using the import keyword in the component .vue file.

For example:

Settings.vue

```<code><template>
 ...
</template>

<script>
import db from '../../database/connection'

export default {
    name: 'Settings',
    methods: {
        async testDbConnection() {
            // Can access the db object from the import statement
            let result = await db.sequelize.query(...)
        },

</script>
</code>```

Body:
I've an Electron/Vue app built with electron-vue, but I can't work out how to access a Sequelize instance which is initialised in main.js, in the component .vue files.

The src/renderer/main.js file contains the usual imports:

import Vue from 'vue'
import axios from 'axios'

import App from './App'
import router from './router'
import store from './store'

import { Sequelize } from 'sequelize'
import mysql2 from 'mysql2'

// create sequelize instance as normal
let db = new Sequelize(
  'database', 'user', 'password', {
    host: '1.2.3.4',
    dialect: 'mysql',
    dialectModule: mysql2
})

new Vue({
  components: { App },
  router,
  store,
  template: '<App/>'
}).$mount('#app')

Now in a src/renderer/components/Settings.vue file I'd like to be able to make a database call, for example:

<template>
...
  <button @click="testDatabaseConnection()">Test Database</button>
...
</template>

Am I doing this in the right/wrong place?  How would you put the db variable into a scope that the Vue component can access?  Are there any best practices here that I should read up on?

Body:
You can import Javascript files/vars/objects by using the import keyword in the component .vue file.

For example:

Settings.vue

<template>
 ...
</template>

<script>
import db from '../../database/connection'

export default {
    name: 'Settings',
    methods: {
        async testDbConnection() {
            // Can access the db object from the import statement
            let result = await db.sequelize.query(...)
        },

</script>


问:
Why is a Spatial Data Frame obtained from OSM/Nominatim invalid?
I want to get plottable spatial (boundary/polygon) data from OpenStreetMap using the nominatim R package.

The nominatim::osm_search_spatial request seems to work successfully but the resulting data, despite being found as a "SpatialPolygonsDataFrame", is shown as invalid and I am not able to get it to plot with plot or tmap. It also seems to be missing its CRS.

I am not sure if I am missing a step or two, or if there is indeed something wrong with the data that is retrieved from OSM (seems unlikely, but possible).

Edit: There seems to be a problem with the latitudes and longitudes in the data received so this question has been edited with a new reprex. It looks like it might need to be asked on a GIS forum rather than here in R, in fact.

Deleted previous reprex showing superfluous steps and results (moved to gist here) - this is what Eugene Chong in his first reply was responding to.

Here's my new, more focused, reprex showing the problem (OSM API key hidden). You can see that the polygon @coords leap from the first point at -1,-1 right up to 53,53 for the second point onwards, hence the diagonal line that is plotted.

library(nominatim)
#> Data (c) OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright
#> Nominatim Usage Policy: http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy
#> MapQuest Nominatim Terms of Use: http://info.mapquest.com/terms-of-use/
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.3, PROJ 4.9.3
library(tmap)
library(tibble)

# get OSM search results for Ashfield district (UK)
ashfield <- nominatim::osm_search_spatial("Ashfield", limit = 1, key = $my_osm_api_key)
class(ashfield)
#> [1] "list"

# extract SPDF from list
ashfield <- ashfield[[1]]
class(ashfield)
#> [1] "SpatialPolygonsDataFrame"
#> attr(,"package")
#> [1] "sp"

# Convert to an SF object and try again
ashfield_sf <- sf::st_as_sf(ashfield)
class(ashfield_sf)
#> [1] "sf"         "data.frame"

# set CRS (thanks to Eugene Chong)
st_crs(ashfield_sf) <- 4326
tmap::qtm(ashfield_sf)
#> Warning: The shape ashfield_sf is invalid. See sf::st_is_valid
```

<p><img src="https://i.imgur.com/1EqUgK3.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code>glimpse(ashfield@data)
#> Observations: 1
#> Variables: 15
#> $ place_id     <chr> "186877616"
#> $ licence      <chr> "Data © OpenStreetMap contributors, ODbL 1.0. https://...
#> $ osm_type     <chr> "relation"
#> $ osm_id       <chr> "154043"
#> $ lat          <dbl> 53.08977
#> $ lon          <dbl> -1.251877
#> $ display_name <chr> "Ashfield, Nottinghamshire, East Midlands, England, Un...
#> $ class        <chr> "boundary"
#> $ type         <chr> "administrative"
#> $ importance   <dbl> 0.2116014
#> $ icon         <chr> "http://ip-10-98-176-55.mq-us-east-1.ec2.aolcloud.net/...
#> $ bbox_left    <fct> 53.0080617
#> $ bbox_top     <fct> 53.1714343
#> $ bbox_right   <fct> -1.3445928
#> $ bbox_bottom  <fct> -1.1642542
head(ashfield@polygons[[1]]@Polygons[[1]]@coords)
#>           [,1]      [,2]
#> [1,] -1.344593 -1.344409
#> [2,] 53.063537 53.063260
#> [3,] 53.064985 53.063764
#> [4,] 53.065520 53.065521
#> [5,] 53.065553 53.065526
#> [6,] 53.065725 53.065656
ashfield_sf$geometry
#> Geometry set for 1 feature
#> geometry type:  POLYGON
#> dimension:      XY
#> bbox:           xmin: -1.344593 ymin: -1.344593 xmax: 53.17143 ymax: 53.17142
#> epsg (SRID):    4326
#> proj4string:    +proj=longlat +datum=WGS84 +no_defs
#> POLYGON ((-1.344593 -1.344409, 53.06354 53.0632...
</code>```

Created on 2020-02-20 by the reprex package (v0.3.0)

Next step: I am going to try a direct download from nominatim rather than via the R package, and see what I get.

答:
Using st_make_valid() from the lwgeom package makes the warning go away:

Add WGS84 as the crs.

```<code>ashfield_sf <- sf::st_as_sf(ashfield)
st_crs(ashfield_sf) <- 4326

sf::st_is_valid(ashfield_sf, reason = TRUE)

[1] "Self-intersection[53.0709899483331 53.0709561246412]"
</code>```

Use st_make_valid()

```<code>library(lwgeom)
ashfield_sf_2 <- st_make_valid(ashfield_sf)
sf::st_is_valid(ashfield_sf_2, reason = TRUE)

[1] "Valid Geometry"
</code>```

As far as the geometry itself, though, it's still just a line extending from Russia to the west coast of Africa, not a polygon of Ashfield as would be expected.

And as far as why the geometry was invalid in the first place, I'm not sure, but the self-intersection error suggests that the polygon crossed over itself at some point (like a bowtie would).  See this post, which has more discussion of valid and invalid geometries: https://www.r-spatial.org/r/2017/03/19/invalid.html

Body:
I want to get plottable spatial (boundary/polygon) data from OpenStreetMap using the nominatim R package.

The nominatim::osm_search_spatial request seems to work successfully but the resulting data, despite being found as a "SpatialPolygonsDataFrame", is shown as invalid and I am not able to get it to plot with plot or tmap. It also seems to be missing its CRS.

I am not sure if I am missing a step or two, or if there is indeed something wrong with the data that is retrieved from OSM (seems unlikely, but possible).

Edit: There seems to be a problem with the latitudes and longitudes in the data received so this question has been edited with a new reprex. It looks like it might need to be asked on a GIS forum rather than here in R, in fact.

Deleted previous reprex showing superfluous steps and results (moved to gist here) - this is what Eugene Chong in his first reply was responding to.

Here's my new, more focused, reprex showing the problem (OSM API key hidden). You can see that the polygon @coords leap from the first point at -1,-1 right up to 53,53 for the second point onwards, hence the diagonal line that is plotted.

library(nominatim)
#> Data (c) OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright
#> Nominatim Usage Policy: http://wiki.openstreetmap.org/wiki/Nominatim_usage_policy
#> MapQuest Nominatim Terms of Use: http://info.mapquest.com/terms-of-use/
library(sf)
#> Linking to GEOS 3.6.1, GDAL 2.2.3, PROJ 4.9.3
library(tmap)
library(tibble)

# get OSM search results for Ashfield district (UK)
ashfield <- nominatim::osm_search_spatial("Ashfield", limit = 1, key = $my_osm_api_key)
class(ashfield)
#> [1] "list"

# extract SPDF from list
ashfield <- ashfield[[1]]
class(ashfield)
#> [1] "SpatialPolygonsDataFrame"
#> attr(,"package")
#> [1] "sp"

# Convert to an SF object and try again
ashfield_sf <- sf::st_as_sf(ashfield)
class(ashfield_sf)
#> [1] "sf"         "data.frame"

# set CRS (thanks to Eugene Chong)
st_crs(ashfield_sf) <- 4326
tmap::qtm(ashfield_sf)
#> Warning: The shape ashfield_sf is invalid. See sf::st_is_valid

glimpse(ashfield@data)
#> Observations: 1
#> Variables: 15
#> $ place_id     <chr> "186877616"
#> $ licence      <chr> "Data © OpenStreetMap contributors, ODbL 1.0. https://...
#> $ osm_type     <chr> "relation"
#> $ osm_id       <chr> "154043"
#> $ lat          <dbl> 53.08977
#> $ lon          <dbl> -1.251877
#> $ display_name <chr> "Ashfield, Nottinghamshire, East Midlands, England, Un...
#> $ class        <chr> "boundary"
#> $ type         <chr> "administrative"
#> $ importance   <dbl> 0.2116014
#> $ icon         <chr> "http://ip-10-98-176-55.mq-us-east-1.ec2.aolcloud.net/...
#> $ bbox_left    <fct> 53.0080617
#> $ bbox_top     <fct> 53.1714343
#> $ bbox_right   <fct> -1.3445928
#> $ bbox_bottom  <fct> -1.1642542
head(ashfield@polygons[[1]]@Polygons[[1]]@coords)
#>           [,1]      [,2]
#> [1,] -1.344593 -1.344409
#> [2,] 53.063537 53.063260
#> [3,] 53.064985 53.063764
#> [4,] 53.065520 53.065521
#> [5,] 53.065553 53.065526
#> [6,] 53.065725 53.065656
ashfield_sf$geometry
#> Geometry set for 1 feature
#> geometry type:  POLYGON
#> dimension:      XY
#> bbox:           xmin: -1.344593 ymin: -1.344593 xmax: 53.17143 ymax: 53.17142
#> epsg (SRID):    4326
#> proj4string:    +proj=longlat +datum=WGS84 +no_defs
#> POLYGON ((-1.344593 -1.344409, 53.06354 53.0632...

Created on 2020-02-20 by the reprex package (v0.3.0)

Next step: I am going to try a direct download from nominatim rather than via the R package, and see what I get.

Body:
Using st_make_valid() from the lwgeom package makes the warning go away:

Add WGS84 as the crs.

ashfield_sf <- sf::st_as_sf(ashfield)
st_crs(ashfield_sf) <- 4326

sf::st_is_valid(ashfield_sf, reason = TRUE)

[1] "Self-intersection[53.0709899483331 53.0709561246412]"

Use st_make_valid()

library(lwgeom)
ashfield_sf_2 <- st_make_valid(ashfield_sf)
sf::st_is_valid(ashfield_sf_2, reason = TRUE)

[1] "Valid Geometry"

As far as the geometry itself, though, it's still just a line extending from Russia to the west coast of Africa, not a polygon of Ashfield as would be expected.

And as far as why the geometry was invalid in the first place, I'm not sure, but the self-intersection error suggests that the polygon crossed over itself at some point (like a bowtie would).  See this post, which has more discussion of valid and invalid geometries: https://www.r-spatial.org/r/2017/03/19/invalid.html


问:
iOS Application: Firebase Dynamic Links are not working with latest Pod file
We integrated the latest Dynamic link Pod to our iOS application.

Whenever we open the link of firebase no function in triggered in our Appdelegate.
Check the method we implemented in App delegate

```<code>    func application(_ application: UIApplication, continue userActivity: NSUserActivity,     restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
 DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
     if(dynamiclink != nil){
         let aStr = dynamiclink!.url!.absoluteString
         print("reopen url :\(String(describing: aStr.removingPercentEncoding))")
         let decodeUrl = aStr.removingPercentEncoding!
     }
 }
 return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
 print("got link1")
 print(" first time url :\(url)")
 let aStr = url.absoluteString
 print("url :\(String(describing: aStr.removingPercentEncoding))")
 let decodeUrl = aStr.removingPercentEncoding!
 if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) {
     if dynamicLink.url != nil{
         let aStr = dynamicLink.url!.absoluteString
         let decodUrl = aStr.removingPercentEncoding!
     }
 }
return true }
</code>```

We are using a custom domain in our application, we added them in info.plist too

```<code><key>FirebaseDynamicLinksCustomDomains</key>
<array>
    <string>https://page.google.com/newrequest</string>
</array>
<key>FirebaseAppDelegateProxyEnabled</key>
<string>YES</string>
</code>```

We added a dynamic link URL to our AssociatedDomains with a prefix of app links like applinks:page.google.com

答:
In iOS 13, AppDelegate methods will not call. Add SceneDelegate to your project.  Add
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
 print(userActivity.webpageURL)
}

we will get userActivity.webpageURL will be our long dynamic link.

Body:
We integrated the latest Dynamic link Pod to our iOS application.

Whenever we open the link of firebase no function in triggered in our Appdelegate.
Check the method we implemented in App delegate

    func application(_ application: UIApplication, continue userActivity: NSUserActivity,     restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
 DynamicLinks.dynamicLinks().handleUniversalLink(userActivity.webpageURL!) { (dynamiclink, error) in
     if(dynamiclink != nil){
         let aStr = dynamiclink!.url!.absoluteString
         print("reopen url :\(String(describing: aStr.removingPercentEncoding))")
         let decodeUrl = aStr.removingPercentEncoding!
     }
 }
 return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
 print("got link1")
 print(" first time url :\(url)")
 let aStr = url.absoluteString
 print("url :\(String(describing: aStr.removingPercentEncoding))")
 let decodeUrl = aStr.removingPercentEncoding!
 if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) {
     if dynamicLink.url != nil{
         let aStr = dynamicLink.url!.absoluteString
         let decodUrl = aStr.removingPercentEncoding!
     }
 }
return true }

We are using a custom domain in our application, we added them in info.plist too

<key>FirebaseDynamicLinksCustomDomains</key>
<array>
    <string>https://page.google.com/newrequest</string>
</array>
<key>FirebaseAppDelegateProxyEnabled</key>
<string>YES</string>

We added a dynamic link URL to our AssociatedDomains with a prefix of app links like applinks:page.google.com


问:
inverted reindent.py (spaces to tabs)
afaik reindent.py (available in the standard python examples) has a tokenizer allowing it to do smart reindenting based on the indentation level rather than on the number of spaces osed per level (which can vary in bad code)

unfortunately it enforces 4-space indentation, but i want tabs, because 1 tab == 1 indentation level is more logical than x spaces.

this question has no suitable answer:

i don’t care about pep-8 (i know how to write my code)

vim is installed, but :retab! doesn’t handle inconsistent indentation

all tools convert spaces used for alignment (!= indentation) to tabs, too.

one way would be to use reindent.py and afterwards doing sth. like:

```<code>#!/usr/bin/env python3
from re import compile
from sys import argv

spaces = compile("^ +")
multistr = False
for line in open(argv[1]):
    num = 0
    if not multistr:
        try:
            num = len(spaces.search(line).group(0)) // 4
        except AttributeError:
            pass
    print("\t"*num + line[num*4:-1])
    if line.count('"""') % 2 == 1:
        multistr = not multistr
</code>```

but that’s rather hacky. is there no non-zealot version of reindent.py?

PS: why suggests the highlighting that // 4 is a comment instead of a truncating division?

The following script should do the trick, but either i missed sth., or tokenize is buggy (or the example in the python documentation)

```<code>#!/usr/bin/env python3

from tokenize import *
from sys import argv

f = open(argv[1])
def readline():
    return bytes(f.readline(), "utf-8")

tokens = []
ilvl=0
for token in tokenize(readline):
    if token.type == INDENT:
        ilvl+=1
        tokens.append((INDENT, "\t"*ilvl))
    else:
        if token.type == DEDENT:
            ilvl-=1
        tokens.append(token)

print(untokenize(tokens).decode('utf-8'))
</code>```

答:
Using sed in unix you could get it with one line:

```<code>sed -r ':f; s|^(\t*)\s{4}|\1\t|g; t f' file
</code>```

edit: this will work for spaces at beginning of the line only.

Title: inverted reindent.py (spaces to tabs)

Body:
afaik reindent.py (available in the standard python examples) has a tokenizer allowing it to do smart reindenting based on the indentation level rather than on the number of spaces osed per level (which can vary in bad code)

unfortunately it enforces 4-space indentation, but i want tabs, because 1 tab == 1 indentation level is more logical than x spaces.

this question has no suitable answer:

i don’t care about pep-8 (i know how to write my code)

vim is installed, but :retab! doesn’t handle inconsistent indentation

all tools convert spaces used for alignment (!= indentation) to tabs, too.

one way would be to use reindent.py and afterwards doing sth. like:

#!/usr/bin/env python3
from re import compile
from sys import argv

spaces = compile("^ +")
multistr = False
for line in open(argv[1]):
    num = 0
    if not multistr:
        try:
            num = len(spaces.search(line).group(0)) // 4
        except AttributeError:
            pass
    print("\t"*num + line[num*4:-1])
    if line.count('"""') % 2 == 1:
        multistr = not multistr

but that’s rather hacky. is there no non-zealot version of reindent.py?

PS: why suggests the highlighting that // 4 is a comment instead of a truncating division?

The following script should do the trick, but either i missed sth., or tokenize is buggy (or the example in the python documentation)

#!/usr/bin/env python3

from tokenize import *
from sys import argv

f = open(argv[1])
def readline():
    return bytes(f.readline(), "utf-8")

tokens = []
ilvl=0
for token in tokenize(readline):
    if token.type == INDENT:
        ilvl+=1
        tokens.append((INDENT, "\t"*ilvl))
    else:
        if token.type == DEDENT:
            ilvl-=1
        tokens.append(token)

print(untokenize(tokens).decode('utf-8'))

Body:
Using sed in unix you could get it with one line:

sed -r ':f; s|^(\t*)\s{4}|\1\t|g; t f' file

edit: this will work for spaces at beginning of the line only.