答:
The issue is due to the number of digit in the number :

for example, for 1221, start and end will never meet in the middle :

iteration 1 : start = 0, end = 3

iteration 2 : start = 1, end = 2

iteration 3 : start = 2, end = 1
...

The fact that "it works" when you do :

```<code> if(str.charAt(start++) < str.charAt(end--)) return false;
</code>```

is by chance.

You should just change the while condition to :

```<code>while(start < end) {
</code>```

Title: while loop condtion, difference between not equal and greater than

Body:
I'm doing a problem checking whether an integer is a palindrome. The logic is I convert it to string and then set the index of the first and the last. I loop through each first and last index and the values should match if they are palindrome. in the loop I increase the first index by one, I decrease the last index by one. So eventually they will meet in the half. The loop condition I originally had was if the indexes of both are not the same. but this gives me String index out of bounds exception. But then when I changed it to loop through as long as start is smaller than the end, it works.

public boolean isPalindrome(int x) {

        if(x < 0) {
            return false;
        }
        String val = String.valueOf(x);

        int end = val.length()-1;
        int start = 0;
        while(start != end) {
            if(val.charAt(start) != val.charAt(end)) {
                return false;
            }
            start++;
            end--;
        }

        return true;
    }
    }

it works when I do

 if(str.charAt(start++) < str.charAt(end--)) return false;

Body:
The issue is due to the number of digit in the number :

for example, for 1221, start and end will never meet in the middle :

iteration 1 : start = 0, end = 3

iteration 2 : start = 1, end = 2

iteration 3 : start = 2, end = 1
...

The fact that "it works" when you do :

 if(str.charAt(start++) < str.charAt(end--)) return false;

is by chance.

You should just change the while condition to :

