问:
Clear Button issue in Custom Entry Renderer for Android
I am creating a custom renderer for an entry. I am mainly trying to add an icon to the left of the entry field. I have achieved this using SetCompoundDrawablesRelativeWithIntrinsicBounds() in Android and using LeftView in iOS.

The problem occurs when ClearButtonVisibility is set to "while editing". After typing something in the entry and the clear button is clicked, the left icon is cleared along with the text (This only occurs in Android. In iOS, only the text is cleared. I realized the built-in clear button image is in the compound drawables so I am setting the compound drawables with my icon as well as the built-in icon.

What is the best workaround to this? I would like it so that when the clear button is clicked, only the text is cleared and not the icon.

Note: The icon is cleared momentarily. When any other event is fired, the icon returns.

CustomEntry - before click

CustomEntry - after click

CustomEntry - after some event

Android.Renderer:

```<code>[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
namespace Styles.Android.Renderers
{
    public class CustomEntryRenderer : EntryRenderer
    {
        public CustomEntryRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // update control UI
            UpdateControl();

            base.OnElementPropertyChanged(sender, e);
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            // update control UI
            UpdateControl();

            base.OnElementChanged(e);
        }

        private void UpdateControl()
        {
            if (Element == null || Control == null)
                return;

            var entry = Element as CustomEntry;

            // set border/background
            var gradientBackground = new GradientDrawable();
            gradientBackground.SetShape(ShapeType.Rectangle);
            gradientBackground.SetColor(Element.BackgroundColor.ToAndroid());
            gradientBackground.SetCornerRadius(entry.CornerRadius);
            gradientBackground.SetStroke(entry.BorderWidth, entry.BorderColor.ToAndroid());
            Control.SetBackground(gradientBackground);

            // set appropriate icon
            int resID = Resources.GetIdentifier("icon_image", "drawable", this.Context.PackageName);
            var drawable = ContextCompat.GetDrawable(this.Context, resID);

            Control.SetCompoundDrawablesRelativeWithIntrinsicBounds(drawable, null, Control.GetCompoundDrawables()[2], null);
            Control.CompoundDrawablePadding = entry.IconPadding;
            paddingLeft = entry.IconPadding;

            // set padding
            Control.SetPadding(Control.PaddingLeft, Control.PaddingTop, Control.PaddingRight, Control.PaddingBottom);
        }
    }
}
</code>```

答:
You could overwrite OnTouchListener to clean the text and SetCompoundDrawable again.

change your CustomRenderer like below:

```<code>[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
namespace Styles.Android.Renderers
{
    public class CustomEntryRenderer : EntryRenderer
    {
        static Drawable drawableLeft;
        static Drawable drawableRight;
        public CustomEntryRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // update control UI
            UpdateControl();

            base.OnElementPropertyChanged(sender, e);
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            // update control UI
            UpdateControl();

            base.OnElementChanged(e);
        }

        private void UpdateControl()
        {
            if (Element == null || Control == null)
                return;

            var entry = Element as CustomEntry;

            // set border/background
            var gradientBackground = new GradientDrawable();
            gradientBackground.SetShape(ShapeType.Rectangle);
            gradientBackground.SetColor(Element.BackgroundColor.ToAndroid());
            gradientBackground.SetCornerRadius(entry.CornerRadius);
            gradientBackground.SetStroke(entry.BorderWidth, entry.BorderColor.ToAndroid());
            Control.SetBackground(gradientBackground);

            // set appropriate icon
            int resID = Resources.GetIdentifier("icon_image", "drawable", this.Context.PackageName);
            drawableLeft = ContextCompat.GetDrawable(this.Context, resID);
            drawableRight = Control.GetCompoundDrawables()[2];
            Control.SetCompoundDrawablesRelativeWithIntrinsicBounds(drawableLeft, null, drawableRight , null);
            Control.CompoundDrawablePadding = entry.IconPadding;
            paddingLeft = entry.IconPadding;

            // set padding
            Control.SetPadding(Control.PaddingLeft, Control.PaddingTop, Control.PaddingRight, Control.PaddingBottom);

            Control.SetOnTouchListener(new OnDrawableTouchListener());
        }

     public class OnDrawableTouchListener : Java.Lang.Object, Android.Views.View.IOnTouchListener
     {
        public bool OnTouch(Android.Views.View v, MotionEvent e)
        {
            if (v is EditText && e.Action == MotionEventActions.Up)
            {
                EditText editText = (EditText)v;
                editText.SetCompoundDrawablesRelativeWithIntrinsicBounds(drawableLeft, null, drawableRight, null);
                if (drawableRight != null)
                {

                    bool touchable = e.GetX() > (editText.Width
                    - editText.PaddingRight - drawableRight.IntrinsicWidth)
                    && (e.GetX() < ((editText.Width - editText.PaddingRight)));
                    if (touchable)
                    {
                        Console.WriteLine(editText.Text);
                        editText.Text = "";
                        editText.SetCompoundDrawablesRelativeWithIntrinsicBounds(drawableLeft, null, drawableRight, null);
                        return true;
                    }

                }
            }

            return false;
        }

     }

    }
}
</code>```

Body:
I am creating a custom renderer for an entry. I am mainly trying to add an icon to the left of the entry field. I have achieved this using SetCompoundDrawablesRelativeWithIntrinsicBounds() in Android and using LeftView in iOS.

The problem occurs when ClearButtonVisibility is set to "while editing". After typing something in the entry and the clear button is clicked, the left icon is cleared along with the text (This only occurs in Android. In iOS, only the text is cleared. I realized the built-in clear button image is in the compound drawables so I am setting the compound drawables with my icon as well as the built-in icon.

What is the best workaround to this? I would like it so that when the clear button is clicked, only the text is cleared and not the icon.

Note: The icon is cleared momentarily. When any other event is fired, the icon returns.

CustomEntry - before click

CustomEntry - after click

CustomEntry - after some event

Android.Renderer:

[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
namespace Styles.Android.Renderers
{
    public class CustomEntryRenderer : EntryRenderer
    {
        public CustomEntryRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // update control UI
            UpdateControl();

            base.OnElementPropertyChanged(sender, e);
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            // update control UI
            UpdateControl();

            base.OnElementChanged(e);
        }

        private void UpdateControl()
        {
            if (Element == null || Control == null)
                return;

            var entry = Element as CustomEntry;

            // set border/background
            var gradientBackground = new GradientDrawable();
            gradientBackground.SetShape(ShapeType.Rectangle);
            gradientBackground.SetColor(Element.BackgroundColor.ToAndroid());
            gradientBackground.SetCornerRadius(entry.CornerRadius);
            gradientBackground.SetStroke(entry.BorderWidth, entry.BorderColor.ToAndroid());
            Control.SetBackground(gradientBackground);

            // set appropriate icon
            int resID = Resources.GetIdentifier("icon_image", "drawable", this.Context.PackageName);
            var drawable = ContextCompat.GetDrawable(this.Context, resID);

            Control.SetCompoundDrawablesRelativeWithIntrinsicBounds(drawable, null, Control.GetCompoundDrawables()[2], null);
            Control.CompoundDrawablePadding = entry.IconPadding;
            paddingLeft = entry.IconPadding;

            // set padding
            Control.SetPadding(Control.PaddingLeft, Control.PaddingTop, Control.PaddingRight, Control.PaddingBottom);
        }
    }
}

Body:
You could overwrite OnTouchListener to clean the text and SetCompoundDrawable again.

change your CustomRenderer like below:

[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
namespace Styles.Android.Renderers
{
    public class CustomEntryRenderer : EntryRenderer
    {
        static Drawable drawableLeft;
        static Drawable drawableRight;
        public CustomEntryRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // update control UI
            UpdateControl();

            base.OnElementPropertyChanged(sender, e);
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            // update control UI
            UpdateControl();

            base.OnElementChanged(e);
        }

        private void UpdateControl()
        {
            if (Element == null || Control == null)
                return;

            var entry = Element as CustomEntry;

            // set border/background
            var gradientBackground = new GradientDrawable();
            gradientBackground.SetShape(ShapeType.Rectangle);
            gradientBackground.SetColor(Element.BackgroundColor.ToAndroid());
            gradientBackground.SetCornerRadius(entry.CornerRadius);
            gradientBackground.SetStroke(entry.BorderWidth, entry.BorderColor.ToAndroid());
            Control.SetBackground(gradientBackground);

            // set appropriate icon
            int resID = Resources.GetIdentifier("icon_image", "drawable", this.Context.PackageName);
            drawableLeft = ContextCompat.GetDrawable(this.Context, resID);
            drawableRight = Control.GetCompoundDrawables()[2];
            Control.SetCompoundDrawablesRelativeWithIntrinsicBounds(drawableLeft, null, drawableRight , null);
            Control.CompoundDrawablePadding = entry.IconPadding;
            paddingLeft = entry.IconPadding;

            // set padding
            Control.SetPadding(Control.PaddingLeft, Control.PaddingTop, Control.PaddingRight, Control.PaddingBottom);

            Control.SetOnTouchListener(new OnDrawableTouchListener());
        }

     public class OnDrawableTouchListener : Java.Lang.Object, Android.Views.View.IOnTouchListener
     {
        public bool OnTouch(Android.Views.View v, MotionEvent e)
        {
            if (v is EditText && e.Action == MotionEventActions.Up)
            {
                EditText editText = (EditText)v;
                editText.SetCompoundDrawablesRelativeWithIntrinsicBounds(drawableLeft, null, drawableRight, null);
                if (drawableRight != null)
                {

                    bool touchable = e.GetX() > (editText.Width
                    - editText.PaddingRight - drawableRight.IntrinsicWidth)
                    && (e.GetX() < ((editText.Width - editText.PaddingRight)));
                    if (touchable)
                    {
                        Console.WriteLine(editText.Text);
                        editText.Text = "";
                        editText.SetCompoundDrawablesRelativeWithIntrinsicBounds(drawableLeft, null, drawableRight, null);
                        return true;
                    }

                }
            }

            return false;
        }

     }

    }
}


来源: stackexchange

问:
Axios - New Instance overrides Global Defaults
quick question on implementation of multiple axios instances.

I call my own API as needed inside my mobile app. Certain API endpoints are protected by checking that the token issued by Google Signin or Facebook Signin is authenticated and matches the expected user. Other endpoints do not require a token and actually require the frontend to not send a token at all to proceed down the proper logic path on the backend.

I set the global axios instance when I fetch the user token on frontend. I am hoping that all axios calls include the token by default. To achieve this, I set the default Authorization header as such:

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

...

axios.defaults.headers.common.Authorization = `Bearer ${fbUserInfo.accessToken}`
</code>```

This code runs on the initial page of the app that is loaded, so everytime I use axios somewhere else in the app, the token is now included. It works as expected until I proceed to the following step.

In order to create some recurring API calls where a token should not be included, I create a "tokenless" instance inside one of my redux action creators.

```<code>const axiosTokenlessInstance = axios.create()
...
axiosTokenlessInstance.defaults.headers.common.Authorization = false
</code>```

This does indeed override the default axios settings when I call it directly, however, I've realized that it also has overridden my default settings when I just call axios directly again.

I expected the behavior to be that I could still call axios.post or axios.get elsewhere and it would still include the token. Was I mistaken and do I have to create a "tokened" instance? I'd prefer not to do this as I'd have to go through and replaced tokened instance explicitly everywhere rather than just using axios default. Thanks!

答:
Try creating a file called setAuthToken.js that handles the auth instance separately. This way any time you need to use the auth, you can just call this function ( I would even suggest limiting to calling this auth only once and having the token saved in the users localStorage):

```<code>import axios from 'axios';

const setAuthToken = token => {
if(token){
    axios.defaults.headers.common['x-auth-token'] = token;
}
else{
  delete axios.defaults.headers.common['x-auth-token'];
}

}

export default setAuthToken;
</code>```

Now let's say you have a backend function call that needs auth verification, you can do it like so:

```<code>import setAuthToken from "../utils/setAuthToken";
export const loginUser = (token) => async (dispatch) => {
  if (localStorage.token) {
    setAuthToken(localStorage.token);
  }
  try {
    const res = await axios.get("/api/auth");
    dispatch({
      type: USER_LOGGED,
      payload: res.data,
    });
  } catch (err) {
    dispatch({
      type: AUTH_ERROR,
    });
  }
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
quick question on implementation of multiple axios instances.

I call my own API as needed inside my mobile app. Certain API endpoints are protected by checking that the token issued by Google Signin or Facebook Signin is authenticated and matches the expected user. Other endpoints do not require a token and actually require the frontend to not send a token at all to proceed down the proper logic path on the backend.

I set the global axios instance when I fetch the user token on frontend. I am hoping that all axios calls include the token by default. To achieve this, I set the default Authorization header as such:

import axios from 'axios'

...

axios.defaults.headers.common.Authorization = `Bearer ${fbUserInfo.accessToken}`

This code runs on the initial page of the app that is loaded, so everytime I use axios somewhere else in the app, the token is now included. It works as expected until I proceed to the following step.

In order to create some recurring API calls where a token should not be included, I create a "tokenless" instance inside one of my redux action creators.

const axiosTokenlessInstance = axios.create()
...
axiosTokenlessInstance.defaults.headers.common.Authorization = false

This does indeed override the default axios settings when I call it directly, however, I've realized that it also has overridden my default settings when I just call axios directly again.

I expected the behavior to be that I could still call axios.post or axios.get elsewhere and it would still include the token. Was I mistaken and do I have to create a "tokened" instance? I'd prefer not to do this as I'd have to go through and replaced tokened instance explicitly everywhere rather than just using axios default. Thanks!

Body:
Try creating a file called setAuthToken.js that handles the auth instance separately. This way any time you need to use the auth, you can just call this function ( I would even suggest limiting to calling this auth only once and having the token saved in the users localStorage):

import axios from 'axios';

const setAuthToken = token => {
if(token){
    axios.defaults.headers.common['x-auth-token'] = token;
}
else{
  delete axios.defaults.headers.common['x-auth-token'];
}

}

export default setAuthToken;

Now let's say you have a backend function call that needs auth verification, you can do it like so:

import setAuthToken from "../utils/setAuthToken";
export const loginUser = (token) => async (dispatch) => {
  if (localStorage.token) {
    setAuthToken(localStorage.token);
  }
  try {
    const res = await axios.get("/api/auth");
    dispatch({
      type: USER_LOGGED,
      payload: res.data,
    });
  } catch (err) {
    dispatch({
      type: AUTH_ERROR,
    });
  }
};


问:
Getting accurate file size in megabytes?
How can I get the accurate file size in MB? I tried this:

```<code>compressed_file_size = File.size("Compressed/#{project}.tar.bz2") / 1024000

puts "file size is #{compressed_file_size} MB"
</code>```

But it chopped the 0.9 and showed 2 MB instead of 2.9 MB

答:
Try:

```<code>compressed_file_size = File.size("Compressed/#{project}.tar.bz2").to_f / 2**20
formatted_file_size = '%.2f' % compressed_file_size
</code>```

One-liner:

```<code>compressed_file_size = '%.2f' % (File.size("Compressed/#{project}.tar.bz2").to_f / 2**20)
</code>```

or:

```<code>compressed_file_size = (File.size("Compressed/#{project}.tar.bz2").to_f / 2**20).round(2)
</code>```

Further information on %-operator of String:
http://ruby-doc.org/core-1.9/classes/String.html#M000207

BTW: I prefer "MiB" instead of "MB" if I use base2 calculations (see: http://en.wikipedia.org/wiki/Mebibyte)

ContentLicense: CC BY-SA 3.0

Body:
How can I get the accurate file size in MB? I tried this:

compressed_file_size = File.size("Compressed/#{project}.tar.bz2") / 1024000

puts "file size is #{compressed_file_size} MB"

But it chopped the 0.9 and showed 2 MB instead of 2.9 MB

Body:
Try:

compressed_file_size = File.size("Compressed/#{project}.tar.bz2").to_f / 2**20
formatted_file_size = '%.2f' % compressed_file_size

One-liner:

compressed_file_size = '%.2f' % (File.size("Compressed/#{project}.tar.bz2").to_f / 2**20)

or:

compressed_file_size = (File.size("Compressed/#{project}.tar.bz2").to_f / 2**20).round(2)

Further information on %-operator of String:
http://ruby-doc.org/core-1.9/classes/String.html#M000207

BTW: I prefer "MiB" instead of "MB" if I use base2 calculations (see: http://en.wikipedia.org/wiki/Mebibyte)


问:
Is it possible to fetch/parse JSON data from one component to a different rendered/dynamic route? (React JS)
I am new to reactJS and just started learning it for a coding assignment, but I am stuck on this one problem. I created an api in a component that FETCHes photo and photo album data from the online JSON prototyping website, and I want to use that data to display on a user page (only photos and albums related to that specific user/userID). The user page is a dynamic child component of the parent component (the home page). here is what it looks like so far

This is for the JSON data. I call it apiData

```<code>import React, { Component } from "react";

class apiData extends Component {
    state = {
        photos: [],
        albums: [],
        isLoading: false
    };
    componentDidMount() {
        this.loadData();
    }

    loadData = async () => {
        const photos = await fetch(
            "https://jsonplaceholder.typicode.com/photos"
        );
        const albums = await fetch(
            "https://jsonplaceholder.typicode.com/albums"
        );
        const photoData = await photos.json();
        const albumData = await albums.json();
        this.setState({ isLoading: true, photos: photoData, albums: albumData});
    };
    render() {
        return (
            <div className="App">
                <p> dataObject={this.state.results}</p>
            </div>
        );
    }
}
</code>```

This is the rendered/dynamic route. currently, I am using
const userPhoto = apiData.photos.find((userPhoto) =>{
to try to access the API, but I get an error that says

TypeError: Cannot read property 'find' of undefined"

(keep in mind, these 2 components are coded on the same .js file)

```<code>    const userPhotoPage = ({match}) => {
    const userPhoto = apiData.photos.find((userPhoto) =>{
        return parseInt(match.params.id) == userPhoto.id
    })

    return <>
        {match.isExact && <>
            <h1>{userPhoto.title}</h1>
            <p>image = {userPhoto.url}</p>
            </>}
        </>
    }
</code>```

I want my userPhotoPage function to successfully access the data from apiData, so I can manipulate it and add data to the photo page, but I'm not sure if this is possible? If I need to provide more information I'll gladly give it!

答: It looks like your trying to access the find method on an undefined object. First off, the .find() method is an iterator on arrays. I tried fetching the data from your JSON photos API but for some reason, it's hanging on this end. I'm not sure if that API actually returns an array. I would look into that first. Next, even if it returns an array and your able to chain the find method on it you're still left with the issue of function scope. The photo objects is scoped to/private your loadData async funtion. You will not be able to access it outside of the function. </p>

Body:
I am new to reactJS and just started learning it for a coding assignment, but I am stuck on this one problem. I created an api in a component that FETCHes photo and photo album data from the online JSON prototyping website, and I want to use that data to display on a user page (only photos and albums related to that specific user/userID). The user page is a dynamic child component of the parent component (the home page). here is what it looks like so far

This is for the JSON data. I call it apiData

import React, { Component } from "react";

class apiData extends Component {
    state = {
        photos: [],
        albums: [],
        isLoading: false
    };
    componentDidMount() {
        this.loadData();
    }

    loadData = async () => {
        const photos = await fetch(
            "https://jsonplaceholder.typicode.com/photos"
        );
        const albums = await fetch(
            "https://jsonplaceholder.typicode.com/albums"
        );
        const photoData = await photos.json();
        const albumData = await albums.json();
        this.setState({ isLoading: true, photos: photoData, albums: albumData});
    };
    render() {
        return (

 dataObject={this.state.results}

        );
    }
}

This is the rendered/dynamic route. currently, I am using
const userPhoto = apiData.photos.find((userPhoto) =>{
to try to access the API, but I get an error that says

TypeError: Cannot read property 'find' of undefined"

(keep in mind, these 2 components are coded on the same .js file)

    const userPhotoPage = ({match}) => {
    const userPhoto = apiData.photos.find((userPhoto) =>{
        return parseInt(match.params.id) == userPhoto.id
    })

    return <>
        {match.isExact && <>

{userPhoto.title}

image = {userPhoto.url}

            </>}
        </>
    }

I want my userPhotoPage function to successfully access the data from apiData, so I can manipulate it and add data to the photo page, but I'm not sure if this is possible? If I need to provide more information I'll gladly give it!


问:
Pausing and Resuming a Thread in Android. Studio
I just want to create another thread, I need to have it to keep doing something until I click button A, then resume when I click on Button B, that's all.

Thread t = new Thread(new Runnable(){

@Override

public void run(){

while(bool) { .... }

}});

t.start();
```

This is the format that I'm trying to follow. I start at the onCreate, but how do I pause and resume a thread?

答:
maybe you can use another flag to do this

example:

private boolean isPause = false;

Thread t = new Thread(new Runnable(){

@Override

public void run(){

 while(bool) {

  if(isPause){ Thread.sleep(500); continue; }

  ....

 }

}});

t.start();

buttonA.setOnClickListener(new View.OnClickListener() {

             Override

             public void onClick(View view) {

                  isPause = true;

             }

        });

buttonB.setOnClickListener(new View.OnClickListener() {

             Override

             public void onClick(View view) {

                  isPause = false;

             }

        });

Body:
I just want to create another thread, I need to have it to keep doing something until I click button A, then resume when I click on Button B, that's all.

Thread t = new Thread(new Runnable(){

@Override

public void run(){

while(bool) { .... }

}});

t.start();

This is the format that I'm trying to follow. I start at the onCreate, but how do I pause and resume a thread?


问:
MailApp.sendEmail method doesn't get through to accounts with URL in the body - Message Blocked
I am working on Google Apps Script. I am trying to send email as follows:

```<code>function test_sendmail(){
  var subject = "subject";
  var body = "https://www.google.com/";
  var emailBody = body;
  var options = {
    htmlBody: body
  }

  var recipient = "XXXXXXXXX@gmail.com";

  MailApp.sendEmail(recipient, subject, emailBody, options);
}
</code>```

"XXXXXXXXX@gmail.com"(email address A) is not valid, but it's only for showing you an example.  I use a real email address in the GAS execution.

The GAS execution is run by another G-suite domain google account(email address B) by which account the code is written.

The email address A has editing rights to the spreadsheet that has the above code in the GAS editor.

But, the email from the above function doesn't get through the email address A. I got this email in the email address B.

LEARN MORE:
https://support.google.com/mail/answer/6596?visit_id=637267406328019079-2003975007&rd=1

Then, I replace the email address with the email address B. and I tried to send it, and it did get through successfully.

Secondly, I changed the URL part:

```<code>var body = "https://www.google.com/";
</code>```

to:

```<code>var body = "";
</code>```

Then, the email successfully get through to both email addresses A and B.

The results listed as below:

The failure of sending email with URL to email address like the email address A has occurred recently like from 1 week or 2 weeks ago. Until then, the 4 cases had been successfully done before. I have no idea why this started happening recently.

I checked if the sender email address B is in the contact list of the recipient email address A.

It is not in my contacts.

But when I searched it, it appeared, so it seems in all contacts.

Added 1:
I tried sending email to the email address C which is another G-suite mail address in the same domain as the email address B, but email address C doesn't have rights to the spreadsheet and the editor.

It sent to the email C successfully even it has no right to the spreadsheet.

Added 2:
I tried sending email to the email address D which is other email address that is neither G-suite domain or @google.com address. The result is the same as the email address A.

答:
Gmail anti-spam algorithms are complex. To prevent that the messages sent by your script being blocked by them, follow the guidelines on Prevent mail to Gmail users from being blocked or sent to spam

Possible Workaround

One of my clients had the same issue, I replaced MailApp.sendEmail(message) by GmailApp.sendEmail(recipient,subject,body,options) apparently this worked (No bounce messages after 10 minutes)

Rafa Guillermo added in a comment:

Just want to add that in this case if this is an ongoing issue you should get your admin to contact G Suite support

If you hasn't access to G Suite Support I think that you could report this issue to Google by using Google Feedback (Open Gmail web UI > click the settings button (gear icon) > Send feedback)

Related

MailApp.sendEmail() in Google Apps Script not sending email (it looks that this is first Q/A about this issue that also suggest replace MailApp by GmailApp)

Message blocked when sending email from Google Script

Body:
I am working on Google Apps Script. I am trying to send email as follows:

function test_sendmail(){
  var subject = "subject";
  var body = "https://www.google.com/";
  var emailBody = body;
  var options = {
    htmlBody: body
  }

  var recipient = "XXXXXXXXX@gmail.com";

  MailApp.sendEmail(recipient, subject, emailBody, options);
}

"XXXXXXXXX@gmail.com"(email address A) is not valid, but it's only for showing you an example.  I use a real email address in the GAS execution.

The GAS execution is run by another G-suite domain google account(email address B) by which account the code is written.

The email address A has editing rights to the spreadsheet that has the above code in the GAS editor.

But, the email from the above function doesn't get through the email address A. I got this email in the email address B.

LEARN MORE:
https://support.google.com/mail/answer/6596?visit_id=637267406328019079-2003975007&rd=1

Then, I replace the email address with the email address B. and I tried to send it, and it did get through successfully.

Secondly, I changed the URL part:

var body = "https://www.google.com/";

to:

var body = "";

Then, the email successfully get through to both email addresses A and B.

The results listed as below:

The failure of sending email with URL to email address like the email address A has occurred recently like from 1 week or 2 weeks ago. Until then, the 4 cases had been successfully done before. I have no idea why this started happening recently.

I checked if the sender email address B is in the contact list of the recipient email address A.

It is not in my contacts.

But when I searched it, it appeared, so it seems in all contacts.

Added 1:
I tried sending email to the email address C which is another G-suite mail address in the same domain as the email address B, but email address C doesn't have rights to the spreadsheet and the editor.

It sent to the email C successfully even it has no right to the spreadsheet.

Added 2:
I tried sending email to the email address D which is other email address that is neither G-suite domain or @google.com address. The result is the same as the email address A.


问:
C++ Vectors insertion and iterators confusion
```<code>int main(){
    vector<int> veclist;
    veclist.push_back(90);
    veclist.push_back(80);
    veclist.push_back(70);

    vector<int>::iterator it;
    it=veclist.begin();
    veclist.insert(it,20);
    cout << *it << endl;  // prints 20
    it++;
    veclist.insert(it,99);
    cout << *it <<endl;  // line abc : prints 0
}
</code>```

<p>Hi, I am working with vectors and iterators in C++. In the above code, why is "line abc" printing 0. Shouldn't it be printing 99 instead? When I print all the vector elements using a for loop, 99 is also printed but why isn't line abc doing so? I am dereferencing the iterator *it, and I expected it to hold the element 99. </p>

答:
When inserting in a vector, all previous iterators are invalidated. Everything after veclist.insert(it,20) is undefined behavior.

To be more precise about what happens under the hood the reason the first print works and the second doesn't is because of the allocated std::vector capacity. Most implementations allocate only 2^N memory chunks.

Therefore, initial vector has capacity of 4. When you increase size from 3 to 4, all previous iterators happen to remain valid. However, when size grows from 4 to 8, memory is copied in a new region, therefore you're accessing deleted memory.

To solve this, you can simply use the result of std::vector::insert, as the valid iterator pointing to the inserted element:

e.g.

```<code>it = veclist.insert(it,20);
</code>```

Body:
int main(){
    vector<int> veclist;
    veclist.push_back(90);
    veclist.push_back(80);
    veclist.push_back(70);

    vector<int>::iterator it;
    it=veclist.begin();
    veclist.insert(it,20);
    cout << *it << endl;  // prints 20
    it++;
    veclist.insert(it,99);
    cout << *it <<endl;  // line abc : prints 0
}

Hi, I am working with vectors and iterators in C++. In the above code, why is "line abc" printing 0. Shouldn't it be printing 99 instead? When I print all the vector elements using a for loop, 99 is also printed but why isn't line abc doing so? I am dereferencing the iterator *it, and I expected it to hold the element 99.

Body:
When inserting in a vector, all previous iterators are invalidated. Everything after veclist.insert(it,20) is undefined behavior.

To be more precise about what happens under the hood the reason the first print works and the second doesn't is because of the allocated std::vector capacity. Most implementations allocate only 2^N memory chunks.

Therefore, initial vector has capacity of 4. When you increase size from 3 to 4, all previous iterators happen to remain valid. However, when size grows from 4 to 8, memory is copied in a new region, therefore you're accessing deleted memory.

To solve this, you can simply use the result of std::vector::insert, as the valid iterator pointing to the inserted element:

e.g.

it = veclist.insert(it,20);


问:
how can i recursively rename folders in windows matching string and ignoring case
I have subfolders which have names:

original_Optimize

Original_optimize

original_optimize

Original_Optimize

I would like to rename all of these to:

Original_Optimize

Is there an easy way of doing this in windows (perhaps using powershell or something in command prompt ) ?

答:
Try this. </p>

```<code>Get-ChildItem C:\path-to-directory -Recurse -Filter *foo* | Rename-Item -NewName { $_.name -replace 'foo', 'bar'} -verbose
</code>```

Body:
Try this.

Get-ChildItem C:\path-to-directory -Recurse -Filter *foo* | Rename-Item -NewName { $_.name -replace 'foo', 'bar'} -verbose


问:
How can I output all objects in a vector using for loop in c++
A class BookLibrary constructs a vector of objects of class BookInfo. The task is to add some 'books' (objects of class BookInfo) into the vector and print them out. For some reason, a conventional for(unsigned int i = 0; i < vector.size(); i++) cout << vector[i] << endl; loop is not working. This is a homework project from Savitch textbook "Problem Solving with C++".

Here's the code:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class BookInfo
{
public:
    BookInfo(string newAuthor, string newTitle);
    BookInfo(string newTitle);
    string getName();
    string getAuthor();
    string getTitle();
private:
    string author;
    string title;
};

class BookLibrary
{
public:
    BookLibrary();
    BookLibrary(vector<BookInfo> newLibrary);
    void add(BookInfo newBook);
    void size();
    void printInfo();
private:
    vector<BookInfo> library;
};

int main()
{
    BookLibrary library1;
    BookInfo book1("Michael Krichton", "Jurassic Park");
    BookInfo book2("War and Peace"), book3("Valter Savitch", "Programming in C++");
    library1.add(book1);
    library1.add(book2);
    library1.add(book3);
    library1.size();
    library1.printInfo();
    return 0;
}

BookInfo::BookInfo(string newAuthor, string newTitle)
{
    author = newAuthor;
    title = newTitle;
}

BookInfo::BookInfo(string newTitle) :
    title(newTitle), author("unknown")
{}

string BookInfo::getName()
{
    return (author + " " + title);
}

string BookInfo::getAuthor()
{
    return author;
}

string BookInfo::getTitle()
{
    return title;
}

BookLibrary::BookLibrary()
{}

BookLibrary::BookLibrary(vector<BookInfo> newLibrary)
{
    library = newLibrary;
}

void BookLibrary::add(BookInfo newBook)
{
    library.push_back(newBook);
}

void BookLibrary::size()
{
    cout << library.size();
}

void BookLibrary::printInfo()
{
    for (unsigned int i = 0; i < library.size(); i++)
        cout << library[i] << endl;
}
```

It underlines the cout << in the last line.

答:
Your loop is not able to print out a BookInfo object, because you have not defined an operator<< for BookInfo.  As such, a statement like cout << library[i] does not know what to do with the BookInfo that library[i] returns.

You need to add that operator, eg:

class BookInfo
{
public:
    ...

    friend ostream& operator<<(ostream &os, const BookInfo &book)
    {
        os << "\"" << book.title << "\" by " << book.author;
        return os;
    }

    ...
};
```

<p>If you want to use your <code>getName()</code> method instead, you would need to declare it as <code>const</code> (which you should do anyway for all of your getters), eg:</p>

<pre class="lang-cpp prettyprint-override"><code>class BookInfo
{
public:
    ...
    string getName() const;
    ...

    friend ostream& operator<<(ostream &os, const BookInfo &book)
    {
        os << book.getName();
        return os;
    }

    ...
};

string BookInfo::getName() const
{
    return ...;
}
</code>```

Body:
A class BookLibrary constructs a vector of objects of class BookInfo. The task is to add some 'books' (objects of class BookInfo) into the vector and print them out. For some reason, a conventional for(unsigned int i = 0; i < vector.size(); i++) cout << vector[i] << endl; loop is not working. This is a homework project from Savitch textbook "Problem Solving with C++".

Here's the code:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class BookInfo
{
public:
    BookInfo(string newAuthor, string newTitle);
    BookInfo(string newTitle);
    string getName();
    string getAuthor();
    string getTitle();
private:
    string author;
    string title;
};

class BookLibrary
{
public:
    BookLibrary();
    BookLibrary(vector<BookInfo> newLibrary);
    void add(BookInfo newBook);
    void size();
    void printInfo();
private:
    vector<BookInfo> library;
};

int main()
{
    BookLibrary library1;
    BookInfo book1("Michael Krichton", "Jurassic Park");
    BookInfo book2("War and Peace"), book3("Valter Savitch", "Programming in C++");
    library1.add(book1);
    library1.add(book2);
    library1.add(book3);
    library1.size();
    library1.printInfo();
    return 0;
}

BookInfo::BookInfo(string newAuthor, string newTitle)
{
    author = newAuthor;
    title = newTitle;
}

BookInfo::BookInfo(string newTitle) :
    title(newTitle), author("unknown")
{}

string BookInfo::getName()
{
    return (author + " " + title);
}

string BookInfo::getAuthor()
{
    return author;
}

string BookInfo::getTitle()
{
    return title;
}

BookLibrary::BookLibrary()
{}

BookLibrary::BookLibrary(vector<BookInfo> newLibrary)
{
    library = newLibrary;
}

void BookLibrary::add(BookInfo newBook)
{
    library.push_back(newBook);
}

void BookLibrary::size()
{
    cout << library.size();
}

void BookLibrary::printInfo()
{
    for (unsigned int i = 0; i < library.size(); i++)
        cout << library[i] << endl;
}

It underlines the cout << in the last line.

Body:
Your loop is not able to print out a BookInfo object, because you have not defined an operator<< for BookInfo.  As such, a statement like cout << library[i] does not know what to do with the BookInfo that library[i] returns.

You need to add that operator, eg:

class BookInfo
{
public:
    ...

    friend ostream& operator<<(ostream &os, const BookInfo &book)
    {
        os << "\"" << book.title << "\" by " << book.author;
        return os;
    }

    ...
};

If you want to use your getName() method instead, you would need to declare it as const (which you should do anyway for all of your getters), eg:

class BookInfo
{
public:
    ...
    string getName() const;
    ...

    friend ostream& operator<<(ostream &os, const BookInfo &book)
    {
        os << book.getName();
        return os;
    }

    ...
};

string BookInfo::getName() const
{
    return ...;
}


答:
Because std::vector<T,Allocator>::insert causes iterator invalidation.

Causes reallocation if the new size() is greater than the old capacity(). If the new size() is greater than capacity(), all iterators and references are invalidated. Otherwise, only the iterators and references before the insertion point remain valid. The past-the-end iterator is also invalidated.

That means after insert's invocation, it has been invalidated. Usage of it like *it or it++ leads to UB.

You should assign it to the return value of insert, which is the iterator pointing to the inserted value. e.g.

```<code>vector<int>::iterator it;
it=veclist.begin();
it=veclist.insert(it,20);
cout << *it << endl;  // prints 20
it++;
it=veclist.insert(it,99);
cout << *it <<endl;   // prints 99
</code>```

Title: C++ Vectors insertion and iterators confusion

Body:
Because std::vector<T,Allocator>::insert causes iterator invalidation.

Causes reallocation if the new size() is greater than the old capacity(). If the new size() is greater than capacity(), all iterators and references are invalidated. Otherwise, only the iterators and references before the insertion point remain valid. The past-the-end iterator is also invalidated.

That means after insert's invocation, it has been invalidated. Usage of it like *it or it++ leads to UB.

You should assign it to the return value of insert, which is the iterator pointing to the inserted value. e.g.

vector<int>::iterator it;
it=veclist.begin();
it=veclist.insert(it,20);
cout << *it << endl;  // prints 20
it++;
it=veclist.insert(it,99);
cout << *it <<endl;   // prints 99


问:
I am getting an error while executing this stored function in Oracle
My stored function requires an input and should return the number of members that have won atleast two awards ...

Here is my Code;

```<code>CREATE OR REPLACE FUNCTION calculateaward
(
  i_PLAYERID VARCHAR2
) RETURN VARCHAR2 AS
cnt NUMBER;
BEGIN

SELECT * INTO cnt FROM
(
  SELECT COUNT(*) AS NOM FROM
  (
    SELECT PLAYERID, USERNAME FROM MEMBER R
    WHERE R.USERNAME IN
    (
      SELECT USERNAME FROM
      (
        SELECT USERNAME, COUNT(*) AS cnt FROM MEMBERAWARD
        GROUP BY USERNAME
      )
      WHERE cnt >= 2
    )
  )
  WHERE player= I_PLAYERID
  GROUP BY PLAYERID
);

  RETURN cnt;
END calculateaward;
</code>```

I am trying to execute the function as follow
exec calculateaward('P0001') but it does not work , please help .

答:
Functions return things: that's what distinguishes them from procedures.  So when we execute them we need to provide a receptacle for the returned value:

In SQL*Plus that would be

```<code>SQL>   var whatever varchar2(30)
SQL>   exec :whatever := calculateaward('P0001')
</code>```

By the way, as your function executes a query whose resulot is a COUNT, the returned value ought to have a datatype of NUMBER rather than VARCHAR2.

Body:
My stored function requires an input and should return the number of members that have won atleast two awards ...

Here is my Code;

CREATE OR REPLACE FUNCTION calculateaward
(
  i_PLAYERID VARCHAR2
) RETURN VARCHAR2 AS
cnt NUMBER;
BEGIN

SELECT * INTO cnt FROM
(
  SELECT COUNT(*) AS NOM FROM
  (
    SELECT PLAYERID, USERNAME FROM MEMBER R
    WHERE R.USERNAME IN
    (
      SELECT USERNAME FROM
      (
        SELECT USERNAME, COUNT(*) AS cnt FROM MEMBERAWARD
        GROUP BY USERNAME
      )
      WHERE cnt >= 2
    )
  )
  WHERE player= I_PLAYERID
  GROUP BY PLAYERID
);

  RETURN cnt;
END calculateaward;

I am trying to execute the function as follow
exec calculateaward('P0001') but it does not work , please help .

Body:
Functions return things: that's what distinguishes them from procedures.  So when we execute them we need to provide a receptacle for the returned value:

In SQL*Plus that would be

SQL>   var whatever varchar2(30)
SQL>   exec :whatever := calculateaward('P0001')

By the way, as your function executes a query whose resulot is a COUNT, the returned value ought to have a datatype of NUMBER rather than VARCHAR2.


问:
SQL query to get sum of headcount according to column grouping
The below query is used to find out the headcount of employees in a particular department. This is working fine-

```<code> SELECT distinct --LVL2_ORG,
            division,
           district,
           department,
           Count(DISTINCT person_number)
             over (
               PARTITION BY department) AS dep_empl_count
    FROM   flattened_tree,
           hr_org_unit_classifications_f houcf,
           hr_all_organization_units_f haouf,
           hr_organization_units_f_tl hauft,
           per_all_assignments_m paam,
           per_all_people_f papf
    WHERE  haouf.organization_id = flattened_tree.department_id
           AND haouf.organization_id = houcf.organization_id
           AND haouf.organization_id = hauft.organization_id
           AND haouf.effective_start_date BETWEEN
               houcf.effective_start_date AND houcf.effective_end_date
           AND hauft.LANGUAGE = 'US'
           AND hauft.effective_start_date = haouf.effective_start_date
           AND hauft.effective_end_date = haouf.effective_end_date
           AND houcf.classification_code = 'DEPARTMENT'
           AND Trunc(SYSDATE) BETWEEN hauft.effective_start_date AND
                                      hauft.effective_end_date
           AND hauft.organization_id = paam.organization_id
           AND paam.person_id = papf.person_id
           AND paam.primary_assignment_flag = 'Y'
           AND paam.assignment_type = 'E'
           AND paam.assignment_status_type IN ( 'ACTIVE', 'SUSPENDED' )
           AND paam.effective_latest_change = 'Y'
           AND trunc(sysdate) between paam.effective_start_date and paam.effective_end_date
AND trunc(sysdate) between papf.effective_start_date and papf.effective_end_date

ORDER  BY division,district,department
</code>```

The output looks like -

```<code>DIVISION            DISTRICT        DEPARTMENT              JAN
CA Division         Grande          XYZ                     0
CA Division         Deer            Deer Tubing             1
CA Division         Deer            XYZ  Fracturing         0
CA Division         Fracturing      CAA  Fracturing         3

US Division         Neuquen         Support                 101
US Division         Neuquen         Cementing               3
US Division         Corporate       Fracturing              190
</code>```

Now I want to calculate the sum in the same query at the division and district level. i.e. sum of headcounts(JAN Column) per district and per division in the same query. Is this possible ?

The output should look like -

```<code>DIVISION            DISTRICT        DEPARTMENT              JAN    SUM(DIVISION)    SUM(DISTRICT)
CA Division         Grande          XYZ                     0        4               0
CA Division         Deer            Deer Tubing             1        4               1
CA Division         Deer            XYZ  Fracturing         0        4               1
CA Division         Fracturing      CAA  Fracturing         3        4               3

US Division         Neuquen         Support                 101      294            104
US Division         Neuquen         Cementing               3        294            104
US Division         Corporate       Fracturing              190      294            190
</code>```

so from above output- sum of division should be sum of all headcounts in one division (CA Division and US Division)
and sum of district should be for Deer district - 1+0=1    for Neuquen district 101+3=104 like that.

答:
Instead of 1 measure:

```<code>   Count(DISTINCT person_number)
     over (
       PARTITION BY department) AS dep_empl_count
</code>```

Use 3 measures:

```<code>   Count(DISTINCT person_number) over (PARTITION BY department) AS dep_empl_count,
   Count(DISTINCT person_number) over (PARTITION BY division) AS div_empl_count,
   Count(DISTINCT person_number) over (PARTITION BY district) AS dis_empl_count
</code>```

Body:
The below query is used to find out the headcount of employees in a particular department. This is working fine-

 SELECT distinct --LVL2_ORG,
            division,
           district,
           department,
           Count(DISTINCT person_number)
             over (
               PARTITION BY department) AS dep_empl_count
    FROM   flattened_tree,
           hr_org_unit_classifications_f houcf,
           hr_all_organization_units_f haouf,
           hr_organization_units_f_tl hauft,
           per_all_assignments_m paam,
           per_all_people_f papf
    WHERE  haouf.organization_id = flattened_tree.department_id
           AND haouf.organization_id = houcf.organization_id
           AND haouf.organization_id = hauft.organization_id
           AND haouf.effective_start_date BETWEEN
               houcf.effective_start_date AND houcf.effective_end_date
           AND hauft.LANGUAGE = 'US'
           AND hauft.effective_start_date = haouf.effective_start_date
           AND hauft.effective_end_date = haouf.effective_end_date
           AND houcf.classification_code = 'DEPARTMENT'
           AND Trunc(SYSDATE) BETWEEN hauft.effective_start_date AND
                                      hauft.effective_end_date
           AND hauft.organization_id = paam.organization_id
           AND paam.person_id = papf.person_id
           AND paam.primary_assignment_flag = 'Y'
           AND paam.assignment_type = 'E'
           AND paam.assignment_status_type IN ( 'ACTIVE', 'SUSPENDED' )
           AND paam.effective_latest_change = 'Y'
           AND trunc(sysdate) between paam.effective_start_date and paam.effective_end_date
AND trunc(sysdate) between papf.effective_start_date and papf.effective_end_date

ORDER  BY division,district,department

The output looks like -

DIVISION            DISTRICT        DEPARTMENT              JAN
CA Division         Grande          XYZ                     0
CA Division         Deer            Deer Tubing             1
CA Division         Deer            XYZ  Fracturing         0
CA Division         Fracturing      CAA  Fracturing         3

US Division         Neuquen         Support                 101
US Division         Neuquen         Cementing               3
US Division         Corporate       Fracturing              190

Now I want to calculate the sum in the same query at the division and district level. i.e. sum of headcounts(JAN Column) per district and per division in the same query. Is this possible ?

The output should look like -

DIVISION            DISTRICT        DEPARTMENT              JAN    SUM(DIVISION)    SUM(DISTRICT)
CA Division         Grande          XYZ                     0        4               0
CA Division         Deer            Deer Tubing             1        4               1
CA Division         Deer            XYZ  Fracturing         0        4               1
CA Division         Fracturing      CAA  Fracturing         3        4               3

US Division         Neuquen         Support                 101      294            104
US Division         Neuquen         Cementing               3        294            104
US Division         Corporate       Fracturing              190      294            190

so from above output- sum of division should be sum of all headcounts in one division (CA Division and US Division)
and sum of district should be for Deer district - 1+0=1    for Neuquen district 101+3=104 like that.

Body:
Instead of 1 measure:

   Count(DISTINCT person_number)
     over (
       PARTITION BY department) AS dep_empl_count

Use 3 measures:

   Count(DISTINCT person_number) over (PARTITION BY department) AS dep_empl_count,
   Count(DISTINCT person_number) over (PARTITION BY division) AS div_empl_count,
   Count(DISTINCT person_number) over (PARTITION BY district) AS dis_empl_count


Title: How to load csv data containing dates into a numpy array?

Body:
I tried different things for too long now.

How do I load csv data containing dates into a numpy array?
This is what doesn't work. It creates a single line with everything that is supposed to be a line now being in a single cell.

import io
import numpy as np
import datetime as dt

def date_parser(d_bytes):
    s = d_bytes.decode('utf-8')
    return np.datetime64(dt.datetime.strptime(s, "%Y-%m-%d %H:%M:%S"))

def read_csv():
    five_min_candles_str = """2020-06-01 17:05:00,9506.01,9523.31,9500.0,9514.52
2020-06-01 17:10:00,9513.44,9525.22,9500.32,9522.0
2020-06-01 17:15:00,9521.56,9525.59,9513.75,9523.53
2020-06-01 17:20:00,9523.21,9525.53,9518.78,9524.55
2020-06-01 17:25:00,9524.55,9538.4,9522.93,9528.73
2020-06-01 17:30:00,9528.73,9548.98,9527.95,9543.72
2020-06-01 17:35:00,9542.71,9547.34,9536.57,9543.66
2020-06-01 17:40:00,9543.67,9543.67,9530.0,9531.85
2020-06-01 17:45:00,9530.84,9535.01,9524.1,9526.75
2020-06-01 17:50:00,9526.47,9538.64,9521.87,9534.57
2020-06-01 17:55:00,9534.58,9548.9,9533.04,9546.98
2020-06-01 18:00:00,9548.18,9558.9,9536.99,9556.25
2020-06-01 18:05:00,9556.15,9579.8,9547.7,9574.09
2020-06-01 18:10:00,9575.0,9592.59,9571.3,9573.93
2020-06-01 18:15:00,9573.68,9610.0,9569.6,9597.78
2020-06-01 18:20:00,9597.78,9598.85,9578.0,9591.39
                """
    nparray = np.genfromtxt(io.StringIO(five_min_candles_str),
                            delimiter=',',
                            dtype=[('Timestamp','datetime64[us]'),
                                   ('Open','object'),
                                   ('High','object'),
                                   ('Low','object'),
                                   ('Close','object')],
                            converters={0: date_parser},
                            )
    print(nparray)

if __name__ == "__main__":
    read_csv()

A solution or hint would be much appreciated!

Edit:
It turned out that it was indeed working already but I expected an 2D array while it became an array of tuples after I've added the types or the converter. The reason for that are the different types in a row. See the other SO question

I marked the answer below as correct anyways as I like it more because it doesn't need any custom parsing of the date and I also like the splitlines() solution more compared to io.StringIO()

Body:
In [53]: five_min_candles_str = """2020-06-01 17:05:00,9506.01,9523.31,9500.0,95
    ...: 14.52
    ...: 2020-06-01 17:10:00,9513.44,9525.22,9500.32,9522.0
    ...: 2020-06-01 17:15:00,9521.56,9525.59,9513.75,9523.53
    ...: 2020-06-01 17:20:00,9523.21,9525.53,9518.78,9524.55
    ...: 2020-06-01 17:25:00,9524.55,9538.4,9522.93,9528.73
    ...: 2020-06-01 17:30:00,9528.73,9548.98,9527.95,9543.72
    ...: 2020-06-01 17:35:00,9542.71,9547.34,9536.57,9543.66
    ...: 2020-06-01 17:40:00,9543.67,9543.67,9530.0,9531.85
    ...: 2020-06-01 17:45:00,9530.84,9535.01,9524.1,9526.75
    ...: 2020-06-01 17:50:00,9526.47,9538.64,9521.87,9534.57
    ...: 2020-06-01 17:55:00,9534.58,9548.9,9533.04,9546.98
    ...: 2020-06-01 18:00:00,9548.18,9558.9,9536.99,9556.25
    ...: 2020-06-01 18:05:00,9556.15,9579.8,9547.7,9574.09
    ...: 2020-06-01 18:10:00,9575.0,9592.59,9571.3,9573.93
    ...: 2020-06-01 18:15:00,9573.68,9610.0,9569.6,9597.78
    ...: 2020-06-01 18:20:00,9597.78,9598.85,9578.0,9591.39
    ...: """

Let's see how numpy handles these date strings.  It's not as robust as pandas, but:

In [55]: np.array('2020-06-01 17:05:00', 'datetime64[s]')
Out[55]: array('2020-06-01T17:05:00', dtype='datetime64[s]')

but looks ok.  The space between date and time is ok ('T' also works).

So lets try a fully automatic dtype:

In [56]: data=np.genfromtxt(five_min_candles_str.splitlines(), delimiter=',', dt
    ...: ype=None, encoding=True)
In [57]: data
Out[57]:
array([('2020-06-01 17:05:00', 9506.01, 9523.31, 9500.  , 9514.52),
       ('2020-06-01 17:10:00', 9513.44, 9525.22, 9500.32, 9522.  ),
       ('2020-06-01 17:15:00', 9521.56, 9525.59, 9513.75, 9523.53),
        ...
       ('2020-06-01 18:20:00', 9597.78, 9598.85, 9578.  , 9591.39)],
      dtype=[('f0', '<U19'), ('f1', '<f8'), ('f2', '<f8'), ('f3', '<f8'), ('f4', '<f8')])

SO we need to specify the datetime dtype (editing that dtype):

In [58]: dt = [('f0', 'datetime64[s]'), ('f1', '<f8'), ('f2', '<f8'), ('f3', '<f8'), ('f4', '<f8')]

In [59]: data=np.genfromtxt(five_min_candles_str.splitlines(), delimiter=',', dtype=dt, encoding=True)
In [60]: data
Out[60]:
array([('2020-06-01T17:05:00', 9506.01, 9523.31, 9500.  , 9514.52),
       ('2020-06-01T17:10:00', 9513.44, 9525.22, 9500.32, 9522.  ),
       ('2020-06-01T17:15:00', 9521.56, 9525.59, 9513.75, 9523.53),
       ('2020-06-01T17:20:00', 9523.21, 9525.53, 9518.78, 9524.55),
      ...
       ('2020-06-01T18:20:00', 9597.78, 9598.85, 9578.  , 9591.39)],
      dtype=[('f0', '<M8[s]'), ('f1', '<f8'), ('f2', '<f8'), ('f3', '<f8'), ('f4', '<f8')])


问:
How do I configure my Angular library to depend on Angular Material?
I have installed Angular Material into my library and have created a shared resource module that imports and exports all of Materials components. Right now I have a folder that contains a module and a component. The module declaration/exports contains the component and the imports array imports the shared Material module.

For some reason the component will not create a story in storybook and will not pass any unit tests because it cannot find the MatRadioModule that was imported from the shared resource.

This is the error that I get:

Template parse errors:
    'mat-radio-button' is not a known element:
    1. If 'mat-radio-button' is an Angular component, then verify that it is part of this module.
    2. If 'mat-radio-button' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

Here is the Material Module:

import { NgModule } from '@angular/core';

// Angular Material Components
import {MatCheckboxModule} from '@angular/material/checkbox';
import {MatButtonModule} from '@angular/material/button';
import {MatInputModule} from '@angular/material/input';
import {MatAutocompleteModule} from '@angular/material/autocomplete';
import {MatDatepickerModule} from '@angular/material/datepicker';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatRadioModule} from '@angular/material/radio';
import {MatSelectModule} from '@angular/material/select';
import {MatSliderModule} from '@angular/material/slider';
import {MatSlideToggleModule} from '@angular/material/slide-toggle';
import {MatMenuModule} from '@angular/material/menu';
import {MatSidenavModule} from '@angular/material/sidenav';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatListModule} from '@angular/material/list';
import {MatGridListModule} from '@angular/material/grid-list';
import {MatCardModule} from '@angular/material/card';
import {MatStepperModule} from '@angular/material/stepper';
import {MatTabsModule} from '@angular/material/tabs';
import {MatExpansionModule} from '@angular/material/expansion';
import {MatButtonToggleModule} from '@angular/material/button-toggle';
import {MatChipsModule} from '@angular/material/chips';
import {MatIconModule} from '@angular/material/icon';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import {MatProgressBarModule} from '@angular/material/progress-bar';
import {MatDialogModule} from '@angular/material/dialog';
import {MatTooltipModule} from '@angular/material/tooltip';
import {MatSnackBarModule} from '@angular/material/snack-bar';
import {MatTableModule} from '@angular/material/table';
import {MatSortModule} from '@angular/material/sort';
import {MatPaginatorModule} from '@angular/material/paginator';

@NgModule({
  imports: [
    MatCheckboxModule,
    MatCheckboxModule,
    MatButtonModule,
    MatInputModule,
    MatAutocompleteModule,
    MatDatepickerModule,
    MatFormFieldModule,
    MatRadioModule,
    MatSelectModule,
    MatSliderModule,
    MatSlideToggleModule,
    MatMenuModule,
    MatSidenavModule,
    MatToolbarModule,
    MatListModule,
    MatGridListModule,
    MatCardModule,
    MatStepperModule,
    MatTabsModule,
    MatExpansionModule,
    MatButtonToggleModule,
    MatChipsModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatProgressBarModule,
    MatDialogModule,
    MatTooltipModule,
    MatSnackBarModule,
    MatTableModule,
    MatSortModule,
    MatPaginatorModule
  ],
  exports: [
    MatCheckboxModule,
    MatCheckboxModule,
    MatButtonModule,
    MatInputModule,
    MatAutocompleteModule,
    MatDatepickerModule,
    MatFormFieldModule,
    MatRadioModule,
    MatSelectModule,
    MatSliderModule,
    MatSlideToggleModule,
    MatMenuModule,
    MatSidenavModule,
    MatToolbarModule,
    MatListModule,
    MatGridListModule,
    MatCardModule,
    MatStepperModule,
    MatTabsModule,
    MatExpansionModule,
    MatButtonToggleModule,
    MatChipsModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatProgressBarModule,
    MatDialogModule,
    MatTooltipModule,
    MatSnackBarModule,
    MatTableModule,
    MatSortModule,
    MatPaginatorModule
  ]
})
export class MaterialModule { }```
</div>
</div>
</p>

<p>Here is the component module:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { NgModule } from '@angular/core';
import { ButtonComponent } from './button.component';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { MaterialModule } from '../material.module';

@NgModule({
  declarations: [ButtonComponent],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    MaterialModule
  ],
  exports: [ButtonComponent]
})
export class ButtonModule { }</code>```

Here is the component with html:

import {Component} from '@angular/core';

/**
 * @title Radios with ngModel
 */
@Component({
  selector: 'nds-button',
  templateUrl: 'button.component.html',
  styleUrls: ['button.component.css'],
})
export class ButtonComponent {

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><mat-radio-group aria-label="Select an option">
  <mat-radio-button value="1">Option 1</mat-radio-button>
  <mat-radio-button value="2">Option 2</mat-radio-button>
</mat-radio-group></code>```

Now I'm just wondering why mat-radio-button would not be a known element?

I should also add that the build works, but failure comes when using Storybook and running my Jest unit tests.

答:
this question already has an answer here.

Generally speaking, you need to add @angular/material as a peer dependency of your library and then call the library from your component. Hope this helps.

Body:
I have installed Angular Material into my library and have created a shared resource module that imports and exports all of Materials components. Right now I have a folder that contains a module and a component. The module declaration/exports contains the component and the imports array imports the shared Material module.

For some reason the component will not create a story in storybook and will not pass any unit tests because it cannot find the MatRadioModule that was imported from the shared resource.

This is the error that I get:

Template parse errors:
    'mat-radio-button' is not a known element:
    1. If 'mat-radio-button' is an Angular component, then verify that it is part of this module.
    2. If 'mat-radio-button' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

Here is the Material Module:

import { NgModule } from '@angular/core';

// Angular Material Components
import {MatCheckboxModule} from '@angular/material/checkbox';
import {MatButtonModule} from '@angular/material/button';
import {MatInputModule} from '@angular/material/input';
import {MatAutocompleteModule} from '@angular/material/autocomplete';
import {MatDatepickerModule} from '@angular/material/datepicker';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatRadioModule} from '@angular/material/radio';
import {MatSelectModule} from '@angular/material/select';
import {MatSliderModule} from '@angular/material/slider';
import {MatSlideToggleModule} from '@angular/material/slide-toggle';
import {MatMenuModule} from '@angular/material/menu';
import {MatSidenavModule} from '@angular/material/sidenav';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatListModule} from '@angular/material/list';
import {MatGridListModule} from '@angular/material/grid-list';
import {MatCardModule} from '@angular/material/card';
import {MatStepperModule} from '@angular/material/stepper';
import {MatTabsModule} from '@angular/material/tabs';
import {MatExpansionModule} from '@angular/material/expansion';
import {MatButtonToggleModule} from '@angular/material/button-toggle';
import {MatChipsModule} from '@angular/material/chips';
import {MatIconModule} from '@angular/material/icon';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import {MatProgressBarModule} from '@angular/material/progress-bar';
import {MatDialogModule} from '@angular/material/dialog';
import {MatTooltipModule} from '@angular/material/tooltip';
import {MatSnackBarModule} from '@angular/material/snack-bar';
import {MatTableModule} from '@angular/material/table';
import {MatSortModule} from '@angular/material/sort';
import {MatPaginatorModule} from '@angular/material/paginator';

@NgModule({
  imports: [
    MatCheckboxModule,
    MatCheckboxModule,
    MatButtonModule,
    MatInputModule,
    MatAutocompleteModule,
    MatDatepickerModule,
    MatFormFieldModule,
    MatRadioModule,
    MatSelectModule,
    MatSliderModule,
    MatSlideToggleModule,
    MatMenuModule,
    MatSidenavModule,
    MatToolbarModule,
    MatListModule,
    MatGridListModule,
    MatCardModule,
    MatStepperModule,
    MatTabsModule,
    MatExpansionModule,
    MatButtonToggleModule,
    MatChipsModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatProgressBarModule,
    MatDialogModule,
    MatTooltipModule,
    MatSnackBarModule,
    MatTableModule,
    MatSortModule,
    MatPaginatorModule
  ],
  exports: [
    MatCheckboxModule,
    MatCheckboxModule,
    MatButtonModule,
    MatInputModule,
    MatAutocompleteModule,
    MatDatepickerModule,
    MatFormFieldModule,
    MatRadioModule,
    MatSelectModule,
    MatSliderModule,
    MatSlideToggleModule,
    MatMenuModule,
    MatSidenavModule,
    MatToolbarModule,
    MatListModule,
    MatGridListModule,
    MatCardModule,
    MatStepperModule,
    MatTabsModule,
    MatExpansionModule,
    MatButtonToggleModule,
    MatChipsModule,
    MatIconModule,
    MatProgressSpinnerModule,
    MatProgressBarModule,
    MatDialogModule,
    MatTooltipModule,
    MatSnackBarModule,
    MatTableModule,
    MatSortModule,
    MatPaginatorModule
  ]
})
export class MaterialModule { }

Here is the component module:

import { NgModule } from '@angular/core';
import { ButtonComponent } from './button.component';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { MaterialModule } from '../material.module';

@NgModule({
  declarations: [ButtonComponent],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    MaterialModule
  ],
  exports: [ButtonComponent]
})
export class ButtonModule { }

Here is the component with html:

import {Component} from '@angular/core';

/**
 * @title Radios with ngModel
 */
@Component({
  selector: 'nds-button',
  templateUrl: 'button.component.html',
  styleUrls: ['button.component.css'],
})
export class ButtonComponent {

}

<mat-radio-group aria-label="Select an option">
  <mat-radio-button value="1">Option 1</mat-radio-button>
  <mat-radio-button value="2">Option 2</mat-radio-button>
</mat-radio-group>

Now I'm just wondering why mat-radio-button would not be a known element?

I should also add that the build works, but failure comes when using Storybook and running my Jest unit tests.


问:
Simple java lib for text templating?
I need to template some email texts. Nothing fancy, just replace something like @name@ with real value. No pictures, no fancy formatting etc.

What java lib could you recommend? The simplier the better.

答:
You can give Velocity or Freemarker a shot.  I've used both in email templating engines.  They provide simple syntax for basic use cases, but you can get pretty complex later on!

Of the two, I personally prefer Freemarker because they've done a really good job of providing all sorts of different builtins that make formatting numbers and text very simple.

Title: Simple java lib for text templating?


问:
Continue executing code without interrupting output of looping function
I have a while loop counting in centiseconds and printing the current_step var, always on the same line.

I want to run, for example,

```<code>x = True

while x is True:
    pass #printing timer to CLI here

print('this is more code running while the timer is still running')
input('Press enter to stop the timer')
x = False
#When x becomes False, I want the while loop to terminate
</code>```

I know this must involve subprocess or something of the likes, but I don't know what direction to point myself in for learning to solve this issue.

Here is the function for reference:

```<code>def timer(stawt, stahp, step, time_step):
    from time import sleep

    stawt = int(stawt)
    stahp = int(stahp)

    if stahp < 1:
        stahp = 1
    elif stahp > 1000:
        stahp = 1000

    stahp = stahp * 100 + 1
    titerator = iter(range(stawt, stahp, step))

    while True:
        try:
            current_step = str(next(titerator))
            if int(current_step) < 99:
                final_time = '0' + current_step[:0] + '.' + current_step[0:] + 's'
                print('\r' + final_time, end='')
            elif int(current_step) < 999:
                final_time = current_step[:1] + '.' + current_step[1:] + 's'
                print('\r' + final_time, end='')
            elif int(current_step) < 9999:
                final_time = current_step[:2] + '.' + current_step[2:] + 's'
                print('\r' + final_time, end='')
            else:
                final_time = current_step[:3] + '.' + current_step[3:] + 's'
                print('\r' + final_time, end='')

            sleep(time_step)
        except:
            print(); break

    seconds = int((int(current_step) / 100) % 60)
    minutes = int((int(current_step) / 100) // 60)

    if minutes < 1:
        return ''
    else:
        final_time_human = str(minutes) + 'm ' + str(round(seconds)) + 's'
        print(final_time_human + '\n')

def MAIN():
    count_to = float(input('Enter max number of seconds to count:\n'))

    print()
    timer(0, count_to, 1, 0.01)

MAIN()
</code>```

答:
Thanks to @dorukerenaktas, I have got this working. This is their answer adapted into my scriptlet:</p>

```<code>import threading
from os import system

timer_thread = None

def timer(stawt, stahp, step, time_step):
    from time import sleep
    global run_timer

    stawt = int(stawt)
    stahp = int(stahp)

    if stahp < 1:
        print('Sorry, I limit min count to 1 second!\n')
        stahp = 1
    elif stahp > 1000:
        print('Sorry, I limit max count to 1000 seconds!\n')
        stahp = 1000
    else:
        print()

    stahp = stahp * 100 + 1
    titerator = iter(range(stawt, stahp, step))

    def print_time():
        while run_timer is True:
            try:
                current_step = str(next(titerator))
                if int(current_step) < 99:
                    final_time = '0' + current_step[:0] + '.' + current_step[0:] + 's'
                    print('\r' + final_time, end='')
                elif int(current_step) < 999:
                    final_time = current_step[:1] + '.' + current_step[1:] + 's'
                    print('\r' + final_time, end='')
                elif int(current_step) < 9999:
                    final_time = current_step[:2] + '.' + current_step[2:] + 's'
                    print('\r' + final_time, end='')
                else:
                    final_time = current_step[:3] + '.' + current_step[3:] + 's'
                    print('\r' + final_time, end='')

                sleep(time_step)
            except:
                break

        seconds = int((int(current_step) / 100) % 60)
        minutes = int((int(current_step) / 100) // 60)

        if minutes < 1:
            return ''
        else:
            final_time_human = str(minutes) + 'm ' + str(round(seconds)) + 's'
            print('\n' + final_time_human)

    print_time()

def _init_timer():
    global run_timer; run_timer = True
    global timer_thread

    print('Enter max number of seconds to count: ', end='')
    count_to = float(input())

    timer_thread = threading.Thread(target=timer, args=(0, count_to, 1, 0.01))
    timer_thread.start()

    print('\rPress enter to stop the timer:')
    usr_input = input(); run_timer = False

system('clear')
_init_timer()

timer_thread.join()
print('\nGoodbye!')
</code>```

Body:
I have a while loop counting in centiseconds and printing the current_step var, always on the same line.

I want to run, for example,

x = True

while x is True:
    pass #printing timer to CLI here

print('this is more code running while the timer is still running')
input('Press enter to stop the timer')
x = False
#When x becomes False, I want the while loop to terminate

I know this must involve subprocess or something of the likes, but I don't know what direction to point myself in for learning to solve this issue.

Here is the function for reference:

def timer(stawt, stahp, step, time_step):
    from time import sleep

    stawt = int(stawt)
    stahp = int(stahp)

    if stahp < 1:
        stahp = 1
    elif stahp > 1000:
        stahp = 1000

    stahp = stahp * 100 + 1
    titerator = iter(range(stawt, stahp, step))

    while True:
        try:
            current_step = str(next(titerator))
            if int(current_step) < 99:
                final_time = '0' + current_step[:0] + '.' + current_step[0:] + 's'
                print('\r' + final_time, end='')
            elif int(current_step) < 999:
                final_time = current_step[:1] + '.' + current_step[1:] + 's'
                print('\r' + final_time, end='')
            elif int(current_step) < 9999:
                final_time = current_step[:2] + '.' + current_step[2:] + 's'
                print('\r' + final_time, end='')
            else:
                final_time = current_step[:3] + '.' + current_step[3:] + 's'
                print('\r' + final_time, end='')

            sleep(time_step)
        except:
            print(); break

    seconds = int((int(current_step) / 100) % 60)
    minutes = int((int(current_step) / 100) // 60)

    if minutes < 1:
        return ''
    else:
        final_time_human = str(minutes) + 'm ' + str(round(seconds)) + 's'
        print(final_time_human + '\n')

def MAIN():
    count_to = float(input('Enter max number of seconds to count:\n'))

    print()
    timer(0, count_to, 1, 0.01)

MAIN()

Body:
Thanks to @dorukerenaktas, I have got this working. This is their answer adapted into my scriptlet:

import threading
from os import system

timer_thread = None

def timer(stawt, stahp, step, time_step):
    from time import sleep
    global run_timer

    stawt = int(stawt)
    stahp = int(stahp)

    if stahp < 1:
        print('Sorry, I limit min count to 1 second!\n')
        stahp = 1
    elif stahp > 1000:
        print('Sorry, I limit max count to 1000 seconds!\n')
        stahp = 1000
    else:
        print()

    stahp = stahp * 100 + 1
    titerator = iter(range(stawt, stahp, step))

    def print_time():
        while run_timer is True:
            try:
                current_step = str(next(titerator))
                if int(current_step) < 99:
                    final_time = '0' + current_step[:0] + '.' + current_step[0:] + 's'
                    print('\r' + final_time, end='')
                elif int(current_step) < 999:
                    final_time = current_step[:1] + '.' + current_step[1:] + 's'
                    print('\r' + final_time, end='')
                elif int(current_step) < 9999:
                    final_time = current_step[:2] + '.' + current_step[2:] + 's'
                    print('\r' + final_time, end='')
                else:
                    final_time = current_step[:3] + '.' + current_step[3:] + 's'
                    print('\r' + final_time, end='')

                sleep(time_step)
            except:
                break

        seconds = int((int(current_step) / 100) % 60)
        minutes = int((int(current_step) / 100) // 60)

        if minutes < 1:
            return ''
        else:
            final_time_human = str(minutes) + 'm ' + str(round(seconds)) + 's'
            print('\n' + final_time_human)

    print_time()

def _init_timer():
    global run_timer; run_timer = True
    global timer_thread

    print('Enter max number of seconds to count: ', end='')
    count_to = float(input())

    timer_thread = threading.Thread(target=timer, args=(0, count_to, 1, 0.01))
    timer_thread.start()

    print('\rPress enter to stop the timer:')
    usr_input = input(); run_timer = False

system('clear')
_init_timer()

timer_thread.join()
print('\nGoodbye!')


问:
spark - method Error: The argument types of an anonymous function must be fully known
I know there have been quite a few questions on this, but I've created a simple example that I thought should work,but still does not and I'm not sure I understand why

```<code>  def main(args: Array[String]) {
    val sparkConf = new SparkConf().setMaster("local[*]").setAppName("SparkStream")

    val streamingContext = new StreamingContext(sparkConf, Seconds(5))

    val kafkaDStream = KafkaUtils.createStream(streamingContext,"hubble1:2181","aaa",Map("video"->3))

    val wordDStream = kafkaDStream.flatMap(t=>t._2.split("  "))

    val mapDStream = wordDStream.map((_,1))

    val wordToSumDStream = mapDStream.updateStateByKey{
      case (seq,buffer) => {
        val sum = buffer.getOrElse(0) + seq.sum
        Option(sum)
      }
    }

    wordToSumDStream.print()

    streamingContext.start()

    streamingContext.awaitTermination()
  }
</code>```

```<code>Error:(41, 41) missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: (Seq[Int], Option[?]) => Option[?]
      val result = flat.updateStateByKey{
</code>```

Can someone explain why the mapDStream.updateStateByKey method statement does not compile?

答:
Put your logic inside function like below.

```<code>  def update(seq:Seq[Int],buffer: Option[Int]) = Some(buffer.getOrElse(0) + seq.sum)
  val wordToSumDStream = mapDStream.updateStateByKey(update)

</code>```

Check Example

Body:
I know there have been quite a few questions on this, but I've created a simple example that I thought should work,but still does not and I'm not sure I understand why

  def main(args: Array[String]) {
    val sparkConf = new SparkConf().setMaster("local[*]").setAppName("SparkStream")

    val streamingContext = new StreamingContext(sparkConf, Seconds(5))

    val kafkaDStream = KafkaUtils.createStream(streamingContext,"hubble1:2181","aaa",Map("video"->3))

    val wordDStream = kafkaDStream.flatMap(t=>t._2.split("  "))

    val mapDStream = wordDStream.map((_,1))

    val wordToSumDStream = mapDStream.updateStateByKey{
      case (seq,buffer) => {
        val sum = buffer.getOrElse(0) + seq.sum
        Option(sum)
      }
    }

    wordToSumDStream.print()

    streamingContext.start()

    streamingContext.awaitTermination()
  }

Error:(41, 41) missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: (Seq[Int], Option[?]) => Option[?]
      val result = flat.updateStateByKey{

Can someone explain why the mapDStream.updateStateByKey method statement does not compile?

Body:
Put your logic inside function like below.

  def update(seq:Seq[Int],buffer: Option[Int]) = Some(buffer.getOrElse(0) + seq.sum)
  val wordToSumDStream = mapDStream.updateStateByKey(update)

Check Example


问:
DLL Number and Load Performance
Suppose the overall dll size is 100M, here are the 2 cases:

100M * 1

10M  * 10

Will their be much performance impact when using many small sized DLLs? why?

We did a testing recently but didn't detect much performance difference between the 2 cases, I am not sure if there are some wrong steps with my testing or this is the fact.

答: I guess you'd only see a difference if you haven't got enough free memory. In both cases, the OS should take care of the DLLs, they should also be cached so if there is a difference, it should only matter for the first load.</p>

OwnerDisplayName: Baiyan Huang

ContentLicense: CC BY-SA 2.5

Title: DLL Number and Load Performance

OwnerDisplayName: schnaader


问:
if cardNumberArray[0] == 4: IndexError: list index out of range
Just started learning python and I'm trying to print different things based on the user's input, however, when I run the code I get this error:

```<code>    if cardNumberArray[0] == 4:
    IndexError: list index out of range
</code>```

I don't understand why when a number of 14-16 integers is inputted, the program says that cardNumberArray[0] is out of range, and why my program won't even print the different values given the below code.

```<code>cardNumber = input("what is the number?\n")
cardNumberArray = []

for i in cardNumberArray:
  cardNumberArray.append(int(i))
  print(f"Ith value: {cardNumberArray[i]}")

if cardNumberArray[0] == 4:
    print("VISA")
elif cardNumberArray[0] == 5:
  if cardNumberArray[1] == 1 or cardNumberArray[1] == 2 or cardNumberArray[1] == 3 or cardNumberArray[1] == 4 or cardNumberArray[1] == 4 or cardNumberArray[1] == 5:
    print("MASTERCARD")
elif cardNumberArray[0] == 3:
  if cardNumberArray[1] == 4 or cardNumberArray[1] == 7:
    print("AMEX")
else:
  print("INVALID")
</code>```

答:
Adding comments to the code to indicate the state of the array at various points:

```<code>cardNumber = input("what is the number?\n")
cardNumberArray = []  # array is empty

for i in cardNumberArray:  # array is still empty, so this loop does nothing
  cardNumberArray.append(int(i))  #  this never happens
  print(f"Ith value: {cardNumberArray[i]}")

# array is still empty since we never appended to it

if cardNumberArray[0] == 4:  # boom!
</code>```

Maybe you want the loop to be something more like for i in range(cardNumber)?

Or maybe it should be cardNumberArray = [int(input("what is the number?"))]?  It's hard to discern what the intent of this code is; all I know is that as written the array is definitely always empty.

Body:
Just started learning python and I'm trying to print different things based on the user's input, however, when I run the code I get this error:

    if cardNumberArray[0] == 4:
    IndexError: list index out of range

I don't understand why when a number of 14-16 integers is inputted, the program says that cardNumberArray[0] is out of range, and why my program won't even print the different values given the below code.

cardNumber = input("what is the number?\n")
cardNumberArray = []

for i in cardNumberArray:
  cardNumberArray.append(int(i))
  print(f"Ith value: {cardNumberArray[i]}")

if cardNumberArray[0] == 4:
    print("VISA")
elif cardNumberArray[0] == 5:
  if cardNumberArray[1] == 1 or cardNumberArray[1] == 2 or cardNumberArray[1] == 3 or cardNumberArray[1] == 4 or cardNumberArray[1] == 4 or cardNumberArray[1] == 5:
    print("MASTERCARD")
elif cardNumberArray[0] == 3:
  if cardNumberArray[1] == 4 or cardNumberArray[1] == 7:
    print("AMEX")
else:
  print("INVALID")

Body:
Adding comments to the code to indicate the state of the array at various points:

cardNumber = input("what is the number?\n")
cardNumberArray = []  # array is empty

for i in cardNumberArray:  # array is still empty, so this loop does nothing
  cardNumberArray.append(int(i))  #  this never happens
  print(f"Ith value: {cardNumberArray[i]}")

# array is still empty since we never appended to it

if cardNumberArray[0] == 4:  # boom!

Maybe you want the loop to be something more like for i in range(cardNumber)?

Or maybe it should be cardNumberArray = [int(input("what is the number?"))]?  It's hard to discern what the intent of this code is; all I know is that as written the array is definitely always empty.


问:
Is it possible to apply a directive to a component inside another component template?
I have a ComponentA:

```<code>@Component({
    selector: 'component-a',
    template: `<span>{{sampleText}}</span>`,
    styles: []
})
export class ComponentA implements OnInit {

    sampleText: string = 'ComponentA';

    constructor() {}

    ngOnInit() {
    }
}
</code>```

and a directive for ComponentA:

```<code>@Directive({
  selector: '[DirectiveForA]'
})
export class DirectiveForA implements OnInit {

    @Input('customText') customText: string;

    constructor(private componentA: ComponentA) {
    }

    ngOnInit() {
        this.componentA.sampleText = this.customText;
    }
}
</code>```

I could apply my directive for it:

```<code><component-a>
    <ng-template DirectiveForA customText="injectedText"></ng-template>
</component-a>
</code>```

But then, I have another ComponentB, which have an ComponentA inside:

```<code>@Component({
    selector: 'component-b',
    template: `<component-a></component-a>`,
    styles: []
})
export class ComponentB implements OnInit {

    @ViewChild(ComponentA, { static: false }) componentA: ComponentA;

    constructor() {}

    ngOnInit() {
    }
}
</code>```

I want to apply the directive to the ComponentA inside it, when using ComponentB like this:

```<code><component-b>
    <ng-template DirectiveForA customText="injectedText!"></ng-template>
</component-b>
</code>```

Angular is complaining:

```<code>ERROR NullInjectorError: StaticInjectorError(AppModule)[DirectiveForA -> ComponentA]:
    StaticInjectorError(Platform: core)[DirectiveForA -> ComponentA]:
    NullInjectorError: No provider for ComponentA!
</code>```

Question: Is there a way for me to make it works? If there isn't, what is the better practice for this?

(In my case, ComponentA is actually a grid, and DirectiveA is template for a certain grid column. ComponentB is actually the grid with an input form. ComponentB is used very frequently but I want to customize a column inside ComponentA.)

答:
I found a way using optional injection at last.</p>

```<code>@Directive({
  selector: '[DirectiveForA]'
})
export class DirectiveForA implements OnInit {

    @Input('customText') customText: string;
    private target: ComponentA;

    constructor(@Host() @Optional() public componentA: ComponentA, @Host() @Optional() public componentB: ComponentB) {
        if(componentA){
            this.target = componentA;
        }
        else if(componentB){
            this.target = componentB.componentA;
        }
    }

    ngOnInit() {
        if(this.target){
            this.target.sampleText = this.customText;
        }
    }
}
</code>```

Body:
I have a ComponentA:

@Component({
    selector: 'component-a',
    template: `<span>{{sampleText}}</span>`,
    styles: []
})
export class ComponentA implements OnInit {

    sampleText: string = 'ComponentA';

    constructor() {}

    ngOnInit() {
    }
}

and a directive for ComponentA:

@Directive({
  selector: '[DirectiveForA]'
})
export class DirectiveForA implements OnInit {

    @Input('customText') customText: string;

    constructor(private componentA: ComponentA) {
    }

    ngOnInit() {
        this.componentA.sampleText = this.customText;
    }
}

I could apply my directive for it:

<component-a>
    <ng-template DirectiveForA customText="injectedText"></ng-template>
</component-a>

But then, I have another ComponentB, which have an ComponentA inside:

@Component({
    selector: 'component-b',
    template: `<component-a></component-a>`,
    styles: []
})
export class ComponentB implements OnInit {

    @ViewChild(ComponentA, { static: false }) componentA: ComponentA;

    constructor() {}

    ngOnInit() {
    }
}

I want to apply the directive to the ComponentA inside it, when using ComponentB like this:

<component-b>
    <ng-template DirectiveForA customText="injectedText!"></ng-template>
</component-b>

Angular is complaining:

ERROR NullInjectorError: StaticInjectorError(AppModule)[DirectiveForA -> ComponentA]:
    StaticInjectorError(Platform: core)[DirectiveForA -> ComponentA]:
    NullInjectorError: No provider for ComponentA!

Question: Is there a way for me to make it works? If there isn't, what is the better practice for this?

(In my case, ComponentA is actually a grid, and DirectiveA is template for a certain grid column. ComponentB is actually the grid with an input form. ComponentB is used very frequently but I want to customize a column inside ComponentA.)

Body:
I found a way using optional injection at last.

@Directive({
  selector: '[DirectiveForA]'
})
export class DirectiveForA implements OnInit {

    @Input('customText') customText: string;
    private target: ComponentA;

    constructor(@Host() @Optional() public componentA: ComponentA, @Host() @Optional() public componentB: ComponentB) {
        if(componentA){
            this.target = componentA;
        }
        else if(componentB){
            this.target = componentB.componentA;
        }
    }

    ngOnInit() {
        if(this.target){
            this.target.sampleText = this.customText;
        }
    }
}


问:
ORA-00984 column not allowed here
I am getting error
"Execute-984 ORA-00984: column not allowed here"
while I am inserting values in my table Registred_Customer using Pro*C

Registred_Customer is defined as

```<code>CREATE TABLE Registred_Customer (
    Cust_id NUMBER(6) PRIMARY KEY,
    Name VARCHAR2(20) NOT NULL,
    Age NUMBER,
    Sex CHAR,
    Addr VARCHAR2(50),
    Contact NUMBER(10)
);
</code>```

Inserting values using a pro*c method

```<code>addCustomer(i, name,age, gender, address,contectNo);
</code>```

in Pro*C method I use following code to insert

```<code>EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES
(cust_id, cust_name, age, sex, addr,   contact);
</code>```

here cust_name and addr are char *; and sex is char rest as int;

It reports error while using variable but works fine using direct values
like EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES (10, 'Pankaj', 23, 'M', 'asdfs', 45875);

I tried changing few lines but in vain.

Thanks in advance.

答:
As Mr. mentioned, you are trying to use the columns as input values. When you provide actual values it works. Are you perhaps meaning to use PL/SQL variables or the procedure arguments? In this case, whatever your procedure parameters are called is what you should put in the values section.

i.e if addCustomer looks like

```<code>PROCEDURE addCustomer (pId NUMBER, pName VARCHAR2, pAge NUMBER, pGender CHAR, pAddress VARCHAR2, pContact NUMBER)
</code>```

Then you'd do something like

```<code>INSERT INTO registered_customer (cust_id, name, age, sex, addr, contact) VALUES (pId, pName, pAge, pGender, pAddress, pContact);
</code>```

But if you are inserting into all columns you can leave out the column definition and just provide values

Title: ORA-00984 column not allowed here

Body:
I am getting error
"Execute-984 ORA-00984: column not allowed here"
while I am inserting values in my table Registred_Customer using Pro*C

Registred_Customer is defined as

CREATE TABLE Registred_Customer (
    Cust_id NUMBER(6) PRIMARY KEY,
    Name VARCHAR2(20) NOT NULL,
    Age NUMBER,
    Sex CHAR,
    Addr VARCHAR2(50),
    Contact NUMBER(10)
);

Inserting values using a pro*c method

addCustomer(i, name,age, gender, address,contectNo);

in Pro*C method I use following code to insert

EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES
(cust_id, cust_name, age, sex, addr,   contact);

here cust_name and addr are char *; and sex is char rest as int;

It reports error while using variable but works fine using direct values
like EXEC SQL INSERT INTO REGISTRED_CUSTOMER VALUES (10, 'Pankaj', 23, 'M', 'asdfs', 45875);

I tried changing few lines but in vain.

Thanks in advance.

Body:
As Mr. mentioned, you are trying to use the columns as input values. When you provide actual values it works. Are you perhaps meaning to use PL/SQL variables or the procedure arguments? In this case, whatever your procedure parameters are called is what you should put in the values section.

i.e if addCustomer looks like

PROCEDURE addCustomer (pId NUMBER, pName VARCHAR2, pAge NUMBER, pGender CHAR, pAddress VARCHAR2, pContact NUMBER)

Then you'd do something like

INSERT INTO registered_customer (cust_id, name, age, sex, addr, contact) VALUES (pId, pName, pAge, pGender, pAddress, pContact);

But if you are inserting into all columns you can leave out the column definition and just provide values


问:
Where would be an appropriate location in Angular 2+ to keep Jasmine data fixtures?
I have several json responses (from backend) that I use in Jasmine specs, to test component and service functionality.

Recently I figured to move those responses into files in order to share data across multiple specs. However I can't find recommended location to store those files in. I saw an example, where spec fixtures are placed in assets folder, however I believe it is a wrong place, since Angular includes assets folder into a build.

Is there a recommended location for spec fixtures in Angular structure?

答:
this question is highly opinionated with respect to where to put the JSON files. However, inside your tsconfig.app.json, you can put in an exclude key that takes an array of directory locations to exclude when building and serving your application.

I would recommend to create a new folder inside your assets folder to store all your JSON responses, and then exclude that folder in your tsconfig.app.json

Example:

```<code>{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ],
  "exclude": [
    "src/test.ts",
    "src/**/*.spec.ts",
    "src/assets/test-data"
  ]
}

</code>```

Hope this helps

Body:
this question is highly opinionated with respect to where to put the JSON files. However, inside your tsconfig.app.json, you can put in an exclude key that takes an array of directory locations to exclude when building and serving your application.

I would recommend to create a new folder inside your assets folder to store all your JSON responses, and then exclude that folder in your tsconfig.app.json

Example:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": []
  },
  "files": [
    "src/main.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ],
  "exclude": [
    "src/test.ts",
    "src/**/*.spec.ts",
    "src/assets/test-data"
  ]
}

Hope this helps


问:
here, for a non prime number, the break statement in the inner loop is executed but the else statement of the outer loop is not executed, why?
```<code>L = []
nmax = 30

for n in range(2, nmax):
    for factor in L:
        if n % factor == 0:
            break
    else: # no break
        L.append(n)
print(L)
</code>```

Does the else in the outer loop work if the if statement is not execute din the inner loop...are they really connected inspite being in different loops

答:
The else isn't connected to the if statement but to the break statement.

The for/else syntax means that the else block will be executed if there is no break encountered inside the for loop.

Here is an example for ppl to understand it :

fruits = ["Orange", "Apple", "Banana", "Strawberry"]

def searchFruit(wanted):
    for fruit in fruits:
        if fruit == wanted:
            break
    else: # Can't find the wanted fruit
        return False
    # Found the wanted fruit
    return True

searchFruit("Tomato") # Output : False
```

Body:
L = []
nmax = 30

for n in range(2, nmax):
    for factor in L:
        if n % factor == 0:
            break
    else: # no break
        L.append(n)
print(L)

Does the else in the outer loop work if the if statement is not execute din the inner loop...are they really connected inspite being in different loops


问:
How to create dependencies between 2 build pipelines in Azure DevOps and link a work item to build pipeline?
The second build pipeline should be dependable on first build pipeline and the work item should relate to the build pipeline for keeping track.</p>

答:
How to create dependencies between 2 build pipelines in azure Devops and link a work item to build pipeline?

There is an option Build Completion under Triggers in your build definition:

Large products have several components that are dependent on each
  other. These components are often independently built. When an
  upstream component (a library, for example) changes, the downstream
  dependencies have to be rebuilt and revalidated. Teams typically
  manage these dependencies manually.

So, we could use this option to set up dependencies.

And there is another option Automatically link new work in this build under Options in your build definition, which could use to track the related workitems.

As test, I created a pipeline nullTest which depend on nullTest2:

And enable the option Automatically link new work in this build for those two pipelines, after the completion of the construction pipeline nullTest2, the nulltest pipeline is triggered:

Update:

Could you give me a step wise procedure how to associate the work
  item?

Associate the workitem to the pipeline, you just need add associate the workitems when you submit the changes:

Hope this helps.