while(start < end) {


来源: stackexchange

问:
Types imported from node module becomes `any` after compilation
I'm trying to use some of the types from another package in my project API because I'm passing those params down to the mentioned package.
Here is what I'm doing:

```<code>import type { Column, CellProps } from "react-table";

export const foo = (): Column => {...}
</code>```

Everything works fine in the package, but when I build it using rollup, the generated .d.ts file looks like the following and the types become any when used in any consumer package (and when I hover over them in the .d.ts file):

```<code>import type { Column, CellProps } from "react-table";

export declare const foo: () => Column;
</code>```

P.S.
I'm using rollup for removing the declarations from the code and tsc --emitDeclarationOnly for generating those .d.ts files.

P.S.2.
I have the react-table package in my dependencies which provides its built-in types (I'm not using any @types/* package)

答:
This isn't quite right:

I have the react-table package in my dependencies which provides its built-in types (I'm not using any @types/* package)

The react-table package does not bundle its types, but rather provides them on DefinitelyTyped, via @types/react-table. If you want the consumer package to have these types, you have a few options.

One is to make @types/react-table a dependency of your project:

```<code># in your project
npm install @types/react-table
</code>```

Then when the consumer installs your module, they'll pull in @types/react-table as a transitive dependency. This has the downside that JavaScript users of your package will have @types dependencies that they don't need.

Another is to have the consumer package depend on the react-table types via:

```<code># in consumer project
npm install -D @types/react-table
</code>```

The downside of this is that your consumers have to manage this dependency themselves.

A third option is to bundle the dependency. This is a good choice if Column and CellProps are simple interfaces. You could inline their definitions like so:

```<code>// in your project's TS source
export interface Column {
  // ...
}

export interface CellProps {
  // ...
}

export const foo = (): Column => {...}
</code>```

Assuming your declarations are compatible with the upstream declarations in react-table, TypeScript's duck typing will make this all work out.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use some of the types from another package in my project API because I'm passing those params down to the mentioned package.
Here is what I'm doing:

import type { Column, CellProps } from "react-table";

export const foo = (): Column => {...}

Everything works fine in the package, but when I build it using rollup, the generated .d.ts file looks like the following and the types become any when used in any consumer package (and when I hover over them in the .d.ts file):

import type { Column, CellProps } from "react-table";

export declare const foo: () => Column;

P.S.
I'm using rollup for removing the declarations from the code and tsc --emitDeclarationOnly for generating those .d.ts files.

P.S.2.
I have the react-table package in my dependencies which provides its built-in types (I'm not using any @types/* package)

Body:
This isn't quite right:

I have the react-table package in my dependencies which provides its built-in types (I'm not using any @types/* package)

The react-table package does not bundle its types, but rather provides them on DefinitelyTyped, via @types/react-table. If you want the consumer package to have these types, you have a few options.

One is to make @types/react-table a dependency of your project:

# in your project
npm install @types/react-table

Then when the consumer installs your module, they'll pull in @types/react-table as a transitive dependency. This has the downside that JavaScript users of your package will have @types dependencies that they don't need.

Another is to have the consumer package depend on the react-table types via:

# in consumer project
npm install -D @types/react-table

The downside of this is that your consumers have to manage this dependency themselves.

A third option is to bundle the dependency. This is a good choice if Column and CellProps are simple interfaces. You could inline their definitions like so:

// in your project's TS source
export interface Column {
  // ...
}

export interface CellProps {
  // ...
}

export const foo = (): Column => {...}

Assuming your declarations are compatible with the upstream declarations in react-table, TypeScript's duck typing will make this all work out.


问:
How to prevent Editor to go behind the keyboard in Xamarin.Forms?
I have a Chat app. Currently, there is an Entry control for add chat text. Now I want to provide multiline Entry, same like Whatsapp.

If user type more than one line, it should automatic wrap the text to next line.

If user click on Nextline button in mobile keyboard, it should go to next line.

Height of Entry should be automatically increase upto 3 line and it should also decrease if user remove text.

To do that I have tried to replace Entry with Editor and implement following functionality.

1- Put an Editor in place of Entry.
2- Implement a functionality that keep keyboard open until user click on Message list screen or back button.

Now I am trying to implement auto height functioanlity but when user try to type, Editor goes behind the keyboard. Can anybody please suggest me how to keep Editor open and auto size?

Current code:

XAML:

```<code><Grid x:Name="MessageControls" RowSpacing="1" ColumnSpacing="2" Padding="5"
 Grid.Row="1" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="auto" />
    </Grid.ColumnDefinitions>
    <local:ChatEditorWithPlaceholder  x:Name="txtMessage" Grid.Column="0"  TextChanged="EnableSend" Text="{Binding OutGoingText}"/>
    <Frame x:Name="SendButton" Grid.Column="1" Margin= "0" Padding="0" HasShadow="false" HeightRequest="25"
BackgroundColor="Transparent" HorizontalOptions="FillAndExpand">
        <Frame.GestureRecognizers>
            <TapGestureRecognizer Tapped="SendMessage_Click" NumberOfTapsRequired="1" />
        </Frame.GestureRecognizers>
        <Label Text="Send" x:Name="sendButton" TextColor="#1f88b7" HeightRequest="20"
    HorizontalOptions="Center" VerticalOptions="Center"/>
    </Frame>
</Grid>
</code>```

Editor

```<code>public class ChatEditorWithPlaceholder : Editor
{
    public ChatEditorWithPlaceholder()
    {
        this.TextChanged += (sender, e) => { this.InvalidateMeasure(); };
    }
}
</code>```

Editor Renderer:

```<code>public class ChatEditorRenderer : EditorRenderer
{
    protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);
    }
}

protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{
    base.OnElementChanged(e);
    if(Control != null) {
        Control.ScrollEnabled = false;
    }
    var element = this.Element as ChatEditorWithPlaceholder;

    Control.InputAccessoryView = null;
    Control.ShouldEndEditing += DisableHidingKeyboard;

    MessagingCenter.Subscribe<ConversationPage>(this, "FocusKeyboardStatus", (sender) =>
    {

        if (Control != null)
        {
            Control.ShouldEndEditing += EnableHidingKeyboard;
        }

        MessagingCenter.Unsubscribe<ConversationPage>(this, "FocusKeyboardStatus");
    });
}
private bool DisableHidingKeyboard(UITextView textView)
{
    return false;
}

private bool EnableHidingKeyboard(UITextView textView)
{
    return true;
}
</code>```

Screenshots:

答:
You can try to change this line:

```<code><local:ChatEditorWithPlaceholder  x:Name="txtMessage" Grid.Column="0"  TextChanged="EnableSend" Text="{Binding OutGoingText}"/>
</code>```

For this one:

```<code><Editor x:Name="txtMessage" Grid.Column="0" AutoSize="TextChanges" TextChanged="EnableSend" Text="{Binding OutGoingText}"/>
</code>```

Body:
I have a Chat app. Currently, there is an Entry control for add chat text. Now I want to provide multiline Entry, same like Whatsapp.

If user type more than one line, it should automatic wrap the text to next line.

If user click on Nextline button in mobile keyboard, it should go to next line.

Height of Entry should be automatically increase upto 3 line and it should also decrease if user remove text.

To do that I have tried to replace Entry with Editor and implement following functionality.

1- Put an Editor in place of Entry.
2- Implement a functionality that keep keyboard open until user click on Message list screen or back button.

Now I am trying to implement auto height functioanlity but when user try to type, Editor goes behind the keyboard. Can anybody please suggest me how to keep Editor open and auto size?

Current code:

XAML:

<Grid x:Name="MessageControls" RowSpacing="1" ColumnSpacing="2" Padding="5"
 Grid.Row="1" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="auto" />
    </Grid.ColumnDefinitions>
    <local:ChatEditorWithPlaceholder  x:Name="txtMessage" Grid.Column="0"  TextChanged="EnableSend" Text="{Binding OutGoingText}"/>
    <Frame x:Name="SendButton" Grid.Column="1" Margin= "0" Padding="0" HasShadow="false" HeightRequest="25"
BackgroundColor="Transparent" HorizontalOptions="FillAndExpand">
        <Frame.GestureRecognizers>
            <TapGestureRecognizer Tapped="SendMessage_Click" NumberOfTapsRequired="1" />
        </Frame.GestureRecognizers>

    </Frame>
</Grid>

Editor

public class ChatEditorWithPlaceholder : Editor
{
    public ChatEditorWithPlaceholder()
    {
        this.TextChanged += (sender, e) => { this.InvalidateMeasure(); };
    }
}

Editor Renderer:

public class ChatEditorRenderer : EditorRenderer
{
    protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);
    }
}

protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{
    base.OnElementChanged(e);
    if(Control != null) {
        Control.ScrollEnabled = false;
    }
    var element = this.Element as ChatEditorWithPlaceholder;

    Control.InputAccessoryView = null;
    Control.ShouldEndEditing += DisableHidingKeyboard;

    MessagingCenter.Subscribe<ConversationPage>(this, "FocusKeyboardStatus", (sender) =>
    {

        if (Control != null)
        {
            Control.ShouldEndEditing += EnableHidingKeyboard;
        }

        MessagingCenter.Unsubscribe<ConversationPage>(this, "FocusKeyboardStatus");
    });
}
private bool DisableHidingKeyboard(UITextView textView)
{
    return false;
}

private bool EnableHidingKeyboard(UITextView textView)
{
    return true;
}

Screenshots:

Body:
You can try to change this line:

<local:ChatEditorWithPlaceholder  x:Name="txtMessage" Grid.Column="0"  TextChanged="EnableSend" Text="{Binding OutGoingText}"/>

For this one:

<Editor x:Name="txtMessage" Grid.Column="0" AutoSize="TextChanges" TextChanged="EnableSend" Text="{Binding OutGoingText}"/>


问:
Javascript modified array before group by
i am trying to modified array before groupBy

i have this array

```<code>[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]
</code>```

i am trying to modified as per count value has in object value count 3 + 2 = 5 object should in array

witch function i use ? for output array like this

```<code>[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]
</code>```

答:
If your intention is to clone the object in the array the number of times the count inside it, here is the solution.

```<code>let boxes = [
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]

let newBoxes = [];

boxes.forEach(box =>
 {
   let count = box.count;
    while(count > 0)
    {
      newBoxes.push(box);
      count--;
     }
    }
);
</code>```

Your newBoxes will have the expected output.

```<code>[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]
</code>```

Body:
i am trying to modified array before groupBy

i have this array

[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]

i am trying to modified as per count value has in object value count 3 + 2 = 5 object should in array

witch function i use ? for output array like this

[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]

Body:
If your intention is to clone the object in the array the number of times the count inside it, here is the solution.

let boxes = [
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]

let newBoxes = [];

boxes.forEach(box =>
 {
   let count = box.count;
    while(count > 0)
    {
      newBoxes.push(box);
      count--;
     }
    }
);

Your newBoxes will have the expected output.

[
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxOne',
        count: 3
    },
    {
        name: 'BoxTwo',
        count: 2
    },
    {
        name: 'BoxTwo',
        count: 2
    },
]


问:
TypeError: expected string or bytes-like object Tqdm
I have gone through several sources in stackoverflow regarding this issue, but couldn't resolve it.
Thus I have posted it here, kindly resolve.

```<code># Combining all the above statemennts
from tqdm import tqdm
Other_skill = []
# tqdm is for printing the status bar
for sentance in tqdm(project_data['Other skills'].values):
    sent = decontracted(sentance)
    sent = sent.replace('\\r', ' ')
    sent = sent.replace('\\"', ' ')
    sent = sent.replace('\\n', ' ')
    sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
    sent = ' '.join(e for e in sent.split() if e not in stopwords)
    Other_skill.append(sent.lower().strip())
</code>```

Error:

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-12-30687b6f17e1> in <module>()
      4 # tqdm is for printing the status bar
      5 for sentance in tqdm(project_data['Other skills'].values):
----> 6     sent = decontracted(sentance)
      7     sent = sent.replace('\\r', ' ')
      8     sent = sent.replace('\\"', ' ')

<ipython-input-7-a344e4b38b78> in decontracted(phrase)
      4 def decontracted(phrase):
      5     # specific
----> 6     phrase = re.sub(r"won't", "will not", phrase)
      7     phrase = re.sub(r"can\'t", "can not", phrase)
      8

C:\ProgramData\Anaconda3\lib\re.py in sub(pattern, repl, string, count, flags)
    189     a callable, it's passed the match object and must return
    190     a replacement string to be used."""
--> 191     return _compile(pattern, flags).sub(repl, string, count)
    192
    193 def subn(pattern, repl, string, count=0, flags=0):

TypeError: expected string or bytes-like object
</code>```

答:
I think that the brackets in the values() is needed. If i am correct project_data is an dictionary and you missed the brackets in values</p>

```<code>from tqdm import tqdm
Other_skill = []
# tqdm is for printing the status bar
# the values must have round brackets
for sentance in tqdm(project_data['Other skills'].values()):
    sent = decontracted(sentance)
    sent = sent.replace('\\r', ' ')
    sent = sent.replace('\\"', ' ')
    sent = sent.replace('\\n', ' ')
    sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
    sent = ' '.join(e for e in sent.split() if e not in stopwords)
    Other_skill.append(sent.lower().strip())
</code>```

Body:
I have gone through several sources in stackoverflow regarding this issue, but couldn't resolve it.
Thus I have posted it here, kindly resolve.

# Combining all the above statemennts
from tqdm import tqdm
Other_skill = []
# tqdm is for printing the status bar
for sentance in tqdm(project_data['Other skills'].values):
    sent = decontracted(sentance)
    sent = sent.replace('\\r', ' ')
    sent = sent.replace('\\"', ' ')
    sent = sent.replace('\\n', ' ')
    sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
    sent = ' '.join(e for e in sent.split() if e not in stopwords)
    Other_skill.append(sent.lower().strip())

Error:

TypeError                                 Traceback (most recent call last)
<ipython-input-12-30687b6f17e1> in <module>()
      4 # tqdm is for printing the status bar
      5 for sentance in tqdm(project_data['Other skills'].values):
----> 6     sent = decontracted(sentance)
      7     sent = sent.replace('\\r', ' ')
      8     sent = sent.replace('\\"', ' ')

<ipython-input-7-a344e4b38b78> in decontracted(phrase)
      4 def decontracted(phrase):
      5     # specific
----> 6     phrase = re.sub(r"won't", "will not", phrase)
      7     phrase = re.sub(r"can\'t", "can not", phrase)
      8

C:\ProgramData\Anaconda3\lib\re.py in sub(pattern, repl, string, count, flags)
    189     a callable, it's passed the match object and must return
    190     a replacement string to be used."""
--> 191     return _compile(pattern, flags).sub(repl, string, count)
    192
    193 def subn(pattern, repl, string, count=0, flags=0):

TypeError: expected string or bytes-like object

Body:
I think that the brackets in the values() is needed. If i am correct project_data is an dictionary and you missed the brackets in values

from tqdm import tqdm
Other_skill = []
# tqdm is for printing the status bar
# the values must have round brackets
for sentance in tqdm(project_data['Other skills'].values()):
    sent = decontracted(sentance)
    sent = sent.replace('\\r', ' ')
    sent = sent.replace('\\"', ' ')
    sent = sent.replace('\\n', ' ')
    sent = re.sub('[^A-Za-z0-9]+', ' ', sent)
    sent = ' '.join(e for e in sent.split() if e not in stopwords)
    Other_skill.append(sent.lower().strip())


问:
Variant with unique types
While writing a cpp library I ended up with possiblity that std::variants shall contain repeating types, that is for example, std::variant<int, double, int, std::string, int>. It may be useful in some occasions but in case of my library I find this unnecessary. And so I would like to filter type reptitions like this:

std::variant<int, double, int, std::string, int> -> std::variant<int, double, std::string>

std::variant<std::string, std::string, int> -> std::variant<std::string, int>

How can this be done?

答:
With Boost.Mp11, this is a short one-liner (as always): </p>

```<code>using V1 = mp_unique<std::variant<int, double, int, std::string, int>>;
// V1 is std::variant<int, double, std::string>

using V2 = mp_unique<std::variant<std::string, std::string, int>>;
// V2 is std::variant<std::string, int>
</code>```

Title: Variant with unique types

Body:
With Boost.Mp11, this is a short one-liner (as always):

using V1 = mp_unique<std::variant<int, double, int, std::string, int>>;
// V1 is std::variant<int, double, std::string>

using V2 = mp_unique<std::variant<std::string, std::string, int>>;
// V2 is std::variant<std::string, int>


问:
Redux - how to keep the reducer state during hot reload
I use  React + Redux + Webpack + WebpackDevserver. Once the hot loader is launched all my reducers are reseted to the initial state.

Can I keep somehow my reducers in the actual state?

My Webpack config contains:

```<code>entry: [
    "./index.jsx"
],
output: {
    filename: "./bundle.js"
},
module: {
    loaders: [
        {
            test: /\.js|\.jsx$/,
            exclude: /node_modules/,
            loaders: ["react-hot","babel-loader"],
         }
    ]
},
plugins: [
    new webpack.HotModuleReplacementPlugin()
]
</code>```

My reducers stats with:

```<code>const initialState = {
...
}

export default function config(state = initialState, action) { ...
</code>```

I start my Webpack Dev-Server just by:

```<code>"start": "webpack-dev-server",
</code>```

答:
Yes you can, actually if you use react-hot-loader you'll have that exactly result and much more.

react-hot-loader will make sure to only update the exactly three you had change, and also will keeps the state on redux.

Example: you're creating a modal that receives some info from API and then keeps the info on redux, if you change the text color you know you'll have to wait for the entire app refresh, then the browser render, then you've to open the modal, wait the API and etc. BUT with react-hot-loader, after you changed that color, your modal will be still open, with your current data, and just that color will be updated.

Following the steps from the package README:

1 - You need to install the package (yes doesn't need to be a dev dependency, the README explain with more details why)

```<code>npm install react-hot-loader
</code>```

2 - Add it on .babelrc

```<code>// .babelrc
{
  "plugins": ["react-hot-loader/babel"]
}
</code>```

3 - Import hot at the first line of App.js file (yes, above React, ReactDOM, above all) and then mark your root component as hot-exported

// App.js
import { hot } from 'react-hot-loader/root';
const App = () =>
Hello World!
;
export default hot(App);
```

That's it, now you should have a hot reload that focus only at the last changes and keeps the redux state for you.

OBS: If you use hooks, please check out more details here on the docs

ContentLicense: CC BY-SA 3.0

Body:
I use  React + Redux + Webpack + WebpackDevserver. Once the hot loader is launched all my reducers are reseted to the initial state.

Can I keep somehow my reducers in the actual state?

My Webpack config contains:

entry: [
    "./index.jsx"
],
output: {
    filename: "./bundle.js"
},
module: {
    loaders: [
        {
            test: /\.js|\.jsx$/,
            exclude: /node_modules/,
            loaders: ["react-hot","babel-loader"],
         }
    ]
},
plugins: [
    new webpack.HotModuleReplacementPlugin()
]

My reducers stats with:

const initialState = {
...
}

export default function config(state = initialState, action) { ...

I start my Webpack Dev-Server just by:

"start": "webpack-dev-server",

Body:
Yes you can, actually if you use react-hot-loader you'll have that exactly result and much more.

react-hot-loader will make sure to only update the exactly three you had change, and also will keeps the state on redux.

Example: you're creating a modal that receives some info from API and then keeps the info on redux, if you change the text color you know you'll have to wait for the entire app refresh, then the browser render, then you've to open the modal, wait the API and etc. BUT with react-hot-loader, after you changed that color, your modal will be still open, with your current data, and just that color will be updated.

Following the steps from the package README:

1 - You need to install the package (yes doesn't need to be a dev dependency, the README explain with more details why)

npm install react-hot-loader

2 - Add it on .babelrc

// .babelrc
{
  "plugins": ["react-hot-loader/babel"]
}

3 - Import hot at the first line of App.js file (yes, above React, ReactDOM, above all) and then mark your root component as hot-exported

// App.js
import { hot } from 'react-hot-loader/root';
const App = () => <div>Hello World!</div>;
export default hot(App);

That's it, now you should have a hot reload that focus only at the last changes and keeps the redux state for you.

OBS: If you use hooks, please check out more details here on the docs


问:
Resizing UIImageview with a UITextview using UIGuesture
I'm new in Iphone. I have an UITextView inside a UIImageView . Now I need to dynamically resize the UIImageView so that its textview also change its size dynamically. Moreover I can move this UIImageView with UITextView around the screen. If any one knows this using UIGuesture please help me.

Any help would be appreciated

答:
If you are looking at resizing the UIImageView object, look at the UIPinchGestureRecognizer. It will have a property called scale that you can use to change its size.

As for the UITextView object that is the subview, you can look at autoresizingMask property inherited from UIView. Set it appropriately so that the text view scales in response to its super view.

For moving the image view, you can use the UIPanGestureRecognizer. You can get the translation using translationInView:. Use this to modify the center of the image view object. This should move the image view as you drag your finger around.

I hope you've gone through the guide. Let us know if you face problems implementing this and put some code so that we can guide you in the right direction.


问:
Different output on changing the position of fgets() function
The output is correct when fgets() in included in the while loop, but taking it outside makes it an infinite loop. Can anyone explain why?</p>

```<code>main()
{
    FILE *fp=fopen("myfile.txt","r");
    char s[100];
    fgets(s,50,fp);
    while(s!=NULL) //infinte loop
        puts(s);
    /* while((fgets(s,100,fp))!=NULL)
          puts(s);
       This runs fine */
    fclose(fp);
}
</code>```

答:
Code 1

```<code>main()
{
    FILE *fp = NULL;
    FILE *fp=fopen("myfile.txt","r");
    if(!fp)
    {
        /*error occured during fopen()! abort*/
        printf("Error while openning the file!\n");
        return 1;
    }
    char s[100];
    fgets(s,50,fp);   /*1*/

    while(s != NULL)  /*2*/
    {
        puts(s);      /*3*/
    }
    fclose(fp);
}
</code>```

Code 2

```<code>main()
{
    FILE *fp=fopen("myfile.txt","r");
    char s[100];
    while((fgets(s,100,fp)) != NULL) /*1*/
    {
        puts(s);                     /*2*/
    }

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

In Code 1, when you reach point /*1*/ your buffer s in not empty and contain some string (its not null). so you are entering the while loop with s!=null then in /*3*/ you are printing this in the stdoutput and return to point /*2*/ to ask if s != null and getting again the same answer that s is not null. hence you are stuck in this infinite loop forever.

In Code 2, In point /*1*/ you are redaing a line from the input stream and ask if its not null. fgets() Upon successful completion, fgets() shall return s.  If the stream is at end-of-file, the end-of-file indicator for the stream shall be set and fgets() shall return a null pointer.  If a read error occurs, the error indicator for the stream shall be set, fgets() shall return a null pointer, and shall set errno to indicate the error. In some point you will reach the eof and fgets() will return null and then you will exit the loop. for further reading please refer to man pages in the link

Body:
The output is correct when fgets() in included in the while loop, but taking it outside makes it an infinite loop. Can anyone explain why?

main()
{
    FILE *fp=fopen("myfile.txt","r");
    char s[100];
    fgets(s,50,fp);
    while(s!=NULL) //infinte loop
        puts(s);
    /* while((fgets(s,100,fp))!=NULL)
          puts(s);
       This runs fine */
    fclose(fp);
}

Body:
Code 1

main()
{
    FILE *fp = NULL;
    FILE *fp=fopen("myfile.txt","r");
    if(!fp)
    {
        /*error occured during fopen()! abort*/
        printf("Error while openning the file!\n");
        return 1;
    }
    char s[100];
    fgets(s,50,fp);   /*1*/

    while(s != NULL)  /*2*/
    {
        puts(s);      /*3*/
    }
    fclose(fp);
}

Code 2

main()
{
    FILE *fp=fopen("myfile.txt","r");
    char s[100];
    while((fgets(s,100,fp)) != NULL) /*1*/
    {
        puts(s);                     /*2*/
    }

    fclose(fp);
}

In Code 1, when you reach point /*1*/ your buffer s in not empty and contain some string (its not null). so you are entering the while loop with s!=null then in /*3*/ you are printing this in the stdoutput and return to point /*2*/ to ask if s != null and getting again the same answer that s is not null. hence you are stuck in this infinite loop forever.

In Code 2, In point /*1*/ you are redaing a line from the input stream and ask if its not null. fgets() Upon successful completion, fgets() shall return s.  If the stream is at end-of-file, the end-of-file indicator for the stream shall be set and fgets() shall return a null pointer.  If a read error occurs, the error indicator for the stream shall be set, fgets() shall return a null pointer, and shall set errno to indicate the error. In some point you will reach the eof and fgets() will return null and then you will exit the loop. for further reading please refer to man pages in the link


问:
group by filtered pandas dataframe and select latest in each group
I'm facing a problem with filtered dataframe and groupby

Say I have this dataframe

```
    id     product   date
0   220    6647     2015-09-01
1   220    6647     2014-09-03
2   220    6647     2014-10-16
3   826    3380     2014-11-11
4   826    3380     2015-12-09
5   826    3380     2015-05-19
6   901    4555     2015-09-01
7   901    4555     2014-10-05
8   901    4555     2014-11-01
```

I'd like to first select rows of year 2015 and then groupby id and get the latest by date

I've read this article, that works great on the entire df

but it seems it's not working if I first try to filter the df like this

```<code>my_date = datetime.datetime(2014, 12, 31)
df = df[df.date>my_date]
</code>```

now if I run the following code

```<code>df.loc[df.groupby('id').date.idxmax()]
</code>```

it gives my the following error

attempt to get argmax of an empty sequence

Any help would be appreciated :)
thanks

答:
ok, I got it

the example I posted is taken from another article and it works perfect

my own example is a bit different

my dataframe groupby item is taype category

if I leave it as object it works

Body:
I'm facing a problem with filtered dataframe and groupby

Say I have this dataframe

    id     product   date
0   220    6647     2015-09-01
1   220    6647     2014-09-03
2   220    6647     2014-10-16
3   826    3380     2014-11-11
4   826    3380     2015-12-09
5   826    3380     2015-05-19
6   901    4555     2015-09-01
7   901    4555     2014-10-05
8   901    4555     2014-11-01

I'd like to first select rows of year 2015 and then groupby id and get the latest by date

I've read this article, that works great on the entire df

but it seems it's not working if I first try to filter the df like this

my_date = datetime.datetime(2014, 12, 31)
df = df[df.date>my_date]

now if I run the following code

df.loc[df.groupby('id').date.idxmax()]

it gives my the following error

attempt to get argmax of an empty sequence

Any help would be appreciated :)
thanks


问:
Webpack, including HTML files within other HTML files
Webpack and Pug have a really nifty feature called includes. This allows you to load another pug template from a pug template by just calling:

```<code>  include ../components/head.pug
</code>```

As far as I understand it this doesn't use any JS and is done automatically when Webpack compiles the scripts.

Is there any way to achieve this without using pug and without adding HTML files to the dom client-side with JS?

I've looked at a bunch of Webpack plugins but none seem to do this without loading html from the JS.

答:
Turns out this is included in html-webpack-plugin.

Just add:

```<code>  <%= require('html-loader!../components/file.html') %>
</code>```

Within the html file and it will be automatically replaced on compile.

Body:
Webpack and Pug have a really nifty feature called includes. This allows you to load another pug template from a pug template by just calling:

  include ../components/head.pug

As far as I understand it this doesn't use any JS and is done automatically when Webpack compiles the scripts.

Is there any way to achieve this without using pug and without adding HTML files to the dom client-side with JS?

I've looked at a bunch of Webpack plugins but none seem to do this without loading html from the JS.

Body:
Turns out this is included in html-webpack-plugin.

Just add:

  <%= require('html-loader!../components/file.html') %>

Within the html file and it will be automatically replaced on compile.


问:
How to avoid iOS automatic font size adjustment?
I am NOT talking about zooming the page, but rather the way MobileSafari on iOS automatically bumps up some font sizes sometimes.

When, exactly, is this done? Can it be prevented or discouraged?

答:
Had a lot of trouble tracking it down, but: it’s the -webkit-text-size-adjust property in CSS.

Values:

Percentage (of default size), e.g. 120%, or 100%

auto (the default)

none – if auto isn’t working for your page. However this often causes problems with zooming. Use 100% instead. For example, open Safari on your desktop and zoom the page (Command-Plus) – your text won’t be enlarged, even though the entire page has zoomed! Don’t use none!

Note that these can be applied not just at the page level but at the element/widget/container level.

(I would not just specify a value of 100% for my website unless I was damn sure it was already optimized for small screens, and never none since it causes problems.)

Please note that in Firefox Mobile (e.g. for Android and Firefox OS) there is a similar property, -moz-text-size-adjust, documented here. Thanks to Costa for pointing this out.

Update, 10 years later: This MDN page is probably best for checking what browsers' current compatibilities and vendor prefixes are for this property.


问:
Not able to migate data
I was trying to migrate my data to mysql database and this error popped up

SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'read' (SQL: alter table `messages` add `read` tinyint(1) not null default 'false' after `to`)

Before this I was using sqlite and didn't face any such problem.

This is the table:-

```<code><?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddReadToMessages extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('messages', function (Blueprint $table) {
            $table->boolean('read')->after('to')->default('false');
                    });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('messages', function (Blueprint $table) {
            $table->dropColumn('read');
                    });
    }
}
</code>```

Can anyone please help me

-ThankYou

答:
'false' is a string, false is a Boolean. Change your migration to

```<code>$table->boolean('read')->after('to')->default(false);
</code>```

Title: Not able to migate data

Body:
I was trying to migrate my data to mysql database and this error popped up

SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'read' (SQL: alter table `messages` add `read` tinyint(1) not null default 'false' after `to`)

Before this I was using sqlite and didn't face any such problem.

This is the table:-

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddReadToMessages extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('messages', function (Blueprint $table) {
            $table->boolean('read')->after('to')->default('false');
                    });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('messages', function (Blueprint $table) {
            $table->dropColumn('read');
                    });
    }
}

Can anyone please help me

-ThankYou

Body:
'false' is a string, false is a Boolean. Change your migration to

$table->boolean('read')->after('to')->default(false);


问:
Using a template with lambda function pointer
I'm playing around with some C++11 features, and I encountered the following:

```<code>#include <iostream>
#include <vector>

template <class T>
void map(std::vector<T>& values, T(*func)(T)) {
    for (int &value : values) {
        value = func(value);
    }
}

int mul2(int x) {
    return 2*x;
}

auto mul3 = [](int value) {
    return value * 3;
};

int main() {
    std::vector<int> v = { 1,2,3,4,5 };
    map(v, mul3);
    for (auto value : v) {
        std::cout << value << std::endl;
    }
}
</code>```

using map with mul2 works as expected, but when I use the mul3 function it gives a compilation error. I expected that auto in this case would give me a int function pointer, but it seems that is not the case here. Anybody could explain this behaviour?

答:
Expanded from my comment (when the question was closed), you can template away the function details using the functor template "pattern":

```<code>template <class T, typename Functor>
void map(std::vector<T>& values, Functor func) {
    for (int &value : values) {
        value = func(value);
    }
}
</code>```

See here for full example: https://godbolt.org/z/fdHvAP

Body:
I'm playing around with some C++11 features, and I encountered the following:

#include <iostream>
#include <vector>

template <class T>
void map(std::vector<T>& values, T(*func)(T)) {
    for (int &value : values) {
        value = func(value);
    }
}

int mul2(int x) {
    return 2*x;
}

auto mul3 = [](int value) {
    return value * 3;
};

int main() {
    std::vector<int> v = { 1,2,3,4,5 };
    map(v, mul3);
    for (auto value : v) {
        std::cout << value << std::endl;
    }
}

using map with mul2 works as expected, but when I use the mul3 function it gives a compilation error. I expected that auto in this case would give me a int function pointer, but it seems that is not the case here. Anybody could explain this behaviour?

Body:
Expanded from my comment (when the question was closed), you can template away the function details using the functor template "pattern":

template <class T, typename Functor>
void map(std::vector<T>& values, Functor func) {
    for (int &value : values) {
        value = func(value);
    }
}

See here for full example: https://godbolt.org/z/fdHvAP


问:
Change Azure B2C subscription
Is there any way to change the billing subscription on a Azure B2C tenant. I see this article which states: "Azure AD B2C tenants can be moved to another subscription if the source and destination subscriptions exist within the same Azure Active Directory tenant." but I suppose this did not clarify for me.

I have two different subscriptions which are just independant Azure subscriptions and neither is part of a corporate enrollment, so I don't think they are apart of the same AD tenant, unless onmicrosoft is the AD tenant.

Has anybody done this before?

答: Tenant means .onmicrosoft.com directory. If both subscriptions appear when selecting the directory in the Azure Portal, then the B2C resource can be moved between them. If not, then you first need to move the destination subscription to the tenant in which the subscription that holds the B2C resource lives, move the resource, then move the subscription back to the original tenant if you need to. Moving subscriptions between tenants will lose all RBAC assignments, since they are tied to the users in the original tenant/directory.</p>

Title: Change Azure B2C subscription


问:
Javastatement in ps1 file is not executed as admin if mixed with other statements. (Error:Return argument has an invalid type)
context:

We try to configure runner vms for UFT and Selenium execution. These vms are citrix based and restart at night with the most up to date productive image and lose their automation configuration in this restartprocess.. Then a sheduled task executes a powershellscript with elevated rights which copies a jenkinsfolder to the vm, download the jenkins slave.jar for the connection, installs uft and eclipse and at last starts connection to jenkins.

If i start powershell as admin and execute the commands by hand everything works fine.

If i put it into a powershell scriptfile and execute it with a sheduled Task it looks all fine. But i get a "Return argument has an invalid type" in my job if i start a UFT testcase via jenkins. It looks like the connection is no started with elevated rights.

If i cut the script in half. All steps but the connection in one script and the connection in a second one, the testcase runs without any problems.

I rebuild the script in a batch file but is has the complete same behavior.

So option 3 is working but the citrix admins and my lead are not happy with such an unpredictable behavior. Does anyone has a hint how we can get the script running in one powershell script?

complete Scipt (produces the error):

```<code>switch -wildcard($env:computername){
    "wxp-guirun-p*" {

        robocopy '\\vhv\sachgebiete\Sachgebiete\Testautomatisierung\Installationsdateien\Runner\VhvEntw' 'c:\VHVEntw' /E

        Invoke-WebRequest https://jenkins-master.ads.vhv.de/jnlpJars/slave.jar -OutFile c:\vhvEntw\Jenkins\slave.jar

        cscript '\\vhv\sachgebiete\Sachgebiete\Testautomatisierung\Installationsdateien\Runner\UFT_3811-000\14.0\Package\Wrapper\Default\Wrapper_64.vbs'

        Start-Process 'C:\Program Files (x86)\HP\Unified Functional Testing\bin\HP.UFT.LicenseInstall.exe' -Argument 'concurrent 20402 1 SERVERADRESS'

        cscript '\\vhv\sachgebiete\Sachgebiete\Testautomatisierung\Installationsdateien\Runner\eclipse_1685-000\4.10.0\Package\Wrapper\Default\Wrapper.vbs'

        break;
       }

}

echo $env:computername

switch -wildcard($env:computername){

    "wxp-guirun-p01" {
           java -jar c:\vhventw\jenkins\slave.jar -jnlpUrl SERVERADRESS AND SECRET -workDir "C:\vhvEntw\Jenkins"
            break;
       }
}
</code>```

Cut in half it works:

Installation:

```<code>switch -wildcard($env:computername){
    "wxp-guirun-p*" {

        robocopy '\\vhv\sachgebiete\Sachgebiete\Testautomatisierung\Installationsdateien\Runner\VhvEntw' 'c:\VHVEntw' /E

        Invoke-WebRequest https://jenkins-master.ads.vhv.de/jnlpJars/slave.jar -OutFile c:\vhvEntw\Jenkins\slave.jar

        cscript '\\vhv\sachgebiete\Sachgebiete\Testautomatisierung\Installationsdateien\Runner\UFT_3811-000\14.0\Package\Wrapper\Default\Wrapper_64.vbs'

        Start-Process 'C:\Program Files (x86)\HP\Unified Functional Testing\bin\HP.UFT.LicenseInstall.exe' -Argument 'concurrent 20402 1 SERVERADRESS'

        cscript '\\vhv\sachgebiete\Sachgebiete\Testautomatisierung\Installationsdateien\Runner\eclipse_1685-000\4.10.0\Package\Wrapper\Default\Wrapper.vbs'

        break;
       }

}
</code>```

Connection:

```<code>echo $env:computername

switch -wildcard($env:computername){

    "wxp-guirun-p01" {
            java -jar c:\vhventw\jenkins\slave.jar -jnlpUrl SERVERADRESS AND SECRET -workDir "C:\vhvEntw\Jenkins"
            break;
       }
}
</code>```

答:
If your UFT.exe process is created using the Quicktest.Automation COM Object then the process will not inherit anything from it's parent process (like elevated rights, handlers, environment variables etc). It seems to be spinned of from the User Context.

As a Workaround you could start the UFT.exe process from the command Line (Disable Startup Screens and Add-In Selection), wait a bit and then connect to it with your Automation Object. In this way UFT will inherit your environment variables and handlers, and also the Elevated rights of the Parent Process (Jenkins)

Body:
context:

We try to configure runner vms for UFT and Selenium execution. These vms are citrix based and restart at night with the most up to date productive image and lose their automation configuration in this restartprocess.. Then a sheduled task executes a powershellscript with elevated rights which copies a jenkinsfolder to the vm, download the jenkins slave.jar for the connection, installs uft and eclipse and at last starts connection to jenkins.

If i start powershell as admin and execute the commands by hand everything works fine.

If i put it into a powershell scriptfile and execute it with a sheduled Task it looks all fine. But i get a "Return argument has an invalid type" in my job if i start a UFT testcase via jenkins. It looks like the connection is no started with elevated rights.

If i cut the script in half. All steps but the connection in one script and the connection in a second one, the testcase runs without any problems.

I rebuild the script in a batch file but is has the complete same behavior.

So option 3 is working but the citrix admins and my lead are not happy with such an unpredictable behavior. Does anyone has a hint how we can get the script running in one powershell script?

complete Scipt (produces the error):

switch -wildcard($env:computername){
    "wxp-guirun-p*" {

        robocopy '\\vhv\sachgebiete\Sachgebiete\Testautomatisierung\Installationsdateien\Runner\VhvEntw' 'c:\VHVEntw' /E

        Invoke-WebRequest https://jenkins-master.ads.vhv.de/jnlpJars/slave.jar -OutFile c:\vhvEntw\Jenkins\slave.jar

        cscript '\\vhv\sachgebiete\Sachgebiete\Testautomatisierung\Installationsdateien\Runner\UFT_3811-000\14.0\Package\Wrapper\Default\Wrapper_64.vbs'

        Start-Process 'C:\Program Files (x86)\HP\Unified Functional Testing\bin\HP.UFT.LicenseInstall.exe' -Argument 'concurrent 20402 1 SERVERADRESS'

        cscript '\\vhv\sachgebiete\Sachgebiete\Testautomatisierung\Installationsdateien\Runner\eclipse_1685-000\4.10.0\Package\Wrapper\Default\Wrapper.vbs'

        break;
       }

}

echo $env:computername

switch -wildcard($env:computername){

    "wxp-guirun-p01" {
           java -jar c:\vhventw\jenkins\slave.jar -jnlpUrl SERVERADRESS AND SECRET -workDir "C:\vhvEntw\Jenkins"
            break;
       }
}

Cut in half it works:

Installation:

switch -wildcard($env:computername){
    "wxp-guirun-p*" {

        robocopy '\\vhv\sachgebiete\Sachgebiete\Testautomatisierung\Installationsdateien\Runner\VhvEntw' 'c:\VHVEntw' /E

        Invoke-WebRequest https://jenkins-master.ads.vhv.de/jnlpJars/slave.jar -OutFile c:\vhvEntw\Jenkins\slave.jar

        cscript '\\vhv\sachgebiete\Sachgebiete\Testautomatisierung\Installationsdateien\Runner\UFT_3811-000\14.0\Package\Wrapper\Default\Wrapper_64.vbs'

        Start-Process 'C:\Program Files (x86)\HP\Unified Functional Testing\bin\HP.UFT.LicenseInstall.exe' -Argument 'concurrent 20402 1 SERVERADRESS'

        cscript '\\vhv\sachgebiete\Sachgebiete\Testautomatisierung\Installationsdateien\Runner\eclipse_1685-000\4.10.0\Package\Wrapper\Default\Wrapper.vbs'

        break;
       }

}

Connection:

echo $env:computername

switch -wildcard($env:computername){

    "wxp-guirun-p01" {
            java -jar c:\vhventw\jenkins\slave.jar -jnlpUrl SERVERADRESS AND SECRET -workDir "C:\vhvEntw\Jenkins"
            break;
       }
}


问:
convenient way to convert seconds into more specific format
Is there any convenient way to convert seconds into more specific format.

For example:

I want to convert

```<code>559 seconds
</code>```

to

```<code>9 min 19 sec
</code>```

答:
You can do this: </p>

```<code>$sec = 559;

$min = floor($sec / 60);
$sec = $sec % 60; // 19
</code>```

Body:
Is there any convenient way to convert seconds into more specific format.

For example:

I want to convert

559 seconds

to

9 min 19 sec

Body:
You can do this:

$sec = 559;

$min = floor($sec / 60);
$sec = $sec % 60; // 19


问:
How to split strings across multiple lines in CMake?
I usually have a policy in my project, to never create lines in text files that exceed a line length of 80, so they are easily editable in all kinds of editors (you know the deal). But with CMake I get the problem that I do not know how to split a simple string into multiple lines to avoid one huge line. Consider this basic code:

```<code>set(MYPROJ_VERSION_MAJOR "1")
set(MYPROJ_VERSION_MINOR "0")
set(MYPROJ_VERSION_PATCH "0")
set(MYPROJ_VERSION_EXTRA "rc1")
set(MYPROJ_VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}-${VERSION_EXTRA}")
</code>```

It already exceeds the 80 column limit. So how do I break a line in CMake into multiple lines without getting to verbose (multiple list(APPEND ...) or the like)?

答:
To maintain good indentation in your code it's straightforward enough just to do

```<code>message("These strings " "will all be "
        "concatenated. Don't forget "
        "your trailing spaces!")
</code>```

Or form a string directly with

```<code>string(CONCAT MYSTR "This and " "that "
                    "and me too!")
</code>```

as in Douglas' answer who has more details. However I thought this might just summarise the essential point.

Body:
I usually have a policy in my project, to never create lines in text files that exceed a line length of 80, so they are easily editable in all kinds of editors (you know the deal). But with CMake I get the problem that I do not know how to split a simple string into multiple lines to avoid one huge line. Consider this basic code:

set(MYPROJ_VERSION_MAJOR "1")
set(MYPROJ_VERSION_MINOR "0")
set(MYPROJ_VERSION_PATCH "0")
set(MYPROJ_VERSION_EXTRA "rc1")
set(MYPROJ_VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}-${VERSION_EXTRA}")

It already exceeds the 80 column limit. So how do I break a line in CMake into multiple lines without getting to verbose (multiple list(APPEND ...) or the like)?

Body:
To maintain good indentation in your code it's straightforward enough just to do

message("These strings " "will all be "
        "concatenated. Don't forget "
        "your trailing spaces!")

Or form a string directly with

string(CONCAT MYSTR "This and " "that "
                    "and me too!")

as in Douglas' answer who has more details. However I thought this might just summarise the essential point.


问:
Use default value with C# method overload
What is the best way to achieve this:
I have a class with 2 method overloads which I create n object from.
If I define b it will used and if not the default.
Where/How do I use this default without changing it permanently in the object.
What I did is the following but there must be a simpler way.</p>

```<code>.
.
.
private int b = 100;
private readonly int defualt_b = 100;

public void Press(int a)
{
...do something...
   Send(a, b);
}

public void Press(int a int new_b)
{
...do something...
    b = new_b; //set b to be used
     Press(a);
    b = default_b; //reset back to its default value
}
</code>```

答:
Add an optional parameter

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments

```<code>public void Press(int a , int new_b = 100)
{
}
</code>```

Body:
What is the best way to achieve this:
I have a class with 2 method overloads which I create n object from.
If I define b it will used and if not the default.
Where/How do I use this default without changing it permanently in the object.
What I did is the following but there must be a simpler way.

.
.
.
private int b = 100;
private readonly int defualt_b = 100;

public void Press(int a)
{
...do something...
   Send(a, b);
}

public void Press(int a int new_b)
{
...do something...
    b = new_b; //set b to be used
     Press(a);
    b = default_b; //reset back to its default value
}

Body:
Add an optional parameter

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments

public void Press(int a , int new_b = 100)
{
}


问:
Social Media and email extraction code needs updating
I am a bit stuck on this code that I put together. I took two codes and put them together, although this code does work for the most part there are still some issues that I can not fix.

WHAT THE CODE DOES

Opens a urls in Sheet3 column A, extracts the emails from the site and any social media links. Then puts the results from column B onwards

Problems

1) TWO code have been put together, but can it be written smarter as currently it looks for emails first and then it looks for social media urls, so if there was 100 urls, it would look for emails in them first and then GO BACK and look for social media urls again, hence the 100 are processed 200 times. When it should find emails and social media urls AT THE SAME TIME

2) Browser has been set to false but still shows in TASK BAR

3) When the process is finished a userform called, "Complete" should show. but it does NOT.

4) As the browser would show, I had to put some code at the end to close the browser, but it is not closing the browser. idealy I would not want the browser to show.

5) Both IE and "MSXML2.ServerXMLHTTP.6.0" are used. As I stated this was TWO code that I put together and therefore not the best. I think "MSXML2.ServerXMLHTTP.6.0" would be much faster. However I could not change the first half of the code to only use "MSXML2.ServerXMLHTTP.6.0" as I have always used IE in the past. Please could someone advise of what to do

What I have tried so far.

I have tried to place the code in several variations, non worked. I was able to fix the part where the active sheet did not have to be sheet3. So it does not matter what sheet I am on it will GET and Paste the results into sheet3.

```<code>Private Sub SocialEmailStartBut_Click()
''Extract emails only from urls
Dim ie As InternetExplorer
Dim url As String
Dim x As Long
Dim HTML As HTMLDocument
Dim ElementCol As Object
Dim Worksheet As Sheet3
Set HTML = CreateObject("htmlfile")

Set ie = CreateObject("internetexplorer.application")
    ie.Visible = False '###### set to false BUT shows in task bar #####

x = 2 '''start row
Do While Sheet3.Cells(x, 1) <> ""
    url = Sheet3.Cells(x, 1)

ie.navigate url
    Do While ie.readyState <> READYSTATE_COMPLETE
    DoEvents
Loop

Set HTML = ie.document
    Set ElementCol = HTML.getElementsByTagName("a")

For Each link In ElementCol
    If InStr(link, "mailto:") Then
        Sheet3.Cells(x, 2).Value = link
        Sheet3.Cells(x, 2) = Right(link, Len(link) - InStr(link, ":"))
        Sheet3.Cells(x, 2).Columns.AutoFit
    End If
Next
x = x + 1
Loop

'#################################################################
'###################Social URL Extractor##########################
'#################################################################
Dim counter As Long
Dim website As Range
Dim row As Long
Dim continue As Boolean
Dim respHead As String

''''The row where website addresses start
row = 2
    continue = True

Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
    Do While continue
'''Could set this to first cell with URL then OFFSET columns to get next web site
Set website = ThisWorkbook.Worksheets("Sheet3").Range("A" & row)
        If Len(website.Value) < 1 Then
            continue = False
        Exit Sub
        End If

        If website Is Nothing Then
            continue = False
        End If

'''Debug.Print website
    With http
        On Error Resume Next
        .Open "GET", website.Value, False
        .send

'''If the website sent a valid response to our request, URLS ARE IN COLUMN A
    If Err.Number = 0 Then
        If .Status = 200 Then
            HTML.body.innerHTML = http.responseText
                Set links = HTML.getElementsByTagName("a")
'''COLUMN C = FACEBOOK
   For Each link In links
      If InStr(UCase(link.outerHTML), "FACEBOOK") Then
      website.Offset(0, 2).Value = link.href
   End If
'''COLUMN D = INSTAGRAM
    If InStr(UCase(link.outerHTML), "INSTAGRAM") Then
        website.Offset(0, 3).Value = link.href
    End If
'''COLUMN E = TWITTER
    If InStr(UCase(link.outerHTML), "TWITTER") Then
        website.Offset(0, 4).Value = link.href
    End If
'''COLUMN F = YOUTUBE
    If InStr(UCase(link.outerHTML), "YOUTUBE") Then
        website.Offset(0, 5).Value = link.href
    End If
'''COLUMN G = LinkedIn
    If InStr(UCase(link.outerHTML), "LINKEDIN") Then
        website.Offset(0, 6).Value = link.href
    End If
Next
    End If
    Set website = Nothing
Else
'''Debug.Print "Error loading page IN COLUMN H"
    website.Offset(0, 8).Value = "Error with website address"
    End If
On Error GoTo 0
 End With
row = row + 1
Loop

Complete.Show '#### THIS FORM DOES NOT SHOW AT THE END ####
''' CLOSE BROWSER
ie.Quit
Set ie = Nothing
Set ElementCol = Nothing
End Sub
</code>```

答:
I made a mistake in thinking. To load dynamic content when the server reports that the page has loaded, another pause is necessary. So you would have to pause at every page because you can't check that. Anyway, I don't know how. So now I have implemented it with the faster MSXML2.

I added counters for all found links. If more than one link was found, a comment with the found count is set in the cell. If you go through the same URLs again, the comments and found links will be deleted and if necessary reset.

The counters should give you an overview if you need a different table layout to get all links and not only the last one. In this case you need your own table to enter all links.

Try the following macro. Read the comments carefully.

```<code>Sub ScrapeSoMeAndMailAddresses()

'******************************************************
'The macro works on the sheet from which it was started
'******************************************************

Dim url As String
Dim http As Object
Dim htmlDoc As Object
Dim nodeAllLinks As Object
Dim nodeOneLink As Object
Dim currentRow As Long

'Counters to check, if there are more than one address per page
Dim addressCounters(5) As Long
Dim checkCounters As Long

  'Initialize variables
  currentRow = 2
  Set htmlDoc = CreateObject("htmlfile")
  Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")

  'Loop over all URLs in column A in the active table
  Do While ActiveSheet.Cells(currentRow, 1).Value <> ""
    'Scroll if current row > 14
    If currentRow > 14 Then
      ActiveWindow.SmallScroll down:=1
    End If
    'Clear content in current row
    ActiveSheet.Range(Cells(currentRow, 2), Cells(currentRow, 9)).ClearContents
    'Get next url from table
    url = ActiveSheet.Cells(currentRow, 1).Value
    'Load page
    http.Open "GET", url, False
    http.send
    'Check if page loading was successful
    If http.Status = 200 Then
      'Build html document for DOM operations
      htmlDoc.body.innerHTML = http.responseText
      'Create node list from all links of the page
      Set nodeAllLinks = htmlDoc.getElementsByTagName("a")
      'Walk through all links of the node list
      For Each nodeOneLink In nodeAllLinks
        'Check for mail address
        If InStr(1, nodeOneLink.href, "mailto:") Then
          'Write mail address to table in column B
          ActiveSheet.Cells(currentRow, 2).Value = Right(nodeOneLink.href, Len(nodeOneLink.href) - InStr(nodeOneLink.href, ":"))
          'Increment mail address counter
          addressCounters(0) = addressCounters(0) + 1
        End If
        'Check for Facebook address
        If InStr(1, UCase(nodeOneLink.href), "FACEBOOK") Then
          'Write Facebook address to table in column C
          ActiveSheet.Cells(currentRow, 3).Value = nodeOneLink.href
          'Increment Facebook counter
          addressCounters(1) = addressCounters(1) + 1
        End If
        'Check for Instagram address
        If InStr(1, UCase(nodeOneLink.href), "INSTAGRAM") Then
          'Write INSTAGRAM address to table in column D
          ActiveSheet.Cells(currentRow, 4).Value = nodeOneLink.href
          'Increment Instagram counter
          addressCounters(2) = addressCounters(2) + 1
        End If
        'Check for Twitter address
        If InStr(1, UCase(nodeOneLink.href), "TWITTER") Then
          'Write Twitter address to table in column E
          ActiveSheet.Cells(currentRow, 5).Value = nodeOneLink.href
          'Increment Twitter counter
          addressCounters(3) = addressCounters(3) + 1
        End If
        'Check for YouTube address
        If InStr(1, UCase(nodeOneLink.href), "YOUTUBE") Then
          'Write YouTube address to table in column F
          ActiveSheet.Cells(currentRow, 6).Value = nodeOneLink.href
          'Increment YouTube counter
          addressCounters(4) = addressCounters(4) + 1
        End If
        'Check for LinkedIn address
        If InStr(1, UCase(nodeOneLink.href), "LINKEDIN") Then
          'Write LinkedIn address to table in column G
          ActiveSheet.Cells(currentRow, 7).Value = nodeOneLink.href
          'Increment LinkedIn counter
          addressCounters(5) = addressCounters(5) + 1
        End If
      Next nodeOneLink

      'Check counters
      For checkCounters = 0 To 5
        'Delete comment if there is one
        If Not ActiveSheet.Cells(currentRow, checkCounters + 2).Comment Is Nothing Then
          ActiveSheet.Cells(currentRow, checkCounters + 2).Comment.Delete
        End If
        'Set comment if more than 1 link were found
        If addressCounters(checkCounters) > 1 Then
          ActiveSheet.Cells(currentRow, checkCounters + 2).AddComment Text:=CStr(addressCounters(checkCounters))
          ActiveSheet.Cells(currentRow, checkCounters + 2).Comment.Shape.TextFrame.AutoSize = True
        End If
      Next checkCounters
    Else
      'Page not loaded
      'Write message in column H
      ActiveSheet.Cells(currentRow, 9).Value = "Error with website address"
    End If

    'Prepare for next page
    Erase addressCounters
    currentRow = currentRow + 1
  Loop

  'Clean up
  Set http = Nothing
  Set htmlDoc = Nothing
  Set nodeAllLinks = Nothing
  Set nodeOneLink = Nothing

  'Check if this works now
  Complete.Show
End Sub
</code>```

Edit: Revised code

Since the macro above is more or less a proof of concept, I have now developed a version that meets the requirements of the first comment under this posting. Nothing more to read from the pages, but a lot of work ;-)

You have to create another table which contains all addresses after a macro run. You have to create the headline manually once. I have not implemented a check for duplicate addresses!

The code of the macro is not perfect (all in one, no functions), but it is much more flexible than version 1. If you understand the code, it should be quite easy to integrate additional platforms if needed.

About the thing with Sheet3:

You can access a sheet from VBA either by the name it has on the tab in the normal Excel view or by its index. Sheet3 is the name as far as I understood it. At the top of the Initialize Variables part, you can easily change the two default names Sheet3 and Sheet4 to match the names used on the tabs. You don't have to change anything else.

If you start the macro the content in both sheets will be delete at first.

Please read the comments in the VBA code carefully!

```<code>Sub ScrapeSoMeAndMailAddresses()

'Columns for both tables
Const colUrl As Long = 1 'Must always be the first column
Const colMail As Long = 2 'Must always be the first column before SoMe platforms
Const colFacebook As Long = 3
Const colInstagram As Long = 4
Const colTwitter As Long = 5
Const colYouTube As Long = 6
Const colLinkedIn As Long = 7 'Must always be the last column of SoMe platforms
Const colError As Long = 9 'Must always be the last column

Dim url As String
Dim http As Object
Dim htmlDoc As Object
Dim nodeAllLinks As Object
Dim nodeOneLink As Object
Dim pageLoadSuccessful As Boolean
Dim tableUrlsOneAddressLeft As String
Dim tableAllAddresses As String
Dim currentRowTableUrls As Long
Dim lastRowTableUrls As Long
Dim currentRowsTableAll(colUrl To colLinkedIn) As Long
Dim lastRowTableAll As Long
Dim addressCounters(colMail To colLinkedIn) As Long
Dim checkCounters As Long

  'Initialize variables
  tableUrlsOneAddressLeft = "Sheet3"
  currentRowTableUrls = 2 'First row for content
  tableAllAddresses = "Sheet4"
  For checkCounters = colUrl To colLinkedIn
    currentRowsTableAll(checkCounters) = 2 'First rows for content
  Next checkCounters
  Set htmlDoc = CreateObject("htmlfile")
  Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")

  'Clear all contents and comments in the URL source sheet from email column to error column
  lastRowTableUrls = Sheets(tableUrlsOneAddressLeft).Cells(Rows.count, colUrl).End(xlUp).row
  Sheets(tableUrlsOneAddressLeft).Range(Cells(currentRowTableUrls, colMail), Cells(lastRowTableUrls, colError)).ClearContents
  Sheets(tableUrlsOneAddressLeft).Range(Cells(currentRowTableUrls, colMail), Cells(lastRowTableUrls, colError)).ClearComments

  'Delete all rows except headline in the sheet with all addresses
  lastRowTableAll = Sheets(tableAllAddresses).Cells(Rows.count, colUrl).End(xlUp).row
  Sheets(tableAllAddresses).Rows(currentRowsTableAll(colUrl) & ":" & lastRowTableAll).Delete Shift:=xlUp

  'Loop over all URLs in column A in the URL source sheet
  Do While Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, 1).Value <> ""

    '**************************************
    'Scroll for visual monitoring
    'Comment out the following three lines,
    'if Sheet3 is not visible while the
    'macro runs
    'Otherwise a runtime error will occur
    If currentRowTableUrls > 14 Then
      ActiveWindow.SmallScroll down:=1
    End If
    '**************************************

    'Get next url from the URL source sheet
    url = Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colUrl).Value

    'Try to load page
    'Temporarily disable error
    'handling if there is a timeout
    On Error Resume Next
    http.Open "GET", url, False
    http.send
    On Error GoTo 0

    'Check if page loading was successful
    If http.Status = 200 Then
      pageLoadSuccessful = True
    End If

    If pageLoadSuccessful Then
      'Build html document for DOM operations
      htmlDoc.body.innerHTML = http.responseText
      'Create node list from all links of the page
      Set nodeAllLinks = htmlDoc.getElementsByTagName("a")
      'Walk through all links of the node list
      For Each nodeOneLink In nodeAllLinks
        'Check for mail address
        If InStr(1, nodeOneLink.href, "mailto:") Then
          'Write mail address to both tables
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colMail).Value = Right(nodeOneLink.href, Len(nodeOneLink.href) - InStr(nodeOneLink.href, ":"))
          Sheets(tableAllAddresses).Cells(currentRowsTableAll(colMail), colMail).Value = Right(nodeOneLink.href, Len(nodeOneLink.href) - InStr(nodeOneLink.href, ":"))
          'Check if it is a new line in the sheet with all addresses
          If currentRowsTableAll(colMail) >= currentRowsTableAll(colUrl) Then
            'Write URL in the new line of the sheet with all addresses
            Sheets(tableAllAddresses).Cells(currentRowsTableAll(colUrl), colUrl).Value = url
            'Increment url counter
            currentRowsTableAll(colUrl) = currentRowsTableAll(colUrl) + 1
          End If
          'Increment mail counters
          currentRowsTableAll(colMail) = currentRowsTableAll(colMail) + 1
          addressCounters(colMail) = addressCounters(colMail) + 1
        End If
        'Check for Facebook address
        If InStr(1, UCase(nodeOneLink.href), "FACEBOOK") Then
          'Write Facebook address to both tables
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colFacebook).Value = nodeOneLink.href
          Sheets(tableAllAddresses).Cells(currentRowsTableAll(colFacebook), colFacebook).Value = nodeOneLink.href
          'Check if it is a new line in the sheet with all addresses
          If currentRowsTableAll(colFacebook) >= currentRowsTableAll(colUrl) Then
            'Write URL in the new line of the sheet with all addresses
            Sheets(tableAllAddresses).Cells(currentRowsTableAll(colUrl), colUrl).Value = url
            'Increment url counter
            currentRowsTableAll(colUrl) = currentRowsTableAll(colUrl) + 1
          End If
          'Increment Facebook counters
          currentRowsTableAll(colFacebook) = currentRowsTableAll(colFacebook) + 1
          addressCounters(colFacebook) = addressCounters(colFacebook) + 1
        End If
        'Check for Instagram address
        If InStr(1, UCase(nodeOneLink.href), "INSTAGRAM") Then
          'Write INSTAGRAM address to both tables
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colInstagram).Value = nodeOneLink.href
          Sheets(tableAllAddresses).Cells(currentRowsTableAll(colInstagram), colInstagram).Value = nodeOneLink.href
          'Check if it is a new line in the sheet with all addresses
          If currentRowsTableAll(colInstagram) >= currentRowsTableAll(colUrl) Then
            'Write URL in the new line of the sheet with all addresses
            Sheets(tableAllAddresses).Cells(currentRowsTableAll(colUrl), colUrl).Value = url
            'Increment url counter
            currentRowsTableAll(colUrl) = currentRowsTableAll(colUrl) + 1
          End If
          'Increment Instagram counters
          currentRowsTableAll(colInstagram) = currentRowsTableAll(colInstagram) + 1
          addressCounters(colInstagram) = addressCounters(colInstagram) + 1
        End If
        'Check for Twitter address
        If InStr(1, UCase(nodeOneLink.href), "TWITTER") Then
          'Write Twitter address to both tables
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colTwitter).Value = nodeOneLink.href
          Sheets(tableAllAddresses).Cells(currentRowsTableAll(colTwitter), colTwitter).Value = nodeOneLink.href
          'Check if it is a new line in the sheet with all addresses
          If currentRowsTableAll(colTwitter) >= currentRowsTableAll(colUrl) Then
            'Write URL in the new line of the sheet with all addresses
            Sheets(tableAllAddresses).Cells(currentRowsTableAll(colUrl), colUrl).Value = url
            'Increment url counter
            currentRowsTableAll(colUrl) = currentRowsTableAll(colUrl) + 1
          End If
          'Increment Twitter counters
          currentRowsTableAll(colTwitter) = currentRowsTableAll(colTwitter) + 1
          addressCounters(colTwitter) = addressCounters(colTwitter) + 1
        End If
        'Check for YouTube address
        If InStr(1, UCase(nodeOneLink.href), "YOUTUBE") Then
          'Write YouTube address to both tables
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colYouTube).Value = nodeOneLink.href
          Sheets(tableAllAddresses).Cells(currentRowsTableAll(colYouTube), colYouTube).Value = nodeOneLink.href
          'Check if it is a new line in the sheet with all addresses
          If currentRowsTableAll(colYouTube) >= currentRowsTableAll(colUrl) Then
            'Write URL in the new line of the sheet with all addresses
            Sheets(tableAllAddresses).Cells(currentRowsTableAll(colUrl), colUrl).Value = url
            'Increment url counter
            currentRowsTableAll(colUrl) = currentRowsTableAll(colUrl) + 1
          End If
          'Increment YouTube counters
          currentRowsTableAll(colYouTube) = currentRowsTableAll(colYouTube) + 1
          addressCounters(colYouTube) = addressCounters(colYouTube) + 1
        End If
        'Check for LinkedIn address
        If InStr(1, UCase(nodeOneLink.href), "LINKEDIN") Then
          'Write LinkedIn address to both tables
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colLinkedIn).Value = nodeOneLink.href
          Sheets(tableAllAddresses).Cells(currentRowsTableAll(colLinkedIn), colLinkedIn).Value = nodeOneLink.href
          'Check if it is a new line in the sheet with all addresses
          If currentRowsTableAll(colLinkedIn) >= currentRowsTableAll(colUrl) Then
            'Write URL in the new line of the sheet with all addresses
            Sheets(tableAllAddresses).Cells(currentRowsTableAll(colUrl), colUrl).Value = url
            'Increment url counter
            currentRowsTableAll(colUrl) = currentRowsTableAll(colUrl) + 1
          End If
          'Increment LinkedIn counters
          currentRowsTableAll(colLinkedIn) = currentRowsTableAll(colLinkedIn) + 1
          addressCounters(colLinkedIn) = addressCounters(colLinkedIn) + 1
        End If
      Next nodeOneLink

      'Check address counters
      For checkCounters = colMail To colLinkedIn
        'Set comment if more than 1 link were found
        If addressCounters(checkCounters) > 1 Then
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, checkCounters).AddComment Text:=CStr(addressCounters(checkCounters))
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, checkCounters).Comment.Shape.TextFrame.AutoSize = True
        End If
      Next checkCounters
    Else
      'Page not loaded
      'Write message URL table
      Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colError).Value = "Error with URL or timeout"
    End If

    'Prepare for next page
    pageLoadSuccessful = False
    Erase addressCounters
    lastRowTableAll = Sheets(tableAllAddresses).Cells(Rows.count, colUrl).End(xlUp).row
    For checkCounters = colUrl To colLinkedIn
      currentRowsTableAll(checkCounters) = lastRowTableAll + 1 'First rows for next page content
    Next checkCounters
    currentRowTableUrls = currentRowTableUrls + 1
  Loop

  'Clean up
  Set http = Nothing
  Set htmlDoc = Nothing
  Set nodeAllLinks = Nothing
  Set nodeOneLink = Nothing

  'Check if this works now
  Complete.Show
End Sub
</code>```

Body:
I am a bit stuck on this code that I put together. I took two codes and put them together, although this code does work for the most part there are still some issues that I can not fix.

WHAT THE CODE DOES

Opens a urls in Sheet3 column A, extracts the emails from the site and any social media links. Then puts the results from column B onwards

Problems

1) TWO code have been put together, but can it be written smarter as currently it looks for emails first and then it looks for social media urls, so if there was 100 urls, it would look for emails in them first and then GO BACK and look for social media urls again, hence the 100 are processed 200 times. When it should find emails and social media urls AT THE SAME TIME

2) Browser has been set to false but still shows in TASK BAR

3) When the process is finished a userform called, "Complete" should show. but it does NOT.

4) As the browser would show, I had to put some code at the end to close the browser, but it is not closing the browser. idealy I would not want the browser to show.

5) Both IE and "MSXML2.ServerXMLHTTP.6.0" are used. As I stated this was TWO code that I put together and therefore not the best. I think "MSXML2.ServerXMLHTTP.6.0" would be much faster. However I could not change the first half of the code to only use "MSXML2.ServerXMLHTTP.6.0" as I have always used IE in the past. Please could someone advise of what to do

What I have tried so far.

I have tried to place the code in several variations, non worked. I was able to fix the part where the active sheet did not have to be sheet3. So it does not matter what sheet I am on it will GET and Paste the results into sheet3.

Private Sub SocialEmailStartBut_Click()
''Extract emails only from urls
Dim ie As InternetExplorer
Dim url As String
Dim x As Long
Dim HTML As HTMLDocument
Dim ElementCol As Object
Dim Worksheet As Sheet3
Set HTML = CreateObject("htmlfile")

Set ie = CreateObject("internetexplorer.application")
    ie.Visible = False '###### set to false BUT shows in task bar #####

x = 2 '''start row
Do While Sheet3.Cells(x, 1) <> ""
    url = Sheet3.Cells(x, 1)

ie.navigate url
    Do While ie.readyState <> READYSTATE_COMPLETE
    DoEvents
Loop

Set HTML = ie.document
    Set ElementCol = HTML.getElementsByTagName("a")

For Each link In ElementCol
    If InStr(link, "mailto:") Then
        Sheet3.Cells(x, 2).Value = link
        Sheet3.Cells(x, 2) = Right(link, Len(link) - InStr(link, ":"))
        Sheet3.Cells(x, 2).Columns.AutoFit
    End If
Next
x = x + 1
Loop

'#################################################################
'###################Social URL Extractor##########################
'#################################################################
Dim counter As Long
Dim website As Range
Dim row As Long
Dim continue As Boolean
Dim respHead As String

''''The row where website addresses start
row = 2
    continue = True

Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
    Do While continue
'''Could set this to first cell with URL then OFFSET columns to get next web site
Set website = ThisWorkbook.Worksheets("Sheet3").Range("A" & row)
        If Len(website.Value) < 1 Then
            continue = False
        Exit Sub
        End If

        If website Is Nothing Then
            continue = False
        End If

'''Debug.Print website
    With http
        On Error Resume Next
        .Open "GET", website.Value, False
        .send

'''If the website sent a valid response to our request, URLS ARE IN COLUMN A
    If Err.Number = 0 Then
        If .Status = 200 Then
            HTML.body.innerHTML = http.responseText
                Set links = HTML.getElementsByTagName("a")
'''COLUMN C = FACEBOOK
   For Each link In links
      If InStr(UCase(link.outerHTML), "FACEBOOK") Then
      website.Offset(0, 2).Value = link.href
   End If
'''COLUMN D = INSTAGRAM
    If InStr(UCase(link.outerHTML), "INSTAGRAM") Then
        website.Offset(0, 3).Value = link.href
    End If
'''COLUMN E = TWITTER
    If InStr(UCase(link.outerHTML), "TWITTER") Then
        website.Offset(0, 4).Value = link.href
    End If
'''COLUMN F = YOUTUBE
    If InStr(UCase(link.outerHTML), "YOUTUBE") Then
        website.Offset(0, 5).Value = link.href
    End If
'''COLUMN G = LinkedIn
    If InStr(UCase(link.outerHTML), "LINKEDIN") Then
        website.Offset(0, 6).Value = link.href
    End If
Next
    End If
    Set website = Nothing
Else
'''Debug.Print "Error loading page IN COLUMN H"
    website.Offset(0, 8).Value = "Error with website address"
    End If
On Error GoTo 0
 End With
row = row + 1
Loop

Complete.Show '#### THIS FORM DOES NOT SHOW AT THE END ####
''' CLOSE BROWSER
ie.Quit
Set ie = Nothing
Set ElementCol = Nothing
End Sub

Body:
I made a mistake in thinking. To load dynamic content when the server reports that the page has loaded, another pause is necessary. So you would have to pause at every page because you can't check that. Anyway, I don't know how. So now I have implemented it with the faster MSXML2.

I added counters for all found links. If more than one link was found, a comment with the found count is set in the cell. If you go through the same URLs again, the comments and found links will be deleted and if necessary reset.

The counters should give you an overview if you need a different table layout to get all links and not only the last one. In this case you need your own table to enter all links.

Try the following macro. Read the comments carefully.

Sub ScrapeSoMeAndMailAddresses()

'******************************************************
'The macro works on the sheet from which it was started
'******************************************************

Dim url As String
Dim http As Object
Dim htmlDoc As Object
Dim nodeAllLinks As Object
Dim nodeOneLink As Object
Dim currentRow As Long

'Counters to check, if there are more than one address per page
Dim addressCounters(5) As Long
Dim checkCounters As Long

  'Initialize variables
  currentRow = 2
  Set htmlDoc = CreateObject("htmlfile")
  Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")

  'Loop over all URLs in column A in the active table
  Do While ActiveSheet.Cells(currentRow, 1).Value <> ""
    'Scroll if current row > 14
    If currentRow > 14 Then
      ActiveWindow.SmallScroll down:=1
    End If
    'Clear content in current row
    ActiveSheet.Range(Cells(currentRow, 2), Cells(currentRow, 9)).ClearContents
    'Get next url from table
    url = ActiveSheet.Cells(currentRow, 1).Value
    'Load page
    http.Open "GET", url, False
    http.send
    'Check if page loading was successful
    If http.Status = 200 Then
      'Build html document for DOM operations
      htmlDoc.body.innerHTML = http.responseText
      'Create node list from all links of the page
      Set nodeAllLinks = htmlDoc.getElementsByTagName("a")
      'Walk through all links of the node list
      For Each nodeOneLink In nodeAllLinks
        'Check for mail address
        If InStr(1, nodeOneLink.href, "mailto:") Then
          'Write mail address to table in column B
          ActiveSheet.Cells(currentRow, 2).Value = Right(nodeOneLink.href, Len(nodeOneLink.href) - InStr(nodeOneLink.href, ":"))
          'Increment mail address counter
          addressCounters(0) = addressCounters(0) + 1
        End If
        'Check for Facebook address
        If InStr(1, UCase(nodeOneLink.href), "FACEBOOK") Then
          'Write Facebook address to table in column C
          ActiveSheet.Cells(currentRow, 3).Value = nodeOneLink.href
          'Increment Facebook counter
          addressCounters(1) = addressCounters(1) + 1
        End If
        'Check for Instagram address
        If InStr(1, UCase(nodeOneLink.href), "INSTAGRAM") Then
          'Write INSTAGRAM address to table in column D
          ActiveSheet.Cells(currentRow, 4).Value = nodeOneLink.href
          'Increment Instagram counter
          addressCounters(2) = addressCounters(2) + 1
        End If
        'Check for Twitter address
        If InStr(1, UCase(nodeOneLink.href), "TWITTER") Then
          'Write Twitter address to table in column E
          ActiveSheet.Cells(currentRow, 5).Value = nodeOneLink.href
          'Increment Twitter counter
          addressCounters(3) = addressCounters(3) + 1
        End If
        'Check for YouTube address
        If InStr(1, UCase(nodeOneLink.href), "YOUTUBE") Then
          'Write YouTube address to table in column F
          ActiveSheet.Cells(currentRow, 6).Value = nodeOneLink.href
          'Increment YouTube counter
          addressCounters(4) = addressCounters(4) + 1
        End If
        'Check for LinkedIn address
        If InStr(1, UCase(nodeOneLink.href), "LINKEDIN") Then
          'Write LinkedIn address to table in column G
          ActiveSheet.Cells(currentRow, 7).Value = nodeOneLink.href
          'Increment LinkedIn counter
          addressCounters(5) = addressCounters(5) + 1
        End If
      Next nodeOneLink

      'Check counters
      For checkCounters = 0 To 5
        'Delete comment if there is one
        If Not ActiveSheet.Cells(currentRow, checkCounters + 2).Comment Is Nothing Then
          ActiveSheet.Cells(currentRow, checkCounters + 2).Comment.Delete
        End If
        'Set comment if more than 1 link were found
        If addressCounters(checkCounters) > 1 Then
          ActiveSheet.Cells(currentRow, checkCounters + 2).AddComment Text:=CStr(addressCounters(checkCounters))
          ActiveSheet.Cells(currentRow, checkCounters + 2).Comment.Shape.TextFrame.AutoSize = True
        End If
      Next checkCounters
    Else
      'Page not loaded
      'Write message in column H
      ActiveSheet.Cells(currentRow, 9).Value = "Error with website address"
    End If

    'Prepare for next page
    Erase addressCounters
    currentRow = currentRow + 1
  Loop

  'Clean up
  Set http = Nothing
  Set htmlDoc = Nothing
  Set nodeAllLinks = Nothing
  Set nodeOneLink = Nothing

  'Check if this works now
  Complete.Show
End Sub

Edit: Revised code

Since the macro above is more or less a proof of concept, I have now developed a version that meets the requirements of the first comment under this posting. Nothing more to read from the pages, but a lot of work ;-)

You have to create another table which contains all addresses after a macro run. You have to create the headline manually once. I have not implemented a check for duplicate addresses!

The code of the macro is not perfect (all in one, no functions), but it is much more flexible than version 1. If you understand the code, it should be quite easy to integrate additional platforms if needed.

About the thing with Sheet3:

You can access a sheet from VBA either by the name it has on the tab in the normal Excel view or by its index. Sheet3 is the name as far as I understood it. At the top of the Initialize Variables part, you can easily change the two default names Sheet3 and Sheet4 to match the names used on the tabs. You don't have to change anything else.

If you start the macro the content in both sheets will be delete at first.

Please read the comments in the VBA code carefully!

Sub ScrapeSoMeAndMailAddresses()

'Columns for both tables
Const colUrl As Long = 1 'Must always be the first column
Const colMail As Long = 2 'Must always be the first column before SoMe platforms
Const colFacebook As Long = 3
Const colInstagram As Long = 4
Const colTwitter As Long = 5
Const colYouTube As Long = 6
Const colLinkedIn As Long = 7 'Must always be the last column of SoMe platforms
Const colError As Long = 9 'Must always be the last column

Dim url As String
Dim http As Object
Dim htmlDoc As Object
Dim nodeAllLinks As Object
Dim nodeOneLink As Object
Dim pageLoadSuccessful As Boolean
Dim tableUrlsOneAddressLeft As String
Dim tableAllAddresses As String
Dim currentRowTableUrls As Long
Dim lastRowTableUrls As Long
Dim currentRowsTableAll(colUrl To colLinkedIn) As Long
Dim lastRowTableAll As Long
Dim addressCounters(colMail To colLinkedIn) As Long
Dim checkCounters As Long

  'Initialize variables
  tableUrlsOneAddressLeft = "Sheet3"
  currentRowTableUrls = 2 'First row for content
  tableAllAddresses = "Sheet4"
  For checkCounters = colUrl To colLinkedIn
    currentRowsTableAll(checkCounters) = 2 'First rows for content
  Next checkCounters
  Set htmlDoc = CreateObject("htmlfile")
  Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")

  'Clear all contents and comments in the URL source sheet from email column to error column
  lastRowTableUrls = Sheets(tableUrlsOneAddressLeft).Cells(Rows.count, colUrl).End(xlUp).row
  Sheets(tableUrlsOneAddressLeft).Range(Cells(currentRowTableUrls, colMail), Cells(lastRowTableUrls, colError)).ClearContents
  Sheets(tableUrlsOneAddressLeft).Range(Cells(currentRowTableUrls, colMail), Cells(lastRowTableUrls, colError)).ClearComments

  'Delete all rows except headline in the sheet with all addresses
  lastRowTableAll = Sheets(tableAllAddresses).Cells(Rows.count, colUrl).End(xlUp).row
  Sheets(tableAllAddresses).Rows(currentRowsTableAll(colUrl) & ":" & lastRowTableAll).Delete Shift:=xlUp

  'Loop over all URLs in column A in the URL source sheet
  Do While Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, 1).Value <> ""

    '**************************************
    'Scroll for visual monitoring
    'Comment out the following three lines,
    'if Sheet3 is not visible while the
    'macro runs
    'Otherwise a runtime error will occur
    If currentRowTableUrls > 14 Then
      ActiveWindow.SmallScroll down:=1
    End If
    '**************************************

    'Get next url from the URL source sheet
    url = Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colUrl).Value

    'Try to load page
    'Temporarily disable error
    'handling if there is a timeout
    On Error Resume Next
    http.Open "GET", url, False
    http.send
    On Error GoTo 0

    'Check if page loading was successful
    If http.Status = 200 Then
      pageLoadSuccessful = True
    End If

    If pageLoadSuccessful Then
      'Build html document for DOM operations
      htmlDoc.body.innerHTML = http.responseText
      'Create node list from all links of the page
      Set nodeAllLinks = htmlDoc.getElementsByTagName("a")
      'Walk through all links of the node list
      For Each nodeOneLink In nodeAllLinks
        'Check for mail address
        If InStr(1, nodeOneLink.href, "mailto:") Then
          'Write mail address to both tables
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colMail).Value = Right(nodeOneLink.href, Len(nodeOneLink.href) - InStr(nodeOneLink.href, ":"))
          Sheets(tableAllAddresses).Cells(currentRowsTableAll(colMail), colMail).Value = Right(nodeOneLink.href, Len(nodeOneLink.href) - InStr(nodeOneLink.href, ":"))
          'Check if it is a new line in the sheet with all addresses
          If currentRowsTableAll(colMail) >= currentRowsTableAll(colUrl) Then
            'Write URL in the new line of the sheet with all addresses
            Sheets(tableAllAddresses).Cells(currentRowsTableAll(colUrl), colUrl).Value = url
            'Increment url counter
            currentRowsTableAll(colUrl) = currentRowsTableAll(colUrl) + 1
          End If
          'Increment mail counters
          currentRowsTableAll(colMail) = currentRowsTableAll(colMail) + 1
          addressCounters(colMail) = addressCounters(colMail) + 1
        End If
        'Check for Facebook address
        If InStr(1, UCase(nodeOneLink.href), "FACEBOOK") Then
          'Write Facebook address to both tables
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colFacebook).Value = nodeOneLink.href
          Sheets(tableAllAddresses).Cells(currentRowsTableAll(colFacebook), colFacebook).Value = nodeOneLink.href
          'Check if it is a new line in the sheet with all addresses
          If currentRowsTableAll(colFacebook) >= currentRowsTableAll(colUrl) Then
            'Write URL in the new line of the sheet with all addresses
            Sheets(tableAllAddresses).Cells(currentRowsTableAll(colUrl), colUrl).Value = url
            'Increment url counter
            currentRowsTableAll(colUrl) = currentRowsTableAll(colUrl) + 1
          End If
          'Increment Facebook counters
          currentRowsTableAll(colFacebook) = currentRowsTableAll(colFacebook) + 1
          addressCounters(colFacebook) = addressCounters(colFacebook) + 1
        End If
        'Check for Instagram address
        If InStr(1, UCase(nodeOneLink.href), "INSTAGRAM") Then
          'Write INSTAGRAM address to both tables
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colInstagram).Value = nodeOneLink.href
          Sheets(tableAllAddresses).Cells(currentRowsTableAll(colInstagram), colInstagram).Value = nodeOneLink.href
          'Check if it is a new line in the sheet with all addresses
          If currentRowsTableAll(colInstagram) >= currentRowsTableAll(colUrl) Then
            'Write URL in the new line of the sheet with all addresses
            Sheets(tableAllAddresses).Cells(currentRowsTableAll(colUrl), colUrl).Value = url
            'Increment url counter
            currentRowsTableAll(colUrl) = currentRowsTableAll(colUrl) + 1
          End If
          'Increment Instagram counters
          currentRowsTableAll(colInstagram) = currentRowsTableAll(colInstagram) + 1
          addressCounters(colInstagram) = addressCounters(colInstagram) + 1
        End If
        'Check for Twitter address
        If InStr(1, UCase(nodeOneLink.href), "TWITTER") Then
          'Write Twitter address to both tables
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colTwitter).Value = nodeOneLink.href
          Sheets(tableAllAddresses).Cells(currentRowsTableAll(colTwitter), colTwitter).Value = nodeOneLink.href
          'Check if it is a new line in the sheet with all addresses
          If currentRowsTableAll(colTwitter) >= currentRowsTableAll(colUrl) Then
            'Write URL in the new line of the sheet with all addresses
            Sheets(tableAllAddresses).Cells(currentRowsTableAll(colUrl), colUrl).Value = url
            'Increment url counter
            currentRowsTableAll(colUrl) = currentRowsTableAll(colUrl) + 1
          End If
          'Increment Twitter counters
          currentRowsTableAll(colTwitter) = currentRowsTableAll(colTwitter) + 1
          addressCounters(colTwitter) = addressCounters(colTwitter) + 1
        End If
        'Check for YouTube address
        If InStr(1, UCase(nodeOneLink.href), "YOUTUBE") Then
          'Write YouTube address to both tables
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colYouTube).Value = nodeOneLink.href
          Sheets(tableAllAddresses).Cells(currentRowsTableAll(colYouTube), colYouTube).Value = nodeOneLink.href
          'Check if it is a new line in the sheet with all addresses
          If currentRowsTableAll(colYouTube) >= currentRowsTableAll(colUrl) Then
            'Write URL in the new line of the sheet with all addresses
            Sheets(tableAllAddresses).Cells(currentRowsTableAll(colUrl), colUrl).Value = url
            'Increment url counter
            currentRowsTableAll(colUrl) = currentRowsTableAll(colUrl) + 1
          End If
          'Increment YouTube counters
          currentRowsTableAll(colYouTube) = currentRowsTableAll(colYouTube) + 1
          addressCounters(colYouTube) = addressCounters(colYouTube) + 1
        End If
        'Check for LinkedIn address
        If InStr(1, UCase(nodeOneLink.href), "LINKEDIN") Then
          'Write LinkedIn address to both tables
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colLinkedIn).Value = nodeOneLink.href
          Sheets(tableAllAddresses).Cells(currentRowsTableAll(colLinkedIn), colLinkedIn).Value = nodeOneLink.href
          'Check if it is a new line in the sheet with all addresses
          If currentRowsTableAll(colLinkedIn) >= currentRowsTableAll(colUrl) Then
            'Write URL in the new line of the sheet with all addresses
            Sheets(tableAllAddresses).Cells(currentRowsTableAll(colUrl), colUrl).Value = url
            'Increment url counter
            currentRowsTableAll(colUrl) = currentRowsTableAll(colUrl) + 1
          End If
          'Increment LinkedIn counters
          currentRowsTableAll(colLinkedIn) = currentRowsTableAll(colLinkedIn) + 1
          addressCounters(colLinkedIn) = addressCounters(colLinkedIn) + 1
        End If
      Next nodeOneLink

      'Check address counters
      For checkCounters = colMail To colLinkedIn
        'Set comment if more than 1 link were found
        If addressCounters(checkCounters) > 1 Then
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, checkCounters).AddComment Text:=CStr(addressCounters(checkCounters))
          Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, checkCounters).Comment.Shape.TextFrame.AutoSize = True
        End If
      Next checkCounters
    Else
      'Page not loaded
      'Write message URL table
      Sheets(tableUrlsOneAddressLeft).Cells(currentRowTableUrls, colError).Value = "Error with URL or timeout"
    End If

    'Prepare for next page
    pageLoadSuccessful = False
    Erase addressCounters
    lastRowTableAll = Sheets(tableAllAddresses).Cells(Rows.count, colUrl).End(xlUp).row
    For checkCounters = colUrl To colLinkedIn
      currentRowsTableAll(checkCounters) = lastRowTableAll + 1 'First rows for next page content
    Next checkCounters
    currentRowTableUrls = currentRowTableUrls + 1
  Loop

  'Clean up
  Set http = Nothing
  Set htmlDoc = Nothing
  Set nodeAllLinks = Nothing
  Set nodeOneLink = Nothing

  'Check if this works now
  Complete.Show
End Sub