问:
Azure App Registration: Quickstart not working in Python
What I want: Connecting a Python Web APP by using Flask with our Azrue AD. We are using Office 365 and Azure.

What I have tried: I have tried several times and tutorials from official MS side. But the Quickstart code which MS propose is not working for me. This is the tutorial I have used.
LINK1;IMG1;IMG2

What happens: Each time I can sign in. I get the Webpage with the Sign-in Button. After clicking I get the typical Login Wizzard from Office 365. Everything works. But after finishing that I come back to the Home-site (Log-in-Site). And I get no logfiles from FLASK????? Normaly everything have should work. I found out that is depends on the session.get params in python. But I have no idea how I can solve it.

Hopefully you can help me :)

app.py:

```<code>import uuid
import requests
from flask import Flask, render_template, session, request, redirect, url_for
from flask_session import Session  # https://pythonhosted.org/Flask-Session
import msal
import app_config

app = Flask(__name__)
app.config.from_object(app_config)
Session(app)

@app.route("/")
def index():
    if not session.get("user"):
        return redirect(url_for("login"))
    return render_template('index.html', user=session["user"], version=msal.__version__)

@app.route("/login")
def login():
    session["state"] = str(uuid.uuid4())
    # Technically we could use empty list [] as scopes to do just sign in,
    # here we choose to also collect end user consent upfront
    auth_url = _build_auth_url(scopes=app_config.SCOPE, state=session["state"])
    return render_template("login.html", auth_url=auth_url, version=msal.__version__)

@app.route(app_config.REDIRECT_PATH)  # Its absolute URL must match your app's redirect_uri set in AAD
def authorized():
    if request.args.get('state') != session.get("state"):
        return redirect(url_for("index"))  # No-OP. Goes back to Index page
    if "error" in request.args:  # Authentication/Authorization failure
        return render_template("auth_error.html", result=request.args)
    if request.args.get('code'):
        cache = _load_cache()
        result = _build_msal_app(cache=cache).acquire_token_by_authorization_code(
            request.args['code'],
            scopes=app_config.SCOPE,  # Misspelled scope would cause an HTTP 400 error here
            redirect_uri=url_for("authorized", _external=True))
        if "error" in result:
            return render_template("auth_error.html", result=result)
        session["user"] = result.get("id_token_claims")
        _save_cache(cache)
    return redirect(url_for("index"))

@app.route("/logout")
def logout():
    session.clear()  # Wipe out user and its token cache from session
    return redirect(  # Also logout from your tenant's web session
        app_config.AUTHORITY + "/oauth2/v2.0/logout" +
        "?post_logout_redirect_uri=" + url_for("index", _external=True))

@app.route("/graphcall")
def graphcall():
    token = _get_token_from_cache(app_config.SCOPE)
    if not token:
        return redirect(url_for("login"))
    graph_data = requests.get(  # Use token to call downstream service
        app_config.ENDPOINT,
        headers={'Authorization': 'Bearer ' + token['access_token']},
        ).json()
    return render_template('display.html', result=graph_data)

def _load_cache():
    cache = msal.SerializableTokenCache()
    if session.get("token_cache"):
        cache.deserialize(session["token_cache"])
    return cache

def _save_cache(cache):
    if cache.has_state_changed:
        session["token_cache"] = cache.serialize()

def _build_msal_app(cache=None, authority=None):
    return msal.ConfidentialClientApplication(
        app_config.CLIENT_ID, authority=authority or app_config.AUTHORITY,
        client_credential=app_config.CLIENT_SECRET, token_cache=cache)

def _build_auth_url(authority=None, scopes=None, state=None):
    return _build_msal_app(authority=authority).get_authorization_request_url(
        scopes or [],
        state=state or str(uuid.uuid4()),
        redirect_uri=url_for("authorized", _external=True))

def _get_token_from_cache(scope=None):
    cache = _load_cache()  # This web app maintains one cache per session
    cca = _build_msal_app(cache=cache)
    accounts = cca.get_accounts()
    if accounts:  # So all account(s) belong to the current signed-in user
        result = cca.acquire_token_silent(scope, account=accounts[0])
        _save_cache(cache)
        return result

app.jinja_env.globals.update(_build_auth_url=_build_auth_url)  # Used in template

if __name__ == "__main__":
    app.run()
</code>```

app_config.py:

```<code>import os

CLIENT_SECRET = "g3nK2F1DX4~_-0Mz-g.XXXXXXXXXXXX" # Our Quickstart uses this placeholder
# In your production app, we recommend you to use other ways to store your secret,
# such as KeyVault, or environment variable as described in Flask's documentation here
# https://flask.palletsprojects.com/en/1.1.x/config/#configuring-from-environment-variables
# CLIENT_SECRET = os.getenv("CLIENT_SECRET")
# if not CLIENT_SECRET:
#     raise ValueError("Need to define CLIENT_SECRET environment variable")

AUTHORITY = "https://login.microsoftonline.com/organizations"  # For multi-tenant app
# AUTHORITY = "https://login.microsoftonline.com/Enter_the_Tenant_Name_Here"

CLIENT_ID = "ff68d6d9-d7a7-4433-a094-XXXXXXXXX"

REDIRECT_PATH = "/getAToken"  # It will be used to form an absolute URL
    # And that absolute URL must match your app's redirect_uri set in AAD

# You can find more Microsoft Graph API endpoints from Graph Explorer
# https://developer.microsoft.com/en-us/graph/graph-explorer
ENDPOINT = 'https://graph.microsoft.com/v1.0/users'  # This resource requires no admin consent

# You can find the proper permission names from this document
# https://learn.microsoft.com/en-us/graph/permissions-reference
SCOPE = ["User.ReadBasic.All"]

SESSION_TYPE = "filesystem"  # So token cache will be stored in server-side session
</code>```

答:
I had also been struggling with this, and it turns out my issue came down to not installing the packages listed in the requirements.txt file correctly.

I had previously played around with flask_sessions and some of the authentication libraries, so had some elements already installed on the environment I was using.  Rather than installing from the requirements.txt provided in the repo, I installed the missing packages manually and encountered the same issue as you describe.

After searching thought the github issues I came across the thread below which indicates there is an issue with the flask-sessions package following a change to one of the dependencies

https://github.com/Azure-Samples/ms-identity-python-webapp/issues/16#issuecomment-618168231

After installing the requirements as per the repo (which installs a forked version of flask-session) the sample worked as expected.

Hope this helps.

Body:
What I want: Connecting a Python Web APP by using Flask with our Azrue AD. We are using Office 365 and Azure.

What I have tried: I have tried several times and tutorials from official MS side. But the Quickstart code which MS propose is not working for me. This is the tutorial I have used.
LINK1;IMG1;IMG2

What happens: Each time I can sign in. I get the Webpage with the Sign-in Button. After clicking I get the typical Login Wizzard from Office 365. Everything works. But after finishing that I come back to the Home-site (Log-in-Site). And I get no logfiles from FLASK????? Normaly everything have should work. I found out that is depends on the session.get params in python. But I have no idea how I can solve it.

Hopefully you can help me :)

app.py:

import uuid
import requests
from flask import Flask, render_template, session, request, redirect, url_for
from flask_session import Session  # https://pythonhosted.org/Flask-Session
import msal
import app_config

app = Flask(__name__)
app.config.from_object(app_config)
Session(app)

@app.route("/")
def index():
    if not session.get("user"):
        return redirect(url_for("login"))
    return render_template('index.html', user=session["user"], version=msal.__version__)

@app.route("/login")
def login():
    session["state"] = str(uuid.uuid4())
    # Technically we could use empty list [] as scopes to do just sign in,
    # here we choose to also collect end user consent upfront
    auth_url = _build_auth_url(scopes=app_config.SCOPE, state=session["state"])
    return render_template("login.html", auth_url=auth_url, version=msal.__version__)

@app.route(app_config.REDIRECT_PATH)  # Its absolute URL must match your app's redirect_uri set in AAD
def authorized():
    if request.args.get('state') != session.get("state"):
        return redirect(url_for("index"))  # No-OP. Goes back to Index page
    if "error" in request.args:  # Authentication/Authorization failure
        return render_template("auth_error.html", result=request.args)
    if request.args.get('code'):
        cache = _load_cache()
        result = _build_msal_app(cache=cache).acquire_token_by_authorization_code(
            request.args['code'],
            scopes=app_config.SCOPE,  # Misspelled scope would cause an HTTP 400 error here
            redirect_uri=url_for("authorized", _external=True))
        if "error" in result:
            return render_template("auth_error.html", result=result)
        session["user"] = result.get("id_token_claims")
        _save_cache(cache)
    return redirect(url_for("index"))

@app.route("/logout")
def logout():
    session.clear()  # Wipe out user and its token cache from session
    return redirect(  # Also logout from your tenant's web session
        app_config.AUTHORITY + "/oauth2/v2.0/logout" +
        "?post_logout_redirect_uri=" + url_for("index", _external=True))

@app.route("/graphcall")
def graphcall():
    token = _get_token_from_cache(app_config.SCOPE)
    if not token:
        return redirect(url_for("login"))
    graph_data = requests.get(  # Use token to call downstream service
        app_config.ENDPOINT,
        headers={'Authorization': 'Bearer ' + token['access_token']},
        ).json()
    return render_template('display.html', result=graph_data)

def _load_cache():
    cache = msal.SerializableTokenCache()
    if session.get("token_cache"):
        cache.deserialize(session["token_cache"])
    return cache

def _save_cache(cache):
    if cache.has_state_changed:
        session["token_cache"] = cache.serialize()

def _build_msal_app(cache=None, authority=None):
    return msal.ConfidentialClientApplication(
        app_config.CLIENT_ID, authority=authority or app_config.AUTHORITY,
        client_credential=app_config.CLIENT_SECRET, token_cache=cache)

def _build_auth_url(authority=None, scopes=None, state=None):
    return _build_msal_app(authority=authority).get_authorization_request_url(
        scopes or [],
        state=state or str(uuid.uuid4()),
        redirect_uri=url_for("authorized", _external=True))

def _get_token_from_cache(scope=None):
    cache = _load_cache()  # This web app maintains one cache per session
    cca = _build_msal_app(cache=cache)
    accounts = cca.get_accounts()
    if accounts:  # So all account(s) belong to the current signed-in user
        result = cca.acquire_token_silent(scope, account=accounts[0])
        _save_cache(cache)
        return result

app.jinja_env.globals.update(_build_auth_url=_build_auth_url)  # Used in template

if __name__ == "__main__":
    app.run()

app_config.py:

import os

CLIENT_SECRET = "g3nK2F1DX4~_-0Mz-g.XXXXXXXXXXXX" # Our Quickstart uses this placeholder
# In your production app, we recommend you to use other ways to store your secret,
# such as KeyVault, or environment variable as described in Flask's documentation here
# https://flask.palletsprojects.com/en/1.1.x/config/#configuring-from-environment-variables
# CLIENT_SECRET = os.getenv("CLIENT_SECRET")
# if not CLIENT_SECRET:
#     raise ValueError("Need to define CLIENT_SECRET environment variable")

AUTHORITY = "https://login.microsoftonline.com/organizations"  # For multi-tenant app
# AUTHORITY = "https://login.microsoftonline.com/Enter_the_Tenant_Name_Here"

CLIENT_ID = "ff68d6d9-d7a7-4433-a094-XXXXXXXXX"

REDIRECT_PATH = "/getAToken"  # It will be used to form an absolute URL
    # And that absolute URL must match your app's redirect_uri set in AAD

# You can find more Microsoft Graph API endpoints from Graph Explorer
# https://developer.microsoft.com/en-us/graph/graph-explorer
ENDPOINT = 'https://graph.microsoft.com/v1.0/users'  # This resource requires no admin consent

# You can find the proper permission names from this document
# https://learn.microsoft.com/en-us/graph/permissions-reference
SCOPE = ["User.ReadBasic.All"]

SESSION_TYPE = "filesystem"  # So token cache will be stored in server-side session


来源: stackexchange

问:
What's the difference between "number" and Number in javascript when iterating over an object?
here's an object.

```<code>let menu = {
  width: 200,
  height: 300,
  title: "My menu"
};
</code>```

that's the right code

```<code>function multiplyNumeric(obj) {
  for (let key in obj) {
    if (typeof obj[key] == 'number') {
      obj[key] *= 2;
    }
  }
}
</code>```

and here's my code

```<code>function multiplyNumeric(obj) {
      for (let key in obj) {
        if (typeof(obj[key]) === Number) {
          obj[key] *= 2;
        }
      }
    }
</code>```

Please tell me what makes the difference?

答:
As Jonas Høgh pointed out Nummer is a JavaScript function

A quick examlple of understanding the Number function:

console.log(Number(true));
console.log(Number(false));
console.log(Number(new Date()));
console.log(Number("999"));```

ContentLicense: CC BY-SA 4.0

Body:
here's an object.

let menu = {
  width: 200,
  height: 300,
  title: "My menu"
};

that's the right code

function multiplyNumeric(obj) {
  for (let key in obj) {
    if (typeof obj[key] == 'number') {
      obj[key] *= 2;
    }
  }
}

and here's my code

function multiplyNumeric(obj) {
      for (let key in obj) {
        if (typeof(obj[key]) === Number) {
          obj[key] *= 2;
        }
      }
    }

Please tell me what makes the difference?


问:
why does Logger.Output acquire mutex before checking Lshortfile/Llongfile flag
In Go's implementation of (l *Logger) Output, why acquire mutex before  if l.flag&(Lshortfile|Llongfile) != 0 {?

```<code>func (l *Logger) Output(calldepth int, s string) error {
    now := time.Now() // get this early.
    var file string
    var line int
    l.mu.Lock()
    defer l.mu.Unlock()
    if l.flag&(Lshortfile|Llongfile) != 0 {
        // Release lock while getting caller info - it's expensive.
        l.mu.Unlock()
        var ok bool
        _, file, line, ok = runtime.Caller(calldepth)
        if !ok {
            file = "???"
            line = 0
        }
        l.mu.Lock()
    }
    l.buf = l.buf[:0]
    l.formatHeader(&l.buf, now, file, line)
    l.buf = append(l.buf, s...)
    if len(s) == 0 || s[len(s)-1] != '\n' {
        l.buf = append(l.buf, '\n')
    }
    _, err := l.out.Write(l.buf)
    return err
}
</code>```

what about this?

```<code>func (l *Logger) Output(calldepth int, s string) error {
    now := time.Now() // get this early.
    var file string
    var line int
    if l.flag&(Lshortfile|Llongfile) != 0 {
        var ok bool
        _, file, line, ok = runtime.Caller(calldepth)
        if !ok {
            file = "???"
            line = 0
        }
    }
    // acquire mutex here, avoid aquire mutex twice.
    l.mu.Lock()
    defer l.mu.Unlock()
    l.buf = l.buf[:0]
    l.formatHeader(&l.buf, now, file, line)
    l.buf = append(l.buf, s...)
    if len(s) == 0 || s[len(s)-1] != '\n' {
        l.buf = append(l.buf, '\n')
    }
    _, err := l.out.Write(l.buf)
    return err
}
</code>```

答:
Logger.flag is the field protected by a mutex, not the constants.

log.Logger has a SetFlags method that can be called at any time from any goroutine. This method is implemented as:

```<code>// SetFlags sets the output flags for the logger.
// The flag bits are Ldate, Ltime, and so on.
func (l *Logger) SetFlags(flag int) {
    l.mu.Lock()
    defer l.mu.Unlock()
    l.flag = flag
}
</code>```

The documentation itself make it clear that a logger is safe for concurrent use:

A Logger can be used simultaneously from multiple goroutines; ...

To ensure this guarantee, any field of Logger that can be modified must be synchronized. If you access l.flag without proper synchronization, you are introducing a race condition.

Body:
In Go's implementation of (l *Logger) Output, why acquire mutex before  if l.flag&(Lshortfile|Llongfile) != 0 {?

func (l *Logger) Output(calldepth int, s string) error {
    now := time.Now() // get this early.
    var file string
    var line int
    l.mu.Lock()
    defer l.mu.Unlock()
    if l.flag&(Lshortfile|Llongfile) != 0 {
        // Release lock while getting caller info - it's expensive.
        l.mu.Unlock()
        var ok bool
        _, file, line, ok = runtime.Caller(calldepth)
        if !ok {
            file = "???"
            line = 0
        }
        l.mu.Lock()
    }
    l.buf = l.buf[:0]
    l.formatHeader(&l.buf, now, file, line)
    l.buf = append(l.buf, s...)
    if len(s) == 0 || s[len(s)-1] != '\n' {
        l.buf = append(l.buf, '\n')
    }
    _, err := l.out.Write(l.buf)
    return err
}

what about this?

func (l *Logger) Output(calldepth int, s string) error {
    now := time.Now() // get this early.
    var file string
    var line int
    if l.flag&(Lshortfile|Llongfile) != 0 {
        var ok bool
        _, file, line, ok = runtime.Caller(calldepth)
        if !ok {
            file = "???"
            line = 0
        }
    }
    // acquire mutex here, avoid aquire mutex twice.
    l.mu.Lock()
    defer l.mu.Unlock()
    l.buf = l.buf[:0]
    l.formatHeader(&l.buf, now, file, line)
    l.buf = append(l.buf, s...)
    if len(s) == 0 || s[len(s)-1] != '\n' {
        l.buf = append(l.buf, '\n')
    }
    _, err := l.out.Write(l.buf)
    return err
}

Body:
Logger.flag is the field protected by a mutex, not the constants.

log.Logger has a SetFlags method that can be called at any time from any goroutine. This method is implemented as:

// SetFlags sets the output flags for the logger.
// The flag bits are Ldate, Ltime, and so on.
func (l *Logger) SetFlags(flag int) {
    l.mu.Lock()
    defer l.mu.Unlock()
    l.flag = flag
}

The documentation itself make it clear that a logger is safe for concurrent use:

A Logger can be used simultaneously from multiple goroutines; ...

To ensure this guarantee, any field of Logger that can be modified must be synchronized. If you access l.flag without proper synchronization, you are introducing a race condition.


问:
I have issue with Chrome precisly next block of JS code, work well in Firefox, but in Chrome will show original (uploaded) image size
This is the javascript code. It works fine in Firefox but not in Chrome:

```<code>let big_image = document.getElementById('big_image');
let small_image = document.getElementById('small_image').getElementsByTagName('img');
for (var i = 0; i < small_image.length; i++){
    small_image[i].addEventListener('click', function(){
        let image_src = this.getAttribute('src');
        big_image.innerHTML = "<img src=" + image_src + " width='400px' height='400px'>";

    });
}
</code>```

Template:

```<code><div class="container mt-5">
    <div class="row">
        <div class="col-md-6" id="big_image">
            <img src="{{ url_for('static', filename='images/' + product.image_1) }}" alt="{{ product.name }}" width="400" height="400">
        </div>
        <div class="col-md-6">
            <h3>Product name: {{ product.name }}</h3>
            <hr>
            <p>Price: €{{ product.price }}</p>
            {% if product.discount > 0 %}
                <p>Discount: {{ product.discount }}%</p>
            {% endif %}
            <strong>Description:</strong>
            <p>{{ product.description }}</p>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12 mt-3" id="small_image">
            <img src="{{ url_for('static', filename='images/' + product.image_1) }}" alt="{{ product.name }}" width="120" height="120" class="p-3">
            <img src="{{ url_for('static', filename='images/' + product.image_2) }}" alt="{{ product.name }}" width="120" height="120" class="p-3">
            <img src="{{ url_for('static', filename='images/' + product.image_3) }}" alt="{{ product.name }}" width="120" height="120" class="p-3">

        </div>
    </div>
</div>
</code>```

Does anyone know what could be the problem in this case?

答:
The problem is with the src attribute of the image.

Instead of writing

```<code>big_image.innerHTML = "<img src=" + image_src + " width='400px' height='400px'>";
</code>```

you should write

```<code>big_image.innerHTML = "<img src='" + image_src + "' width='400px' height='400px'>";
</code>```

The variable image_src doesn't have the '' around it, so you have to add them manually

Body:
This is the javascript code. It works fine in Firefox but not in Chrome:

let big_image = document.getElementById('big_image');
let small_image = document.getElementById('small_image').getElementsByTagName('img');
for (var i = 0; i < small_image.length; i++){
    small_image[i].addEventListener('click', function(){
        let image_src = this.getAttribute('src');
        big_image.innerHTML = "";

    });
}

Template:

Product name: {{ product.name }}

Price: €{{ product.price }}

            {% if product.discount > 0 %}

Discount: {{ product.discount }}%

            {% endif %}
            Description:

{{ product.description }}

Does anyone know what could be the problem in this case?

Body:
The problem is with the src attribute of the image.

Instead of writing

big_image.innerHTML = "<img src=" + image_src + " width='400px' height='400px'>";

you should write

big_image.innerHTML = "<img src='" + image_src + "' width='400px' height='400px'>";

The variable image_src doesn't have the '' around it, so you have to add them manually


问:
Navigation Drawer menu items aren't clickable
Nothing is happening when I'm selecting any option from the navigation drawer. As soon as I click on the navigation drawer the drawer closes. I'll add my GitHub repository link also if you want to try correcting from there you are very much welcome:

https://github.com/tanmay380/andorid-studio-

This is my alphabetBaseShow class which shows the Navigation Drawer (I'll delete some of the lines so that it uses less space)

```<code>package com.example.myapplication.background;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.R;
import com.example.myapplication.infront.CharacterSelection;
import com.example.myapplication.infront.SplashScreen;
import com.software.shell.fab.ActionButton;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;

public class alphabetBaseShow extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    protected String mPracticeString;
    protected DrawingView mDrawView;
    public SeekBar seekBar;
    Button button;
    public boolean draw = true;
    AudioManager audio;
    protected TextView mScoreTimerView;
    protected TextView mBestScoreView;
    protected boolean mDone;
    public AlertDialog.Builder alertDialog;
    private static final int STORAGE_PERMISSION_CODE = 101;
    public TextView colorset;
    public NavigationView navigationView;
    //private TextToSpeech textToSpeech;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            System.gc();
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_alphabet_show);

            Toolbar toolbar = findViewById(R.id.PracticeToolbar);
            setSupportActionBar(toolbar);
            // textToSpeech=new TextToSpeech(this,LanguageSelection);
            drawerLayout = findViewById(R.id.drawerLayout);
            actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.close, R.string.open);
            drawerLayout.addDrawerListener(actionBarDrawerToggle);
            actionBarDrawerToggle.syncState();

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

            mDrawView = new DrawingView(this);
            seekBar = findViewById(R.id.size1);
            mDrawView = findViewById(R.id.DrawingView);
            mBestScoreView = (TextView) findViewById(R.id.best_score_View);
            mScoreTimerView = (TextView) findViewById(R.id.score_and_timer_View);
            mPracticeString = getIntent().getStringExtra(getResources().getString(R.string.practice_string));
            mDone = false;
            mScoreTimerView.bringToFront();

            mDrawView.canVibrate(true);
            mDrawView.setBitmapFromText(mPracticeString);

            audio = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);

        /*switch (audio.getStreamVolume(AudioManager.STREAM_MUSIC)) {
            case AudioManager.RINGER_MODE_SILENT:
                Toast.makeText(getApplicationContext(), "TURN UP THE VOLUME", Toast.LENGTH_SHORT).show();
        }*/
            if ((audio.getStreamVolume(AudioManager.STREAM_MUSIC) > 1)) {
                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
            }
            else if (audio.getStreamVolume(AudioManager.STREAM_MUSIC) == 0) {
                audio.setStreamVolume(AudioManager.STREAM_MUSIC, 10, 1);

                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
            }
        }
        catch (Exception e) {
            showErrorDialog(e);
        }

    }

    private void toggleSeekbar() {
        if (seekBar.getVisibility() == View.INVISIBLE) {
            seekBar.setVisibility(View.VISIBLE);
            seekBar.bringToFront();
            mDrawView.candraw(false);
        }
        else {
            seekBar.setVisibility(View.INVISIBLE);
            mDrawView.candraw(true);
        }

    }

    public void clickit() {
        toggleSeekbar();
        setSize();
    }

    public void setSize() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mDrawView.setCurrentWidth(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                toggleSeekbar();
            }
        });
        return;
    }

    public void practiceOnClick(View v) {
        switch (v.getId()) {

            case R.id.reset:
                if (mDone) {
                    mDrawView.init();
                }

                mDrawView.setBitmapFromText(mPracticeString);
                mBestScoreView.setAnimation(Animator.createFadeOutAnimation());
                mDrawView.startAnimation(Animator.createScaleUpAnimation());
                mScoreTimerView.setAnimation(Animator.createFadeOutAnimation());

                Animator.createYFlipForwardAnimation(findViewById(R.id.done));
                ((ActionButton) findViewById(R.id.done)).setImageResource(R.drawable.ic_done);
                Animator.createYFlipBackwardAnimation(findViewById(R.id.done));
                mDone = false; //implies that the user isn't done
                mDrawView.candraw(true);

                break;

            case R.id.done:
                String result = mDrawView.saveBitmap(mPracticeString, "");
                if (result.charAt(0) == '/')
                    result = "Trace Saved";

                Toast.makeText(this, result, Toast.LENGTH_SHORT).show(); // Toast displayed with the status of saving the trace
                if (!mDone) {
                    float best = SplashScreen.mDbHelper.getScore(mPracticeString);
                    if (best < mDrawView.score()) {
                        best = mDrawView.score();
                        SplashScreen.mDbHelper.writeScore(mPracticeString, best);
                    }

                    //Animations for when the user is done with the trace
                    mDrawView.startAnimation(Animator.createScaleDownAnimation());
                    findViewById(R.id.best_score_View).bringToFront();
                    ((TextView) findViewById(R.id.best_score_View)).setText("Best: " + String.valueOf(best));
                    mScoreTimerView.setText("Score: " + String.valueOf(mDrawView.score()));
                    mScoreTimerView.setAnimation(Animator.createFadeInAnimation());
                    mBestScoreView.setAnimation(Animator.createFadeInAnimation());

                    Animator.createYFlipForwardAnimation(findViewById(R.id.done));
                    ((ActionButton) findViewById(R.id.done)).setImageResource(R.drawable.ic_save);
                    Animator.createYFlipBackwardAnimation(findViewById(R.id.done));

                    mDrawView.candraw(false);
                    mDone = true;
                }
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        if (!mDone) {
            int next = Arrays.asList(SplashScreen.CHARACTER_LIST).indexOf(mPracticeString);
            switch (item.getItemId()) {

                case R.id.action_next:
                    next = (next + 1) % SplashScreen.CHARACTER_LIST.length;
                    break;

                case R.id.action_previous:

                    next = (next + SplashScreen.CHARACTER_LIST.length - 1) % SplashScreen.CHARACTER_LIST.length;
                    break;

                case R.id.setting:
                    clickit();
                    break;
            }

            if (item.getItemId() == R.id.action_next || item.getItemId() == R.id.action_previous) {
                mPracticeString = SplashScreen.CHARACTER_LIST[next];
                mDrawView.setBitmapFromText(mPracticeString);
                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
            }
        }
        return super.onOptionsItemSelected(item);
    }

    protected void showErrorDialog(final Exception e) {
        new AlertDialog.Builder(this)
                .setTitle("ERROR")
                .setMessage(Log.getStackTraceString(e))
                .setPositiveButton("Save to File", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + File.separator + getResources().getString(R.string.app_name));
                            File file = new File(mediaStorageDir.getPath() + File.separator + "error.txt");
                            if (file.exists() || file.createNewFile()) {
                                FileOutputStream fOut = new FileOutputStream(file, true);
                                fOut.write(("\n\n" + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date()) + "\n\n").getBytes());
                                fOut.write(Log.getStackTraceString(e).getBytes());
                                fOut.flush();
                                fOut.close();
                            }
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        int id = menuItem.getItemId();

        switch (id) {
            case R.id.green:
                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
                break;
            case R.id.red:
                Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
                break;
            case R.id.black:
                Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
                break;
            case R.id.blue:
                Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
    }
}
</code>```

This is my XML file (deleted some Textview lines as they were not important hence less space will be required):

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".background.alphabetBaseShow">

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:layout_marginTop="55dp"
        app:headerLayout="@layout/header"
        app:menu="@menu/colors"
        android:clickable="true">

    </android.support.design.widget.NavigationView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.Toolbar
            android:id="@+id/PracticeToolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/ActionbarBg"
            app:title="PRACTICE " />

        <com.example.myapplication.background.DrawingView
            android:id="@+id/DrawingView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="50dp" />

        <com.software.shell.fab.ActionButton
            android:id="@+id/done"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:layout_marginEnd="0dp"
            android:layout_marginRight="0dp"
            android:layout_marginBottom="0dp"
            android:onClick="practiceOnClick"
            app:button_color="@color/ButtonBg"
            app:image="@drawable/ic_done" />

        <com.software.shell.fab.ActionButton
            android:id="@+id/reset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentBottom="true"
            android:onClick="practiceOnClick"
            app:button_color="@color/ButtonBg"
            app:image="@drawable/ic_reset" />
    </RelativeLayout>
</android.support.v4.widget.DrawerLayout>
</code>```

This is my colors.xml (menu file). I've even tried to add onClick inside item, but it didn't work:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/green"
            android:icon="@drawable/ic_save"
            android:title="GREEN" />
        <item
            android:id="@+id/black"
            android:icon="@drawable/ic_save"
            android:title="BLACK" />
        <item
            android:id="@+id/blue"
            android:icon="@drawable/ic_save"
            android:title="BLUE" />
        <item
            android:id="@+id/red"
            android:icon="@drawable/ic_save"
            android:title="RED"
            android:onClick="toast"/>

    </group>
</menu>
</code>```

答:
Created a pull request to your repository. Check out.

P.S.:

You should have used the same version of support and design libraries

Do not use System.gs (!)

The main reason why your navigation item click listener did not work was - you did not assign your interface implementation,

```<code>navigationView.setNavigationItemSelectedListener(this);
</code>```

instead of

```<code>navigationView.setNavigationItemSelectedListener(new OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // Some stuff here
    }
});
</code>```

as you have implemented the interface NavigationView.OnNavigationItemSelectedListener.

Body:
Nothing is happening when I'm selecting any option from the navigation drawer. As soon as I click on the navigation drawer the drawer closes. I'll add my GitHub repository link also if you want to try correcting from there you are very much welcome:

https://github.com/tanmay380/andorid-studio-

This is my alphabetBaseShow class which shows the Navigation Drawer (I'll delete some of the lines so that it uses less space)

package com.example.myapplication.background;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.R;
import com.example.myapplication.infront.CharacterSelection;
import com.example.myapplication.infront.SplashScreen;
import com.software.shell.fab.ActionButton;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;

public class alphabetBaseShow extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    protected String mPracticeString;
    protected DrawingView mDrawView;
    public SeekBar seekBar;
    Button button;
    public boolean draw = true;
    AudioManager audio;
    protected TextView mScoreTimerView;
    protected TextView mBestScoreView;
    protected boolean mDone;
    public AlertDialog.Builder alertDialog;
    private static final int STORAGE_PERMISSION_CODE = 101;
    public TextView colorset;
    public NavigationView navigationView;
    //private TextToSpeech textToSpeech;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try {
            System.gc();
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_alphabet_show);

            Toolbar toolbar = findViewById(R.id.PracticeToolbar);
            setSupportActionBar(toolbar);
            // textToSpeech=new TextToSpeech(this,LanguageSelection);
            drawerLayout = findViewById(R.id.drawerLayout);
            actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.close, R.string.open);
            drawerLayout.addDrawerListener(actionBarDrawerToggle);
            actionBarDrawerToggle.syncState();

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

            mDrawView = new DrawingView(this);
            seekBar = findViewById(R.id.size1);
            mDrawView = findViewById(R.id.DrawingView);
            mBestScoreView = (TextView) findViewById(R.id.best_score_View);
            mScoreTimerView = (TextView) findViewById(R.id.score_and_timer_View);
            mPracticeString = getIntent().getStringExtra(getResources().getString(R.string.practice_string));
            mDone = false;
            mScoreTimerView.bringToFront();

            mDrawView.canVibrate(true);
            mDrawView.setBitmapFromText(mPracticeString);

            audio = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);

        /*switch (audio.getStreamVolume(AudioManager.STREAM_MUSIC)) {
            case AudioManager.RINGER_MODE_SILENT:
                Toast.makeText(getApplicationContext(), "TURN UP THE VOLUME", Toast.LENGTH_SHORT).show();
        }*/
            if ((audio.getStreamVolume(AudioManager.STREAM_MUSIC) > 1)) {
                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
            }
            else if (audio.getStreamVolume(AudioManager.STREAM_MUSIC) == 0) {
                audio.setStreamVolume(AudioManager.STREAM_MUSIC, 10, 1);

                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
            }
        }
        catch (Exception e) {
            showErrorDialog(e);
        }

    }

    private void toggleSeekbar() {
        if (seekBar.getVisibility() == View.INVISIBLE) {
            seekBar.setVisibility(View.VISIBLE);
            seekBar.bringToFront();
            mDrawView.candraw(false);
        }
        else {
            seekBar.setVisibility(View.INVISIBLE);
            mDrawView.candraw(true);
        }

    }

    public void clickit() {
        toggleSeekbar();
        setSize();
    }

    public void setSize() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mDrawView.setCurrentWidth(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                toggleSeekbar();
            }
        });
        return;
    }

    public void practiceOnClick(View v) {
        switch (v.getId()) {

            case R.id.reset:
                if (mDone) {
                    mDrawView.init();
                }

                mDrawView.setBitmapFromText(mPracticeString);
                mBestScoreView.setAnimation(Animator.createFadeOutAnimation());
                mDrawView.startAnimation(Animator.createScaleUpAnimation());
                mScoreTimerView.setAnimation(Animator.createFadeOutAnimation());

                Animator.createYFlipForwardAnimation(findViewById(R.id.done));
                ((ActionButton) findViewById(R.id.done)).setImageResource(R.drawable.ic_done);
                Animator.createYFlipBackwardAnimation(findViewById(R.id.done));
                mDone = false; //implies that the user isn't done
                mDrawView.candraw(true);

                break;

            case R.id.done:
                String result = mDrawView.saveBitmap(mPracticeString, "");
                if (result.charAt(0) == '/')
                    result = "Trace Saved";

                Toast.makeText(this, result, Toast.LENGTH_SHORT).show(); // Toast displayed with the status of saving the trace
                if (!mDone) {
                    float best = SplashScreen.mDbHelper.getScore(mPracticeString);
                    if (best < mDrawView.score()) {
                        best = mDrawView.score();
                        SplashScreen.mDbHelper.writeScore(mPracticeString, best);
                    }

                    //Animations for when the user is done with the trace
                    mDrawView.startAnimation(Animator.createScaleDownAnimation());
                    findViewById(R.id.best_score_View).bringToFront();
                    ((TextView) findViewById(R.id.best_score_View)).setText("Best: " + String.valueOf(best));
                    mScoreTimerView.setText("Score: " + String.valueOf(mDrawView.score()));
                    mScoreTimerView.setAnimation(Animator.createFadeInAnimation());
                    mBestScoreView.setAnimation(Animator.createFadeInAnimation());

                    Animator.createYFlipForwardAnimation(findViewById(R.id.done));
                    ((ActionButton) findViewById(R.id.done)).setImageResource(R.drawable.ic_save);
                    Animator.createYFlipBackwardAnimation(findViewById(R.id.done));

                    mDrawView.candraw(false);
                    mDone = true;
                }
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        if (!mDone) {
            int next = Arrays.asList(SplashScreen.CHARACTER_LIST).indexOf(mPracticeString);
            switch (item.getItemId()) {

                case R.id.action_next:
                    next = (next + 1) % SplashScreen.CHARACTER_LIST.length;
                    break;

                case R.id.action_previous:

                    next = (next + SplashScreen.CHARACTER_LIST.length - 1) % SplashScreen.CHARACTER_LIST.length;
                    break;

                case R.id.setting:
                    clickit();
                    break;
            }

            if (item.getItemId() == R.id.action_next || item.getItemId() == R.id.action_previous) {
                mPracticeString = SplashScreen.CHARACTER_LIST[next];
                mDrawView.setBitmapFromText(mPracticeString);
                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
            }
        }
        return super.onOptionsItemSelected(item);
    }

    protected void showErrorDialog(final Exception e) {
        new AlertDialog.Builder(this)
                .setTitle("ERROR")
                .setMessage(Log.getStackTraceString(e))
                .setPositiveButton("Save to File", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + File.separator + getResources().getString(R.string.app_name));
                            File file = new File(mediaStorageDir.getPath() + File.separator + "error.txt");
                            if (file.exists() || file.createNewFile()) {
                                FileOutputStream fOut = new FileOutputStream(file, true);
                                fOut.write(("\n\n" + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.getDefault()).format(new Date()) + "\n\n").getBytes());
                                fOut.write(Log.getStackTraceString(e).getBytes());
                                fOut.flush();
                                fOut.close();
                            }
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        int id = menuItem.getItemId();

        switch (id) {
            case R.id.green:
                SplashScreen.TTSobj.speak(mPracticeString, TextToSpeech.QUEUE_FLUSH, null, null);
                break;
            case R.id.red:
                Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
                break;
            case R.id.black:
                Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
                break;
            case R.id.blue:
                Toast.makeText(getApplicationContext(), "REd", Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
    }
}

This is my XML file (deleted some Textview lines as they were not important hence less space will be required):

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".background.alphabetBaseShow">

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:layout_marginTop="55dp"
        app:headerLayout="@layout/header"
        app:menu="@menu/colors"
        android:clickable="true">

    </android.support.design.widget.NavigationView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.Toolbar
            android:id="@+id/PracticeToolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/ActionbarBg"
            app:title="PRACTICE " />

        <com.example.myapplication.background.DrawingView
            android:id="@+id/DrawingView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="50dp" />

        <com.software.shell.fab.ActionButton
            android:id="@+id/done"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:layout_marginEnd="0dp"
            android:layout_marginRight="0dp"
            android:layout_marginBottom="0dp"
            android:onClick="practiceOnClick"
            app:button_color="@color/ButtonBg"
            app:image="@drawable/ic_done" />

        <com.software.shell.fab.ActionButton
            android:id="@+id/reset"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentBottom="true"
            android:onClick="practiceOnClick"
            app:button_color="@color/ButtonBg"
            app:image="@drawable/ic_reset" />
    </RelativeLayout>
</android.support.v4.widget.DrawerLayout>

This is my colors.xml (menu file). I've even tried to add onClick inside item, but it didn't work:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/green"
            android:icon="@drawable/ic_save"
            android:title="GREEN" />
        <item
            android:id="@+id/black"
            android:icon="@drawable/ic_save"
            android:title="BLACK" />
        <item
            android:id="@+id/blue"
            android:icon="@drawable/ic_save"
            android:title="BLUE" />
        <item
            android:id="@+id/red"
            android:icon="@drawable/ic_save"
            android:title="RED"
            android:onClick="toast"/>

    </group>
</menu>

Body:
Created a pull request to your repository. Check out.

P.S.:

You should have used the same version of support and design libraries

Do not use System.gs (!)

The main reason why your navigation item click listener did not work was - you did not assign your interface implementation,

navigationView.setNavigationItemSelectedListener(this);

instead of

navigationView.setNavigationItemSelectedListener(new OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // Some stuff here
    }
});

as you have implemented the interface NavigationView.OnNavigationItemSelectedListener.


问:
Local storage stores string once and will not change
I have this function where it shows the search listing in a card (recent searches). When I search something, it stores successfully in local storage but when I search another item the listing (recent search) doesn't update. Even after page refresh, the same first search stays in the card and won't update at all. Can anyone see whats happening and how to fix this? Thanks in advance!

Javascript:

```<code>function customDeal1() {

  var recentSearch = document.querySelector('#search').value;
  var HighScore = localStorage.getItem('highScore');

var matchArray = findDeals(HighScore, name).slice(0,1);
  const html = matchArray.map(place => {
    const regex = new RegExp(HighScore);
    const nameName = place.name.replace(regex, `<span class="hl">${HighScore}</span>`);
         var shop = place.url.replace(/(centra)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop1 = place.url.replace(/(tesco)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop2 = place.url.replace(/(aldi)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop3 = place.url.replace(/(lidl)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop4 = place.url.replace(/(supervalu)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
    return `

            <img src="${place.imgurl}" alt="Drink Image">
            <h5>${nameName}</h5>
            <p>${(place.price)} ${shop} ${shop1} ${shop2} ${shop3} ${shop4}</p>

    `;
  }).join('') || '<li> No Searches Found </li>';
  deal2.innerHTML = html;

if(!localStorage.getItem('highScore') || localStorage.getItem('highScore').length === 0){
  localStorage.setItem('highScore', recentSearch);
}

};
const deal2 = document.querySelector('.deal1');
setInterval(customDeal1,5000);
</code>```

答:
I think the problem is in this line

```<code>if(!localStorage.getItem('highScore') || localStorage.getItem('highScore').length === 0){
  localStorage.setItem('highScore', recentSearch);
}
</code>```

it works at first because local storage is empty but once you execute the code
recentSearch will be stored in local storage which means the line above will be skipped
to fix this you will have to delete recentSearch from local storage before the line above or just save the data without the if statement because local storage overwrite data

Body:
I have this function where it shows the search listing in a card (recent searches). When I search something, it stores successfully in local storage but when I search another item the listing (recent search) doesn't update. Even after page refresh, the same first search stays in the card and won't update at all. Can anyone see whats happening and how to fix this? Thanks in advance!

Javascript:

function customDeal1() {

  var recentSearch = document.querySelector('#search').value;
  var HighScore = localStorage.getItem('highScore');

var matchArray = findDeals(HighScore, name).slice(0,1);
  const html = matchArray.map(place => {
    const regex = new RegExp(HighScore);
    const nameName = place.name.replace(regex, `<span class="hl">${HighScore}</span>`);
         var shop = place.url.replace(/(centra)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop1 = place.url.replace(/(tesco)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop2 = place.url.replace(/(aldi)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop3 = place.url.replace(/(lidl)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop4 = place.url.replace(/(supervalu)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
    return `

${nameName}

${(place.price)} ${shop} ${shop1} ${shop2} ${shop3} ${shop4}

    `;
  }).join('') || '
 No Searches Found
';
  deal2.innerHTML = html;

if(!localStorage.getItem('highScore') || localStorage.getItem('highScore').length === 0){
  localStorage.setItem('highScore', recentSearch);
}

};
const deal2 = document.querySelector('.deal1');
setInterval(customDeal1,5000);

Body:
I think the problem is in this line

if(!localStorage.getItem('highScore') || localStorage.getItem('highScore').length === 0){
  localStorage.setItem('highScore', recentSearch);
}

it works at first because local storage is empty but once you execute the code
recentSearch will be stored in local storage which means the line above will be skipped
to fix this you will have to delete recentSearch from local storage before the line above or just save the data without the if statement because local storage overwrite data


问:
Cannot launch what 3 words intent
I am trying to open the what3words app using the documentation here

https://developer.what3words.com/tutorial/mobile-linking-to-the-what3words-app/

```<code>Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("w3w://show?threewords=daring.lion.race"));
startActivityForResult(intent, INTENT_CODE);
</code>```

but I keep getting this issue

```<code>android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=w3w://show?threewords=daring.lion.race}
</code>```

I am on my device and have google play and the what3words app installed on the device.

答:
Try opening the app like this:

```<code>Intent intent = packageManager.getLaunchIntentForPackage("{w3w package name}");
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("w3w://show?threewords=daring.lion.race"));
startActivity(intent);
</code>```

To get the package name look for it in adb:

```<code>adb shell pm list packages
</code>```

Title: Cannot launch what 3 words intent

Body:
I am trying to open the what3words app using the documentation here

https://developer.what3words.com/tutorial/mobile-linking-to-the-what3words-app/

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("w3w://show?threewords=daring.lion.race"));
startActivityForResult(intent, INTENT_CODE);

but I keep getting this issue

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=w3w://show?threewords=daring.lion.race}

I am on my device and have google play and the what3words app installed on the device.

Body:
Try opening the app like this:

Intent intent = packageManager.getLaunchIntentForPackage("{w3w package name}");
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("w3w://show?threewords=daring.lion.race"));
startActivity(intent);

To get the package name look for it in adb:

adb shell pm list packages


问:
Comparing sql with c# list in query?
I have a problem with comparing a value in my sql database with a list of object in my code.

The object does not exist in DB

Example of an object in the list:

```<code>{
    public long CompareId
    public bool HasAccess
}
</code>```

I'm using SQLBuilder in c#
And then I want to make a query that says something like this:

In made up code

```<code>SELECT * FROM EntityPermission
WHERE EntityPermission.HasAccess = listOfObjects.Where(obj => obj.CompareId == EntityPermission.CompareId).HasAccess
</code>```

In more made up code but with sql builder

```<code>query.WHERE("(EntityPermission.HasAccess = {0})", listOfObjects.Where(obj => obj.CompareId == EntityPermission.CompareId).HasAccess)
</code>```

I'm fully aware of that I'm mixing c# and sql here, but it was the best way I could explain what I want to accomplish.

In words

I want to find the EntityPermission where the HasAccess column is equal to the HasAccess property of the object where they have the same Id.

Really thankful for all help!

答:
What you're looking for is the SQL WHERE...IN () syntax.

If you're using a tool that produces SQL, what you want to do is something like this:

1) get the list of values you want to compare

2) Create a string like the following from them:

```<code>"('value1','value2','value3')"
</code>```

3) then produce a query that looks like this:

```<code>SELECT * FROM EntityPermission
WHERE EntityPermission.HasAccess
IN ('value1','value2','value3')
</code>```

for an ORM like Entity Framework, NHibernate, etc, you can do the following:

```<code>var results = db.EntityPermissions
                .Where(x => listOfObjects
                           .Where(obj => obj.CompareId == EntityPermission.CompareId)
                .Select(y => y.HasAccess)
                .Contains(x.HasAccess))
</code>```

Title: Comparing sql with c# list in query?

Body:
I have a problem with comparing a value in my sql database with a list of object in my code.

The object does not exist in DB

Example of an object in the list:

{
    public long CompareId
    public bool HasAccess
}

I'm using SQLBuilder in c#
And then I want to make a query that says something like this:

In made up code

SELECT * FROM EntityPermission
WHERE EntityPermission.HasAccess = listOfObjects.Where(obj => obj.CompareId == EntityPermission.CompareId).HasAccess

In more made up code but with sql builder

query.WHERE("(EntityPermission.HasAccess = {0})", listOfObjects.Where(obj => obj.CompareId == EntityPermission.CompareId).HasAccess)

I'm fully aware of that I'm mixing c# and sql here, but it was the best way I could explain what I want to accomplish.

In words

I want to find the EntityPermission where the HasAccess column is equal to the HasAccess property of the object where they have the same Id.

Really thankful for all help!

Body:
What you're looking for is the SQL WHERE...IN () syntax.

If you're using a tool that produces SQL, what you want to do is something like this:

1) get the list of values you want to compare

2) Create a string like the following from them:

"('value1','value2','value3')"

3) then produce a query that looks like this:

SELECT * FROM EntityPermission
WHERE EntityPermission.HasAccess
IN ('value1','value2','value3')

for an ORM like Entity Framework, NHibernate, etc, you can do the following:

var results = db.EntityPermissions
                .Where(x => listOfObjects
                           .Where(obj => obj.CompareId == EntityPermission.CompareId)
                .Select(y => y.HasAccess)
                .Contains(x.HasAccess))


问:
MDX query in SSAS calculated member
I tried the MDX Query in SQL correctly
But I will insert that query in the VisualStudio(SSAS) in the Calculated Members section, but the process time will be faulty

```<code>Select
[Measures].[Fact Student Status Count]on columns
From [Cube_REG_Amozesh DW]
Where ( [Dim Student Status].[Student Status Key].[Student Status Key]-[Dim Student Status].[Student Status Key].&[0])
</code>```

I get the following error:

Severity  Code    Description Project File    Line    Suppression State
  Error     MdxScript(Cube_REG_Amozesh DW) (2, 5) Parser: The syntax for
  'Select' is incorrect. (CREATE DYNAMIC SET CURRENTCUBE.[RegSt]  AS
  Select   [Measures].[Fact Student Status Count]on columns from
  [Cube_REG_Amozesh DW] where ( [Dim Student Status].[Student Status
  Key].[Student Status Key]-[Dim Student Status].[Student Status
  Key].&[0]), DISPLAY_FOLDER = 'شاخص'  ; ).         0

答:
its worked:

CREATE MEMBER CURRENTCUBE.[Measures].RegST
     AS [Measures].[Fact Student Status Count]-([Measures].[Fact Student Status Count],[Dim Student Status].[Student Status Key].&[0])

Title: MDX query in SSAS calculated member

Body:
I tried the MDX Query in SQL correctly
But I will insert that query in the VisualStudio(SSAS) in the Calculated Members section, but the process time will be faulty

Select
[Measures].[Fact Student Status Count]on columns
From [Cube_REG_Amozesh DW]
Where ( [Dim Student Status].[Student Status Key].[Student Status Key]-[Dim Student Status].[Student Status Key].&[0])

I get the following error:

Severity  Code    Description Project File    Line    Suppression State
  Error     MdxScript(Cube_REG_Amozesh DW) (2, 5) Parser: The syntax for
  'Select' is incorrect. (CREATE DYNAMIC SET CURRENTCUBE.[RegSt]  AS
  Select   [Measures].[Fact Student Status Count]on columns from
  [Cube_REG_Amozesh DW] where ( [Dim Student Status].[Student Status
  Key].[Student Status Key]-[Dim Student Status].[Student Status
  Key].&[0]), DISPLAY_FOLDER = 'شاخص'  ; ).         0


问:
For loop with bitshifts
Can anyone explain how does this foor loop works?

for (bitMask = 0x01; bitMask; bitMask <<= 1)

This is the first time that I have encountered such a syntax in a for loop and would love to know how the loop would end.

答:
I think the datatype of bitMask is important here. So considering it as int. Below would be happen.

bitMask would be initialized to value 1.

Every Iteration would shift the bit value of bitMask by 1 place.

eg. 1 = 00001(no of bit will be platform dependent. Considering 32
bit) left shifted by 1 will give 00010 which is equal to value 2

This will generate below sequence of value for bitMask.  1,2,4,16,... until the bit having value 1 overflows the 32 bit size.

Once over flowed the value becomes Undefined for int. and 0 if bitMask is considered Unsigned Int as all the bits are zero now. making the condition in for loop false & break.

Simpler readable version:

```<code>for (bitMask = 1; bitMask != 0; bitMask *= 2)
</code>```

Title: For loop with bitshifts

Body:
I think the datatype of bitMask is important here. So considering it as int. Below would be happen.

bitMask would be initialized to value 1.

Every Iteration would shift the bit value of bitMask by 1 place.

eg. 1 = 00001(no of bit will be platform dependent. Considering 32
bit) left shifted by 1 will give 00010 which is equal to value 2

This will generate below sequence of value for bitMask.  1,2,4,16,... until the bit having value 1 overflows the 32 bit size.

Once over flowed the value becomes Undefined for int. and 0 if bitMask is considered Unsigned Int as all the bits are zero now. making the condition in for loop false & break.

Simpler readable version:

for (bitMask = 1; bitMask != 0; bitMask *= 2)


问:
Check keys' expire times through the redis-cli
I have a question about Redis caching.
I wrote some code to cache some information and it works fine, but is there a way to check what's being stored inside of it through redis-cli? I just want to make sure that the value gets deleted after 10 minutes.

how I store stuff:

Cache::store('redis')->put('inventory_' . $this->user->steamid64, $items, 15);

答:
Since you are using laravel's Cache class instead of Redis - then you need to check for the prefix. By default it ships like this in config/cache.php

```<code>'prefix' => env('CACHE_PREFIX', 'laravel')
</code>```

If there is a prefix(and it is laravel) it is going to be like this (if there is no prefix then you may discard laravel: from the key names)

```<code>127.0.0.1:6379> get laravel:inventory_1
"somevalue"
127.0.0.1:6379> ttl laravel:inventory_1
(integer) 885
127.0.0.1:6379>
</code>```

For the "development" purpose you may also use monitor command to see which commands are executed in redis. It is going to print like this;

```<code>127.0.0.1:6379> monitor
OK
1591091085.487083 [0 127.0.0.1:51828] "set" "myinventory_1" "myvalue" "EX" "900"
1591091091.143395 [0 127.0.0.1:51828] "get" "myinventory_1"
1591091095.280724 [0 127.0.0.1:51828] "ttl" "myinventory_1"
</code>```

Side note: You don't need to call store method if your default cache driver is already redis.

Body:
Since you are using laravel's Cache class instead of Redis - then you need to check for the prefix. By default it ships like this in config/cache.php

'prefix' => env('CACHE_PREFIX', 'laravel')

If there is a prefix(and it is laravel) it is going to be like this (if there is no prefix then you may discard laravel: from the key names)

127.0.0.1:6379> get laravel:inventory_1
"somevalue"
127.0.0.1:6379> ttl laravel:inventory_1
(integer) 885
127.0.0.1:6379>

For the "development" purpose you may also use monitor command to see which commands are executed in redis. It is going to print like this;

127.0.0.1:6379> monitor
OK
1591091085.487083 [0 127.0.0.1:51828] "set" "myinventory_1" "myvalue" "EX" "900"
1591091091.143395 [0 127.0.0.1:51828] "get" "myinventory_1"
1591091095.280724 [0 127.0.0.1:51828] "ttl" "myinventory_1"

Side note: You don't need to call store method if your default cache driver is already redis.


问:
Difference between isEmpty() and isBlank() Method in java 11
Java 11 has added A new instance method  isBlank() to java.lang.String class.

What's the basic difference between the existing isEmpty and newly added isBlank() method?

答:
The difference is as below :-

isBlank() returns true for the string having only white space characters whereas isEmpty() will return false for such strings.

```<code>("\n\r  ").isBlank();  //returns true
("\n\r  ").isEmpty();  //returns false
</code>```

For detailed explanation with Code Example visit : isBlank() vs isEmpty() in String class Java

Body:
The difference is as below :-

isBlank() returns true for the string having only white space characters whereas isEmpty() will return false for such strings.

("\n\r  ").isBlank();  //returns true
("\n\r  ").isEmpty();  //returns false

For detailed explanation with Code Example visit : isBlank() vs isEmpty() in String class Java


问:
Why do I get this error when trying to use Multer for dynamic path?
```<code>app.post('/upload/image', multer({
  dest:  './public/users/',
  changeDest: function(dest, req, res) {
      var newDestination = dest ;
      var stat = null;
      try {
          stat = fs.statSync(newDestination);
      } catch (err) {
          fs.mkdirSync(newDestination);
      }
      if (stat && !stat.isDirectory()) {
          throw new Error("directory cant be created");
      }
      return newDestination
  }
  }), function(req, res) {
       res.send({"status":"success"})
  });
</code>```

I tried using this code so that I can dynamically set the path for multer to store the uploaded pictures from the client. But this code is giving me this error

```<code>    throw new Error(msg);
        ^

Error: Route.post() requires a callback function but got a [object Object]
    at Route.<computed> [as post] (/Volumes/MacExtnd/Programming/webshop/backend/node_modules/express/lib/router/route.js:202:15)
    at Function.app.<computed> [as post] (/Volumes/MacExtnd/Programming/webshop/backend/node_modules/express/lib/application.js:482:19)
    at Object.<anonymous> (/Volumes/MacExtnd/Programming/webshop/backend/server.js:733:5)
</code>```

Please can anyone tell me how to solve this error?

答:
multer(opts) return an object with properties like .single(), .none(). See docs here.

You are passing this object as an Express middleware function, which explains the error. You would want to chose the correct property and pass that instead.

Example from the docs:

```<code>var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})
</code>```

Body:
app.post('/upload/image', multer({
  dest:  './public/users/',
  changeDest: function(dest, req, res) {
      var newDestination = dest ;
      var stat = null;
      try {
          stat = fs.statSync(newDestination);
      } catch (err) {
          fs.mkdirSync(newDestination);
      }
      if (stat && !stat.isDirectory()) {
          throw new Error("directory cant be created");
      }
      return newDestination
  }
  }), function(req, res) {
       res.send({"status":"success"})
  });

I tried using this code so that I can dynamically set the path for multer to store the uploaded pictures from the client. But this code is giving me this error

    throw new Error(msg);
        ^

Error: Route.post() requires a callback function but got a [object Object]
    at Route.<computed> [as post] (/Volumes/MacExtnd/Programming/webshop/backend/node_modules/express/lib/router/route.js:202:15)
    at Function.app.<computed> [as post] (/Volumes/MacExtnd/Programming/webshop/backend/node_modules/express/lib/application.js:482:19)
    at Object.<anonymous> (/Volumes/MacExtnd/Programming/webshop/backend/server.js:733:5)

Please can anyone tell me how to solve this error?

Body:
multer(opts) return an object with properties like .single(), .none(). See docs here.

You are passing this object as an Express middleware function, which explains the error. You would want to chose the correct property and pass that instead.

Example from the docs:

var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})


问:
Extracting discrete timestamp values of a dataset from a continous timestamps
I have a dataset with data points every minute, lets say df_cont with Value having cumulatively increasing numbers

```<code>                Value
datetimeindex
09:00:00         34
09:01:00         45
09:02:00         48
09:03:00         50
.                .
.                .
.                .
18:58:00         55
18:59:00         65
19:00:00         68
</code>```

I have another dataset with just time values, let's say df_time

```<code>Time_1       Time_2
09:05:00     09:15:00
10:05:00     10:25:00
11:55:00     12:15:00
17:05:00     17:15:00
</code>```

Now, the difference has to be found out for "Value" in the timestamp of the difference in time between Time_1 and Time_2.

I can do this manually by using the DateTime functionality

```<code>df_cont["2020-5-14 09:05:00":"2020-5-14 09:15:00"].Value.max() - df["2020-5-14 09:05:00":"2020-5-14 09:15:00"].Value.min()
</code>```

However, was unable to this automatically for all the difference of timestamps by either looping or using some other functions of pandas. Any help would be greatly appreciated.

Body:
I have a dataset with data points every minute, lets say df_cont with Value having cumulatively increasing numbers

                Value
datetimeindex
09:00:00         34
09:01:00         45
09:02:00         48
09:03:00         50
.                .
.                .
.                .
18:58:00         55
18:59:00         65
19:00:00         68

I have another dataset with just time values, let's say df_time

Time_1       Time_2
09:05:00     09:15:00
10:05:00     10:25:00
11:55:00     12:15:00
17:05:00     17:15:00

Now, the difference has to be found out for "Value" in the timestamp of the difference in time between Time_1 and Time_2.

I can do this manually by using the DateTime functionality

df_cont["2020-5-14 09:05:00":"2020-5-14 09:15:00"].Value.max() - df["2020-5-14 09:05:00":"2020-5-14 09:15:00"].Value.min()

However, was unable to this automatically for all the difference of timestamps by either looping or using some other functions of pandas. Any help would be greatly appreciated.

Body:
You can groupby an interval index using cut:

df_cont = pd.DataFrame(index=pd.date_range('09:00', '19:00', freq='T'))
df_cont['Value'] = df_cont.index.hour*100 + df_cont.index.minute
df_time = pd.DataFrame({'Time_1': {0: pd.Timestamp('2020-06-02 09:05:00'), 1: pd.Timestamp('2020-06-02 10:05:00'), 2: pd.Timestamp('2020-06-02 11:55:00'), 3: pd.Timestamp('2020-06-02 17:05:00')}, 'Time_2': {0: pd.Timestamp('2020-06-02 09:15:00'), 1: pd.Timestamp('2020-06-02 10:25:00'), 2: pd.Timestamp('2020-06-02 12:15:00'), 3: pd.Timestamp('2020-06-02 17:15:00')}})

idx = pd.IntervalIndex.from_arrays(df_time.Time_1, df_time.Time_2, 'both')
groups = pd.cut(df_cont.index, idx)
df_cont.groupby(groups).Value.apply(lambda x: x.max() - x.min())

Result:

[2020-06-02 09:05:00, 2020-06-02 09:15:00]    10
[2020-06-02 10:05:00, 2020-06-02 10:25:00]    20
[2020-06-02 11:55:00, 2020-06-02 12:15:00]    60
[2020-06-02 17:05:00, 2020-06-02 17:15:00]    10


问:
Issue when renaming multiple column names in pandas by extracting a element in tuple as string
Now I am working with a dataframe, with the column as follows:

```<code>(Column A, Response) (Column B, Response) (Column C, Response) (Unknown, Item 1) (Unknown, Item 2) ...
  1001                1001                 1001                 1001             1001
  1002                1002                 1002                 1002             1002
  ...
</code>```

For the first 3 columns, i don't need the 'Response' in the tuple and what I want to do is to delete the second part of the tuple in column 1-3, return the first part as a string and rename the column. For the columns from column 4 onwards, it's another way round so that I do not want to apply the same rules from there.

I tried the following:

```<code>for i in range(0,3):
    print(df.column[i][0])
    df.rename({df.columns[i]: df.columns[i][0]}, inplace=True)
</code>```

for the print, I got the right result:

```<code>Column A
Column B
Column C
</code>```

However, when I printed out the columns in the df after the command, it showed the same as before.

```<code>MultiIndex([(         'Column A', ...),
            (         'Column B', ...),
            (         'Column C', ...)],
           )
</code>```

What was the problem here?
And at the same time if I want to convert the output to string, can I also do it in df.rename command or shd I do it somewhere afterwards?

Meanwhile, when I tried the following:

```<code> for i in range(0,3):
        print(df.column[i][0])
        df = df.rename({df.columns[i]: df.columns[i][0]}, inplace=True)
</code>```

It returns AttributeError: 'NoneType' object has no attribute 'columns'

Why would it be?
Thank you for your help!

Additional information:
The table before was in multilevel index, and what I did was to flatten the multilevel index table with the command

```<code>df.columns.to_flat_index()
</code>```

答:
You have a MultiIndex here, which cannot be processed as an Index of tuple values. You must use the MultiIndex method get_level_values to extract one level:

```<code>df.columns = df.columns.get_level_values(0)
</code>```

Specifically, rename is applied separately on the labels of each level which is not what you want here.

Body:
Now I am working with a dataframe, with the column as follows:

(Column A, Response) (Column B, Response) (Column C, Response) (Unknown, Item 1) (Unknown, Item 2) ...
  1001                1001                 1001                 1001             1001
  1002                1002                 1002                 1002             1002
  ...

For the first 3 columns, i don't need the 'Response' in the tuple and what I want to do is to delete the second part of the tuple in column 1-3, return the first part as a string and rename the column. For the columns from column 4 onwards, it's another way round so that I do not want to apply the same rules from there.

I tried the following:

for i in range(0,3):
    print(df.column[i][0])
    df.rename({df.columns[i]: df.columns[i][0]}, inplace=True)

for the print, I got the right result:

Column A
Column B
Column C

However, when I printed out the columns in the df after the command, it showed the same as before.

MultiIndex([(         'Column A', ...),
            (         'Column B', ...),
            (         'Column C', ...)],
           )

What was the problem here?
And at the same time if I want to convert the output to string, can I also do it in df.rename command or shd I do it somewhere afterwards?

Meanwhile, when I tried the following:

 for i in range(0,3):
        print(df.column[i][0])
        df = df.rename({df.columns[i]: df.columns[i][0]}, inplace=True)

It returns AttributeError: 'NoneType' object has no attribute 'columns'

Why would it be?
Thank you for your help!

Additional information:
The table before was in multilevel index, and what I did was to flatten the multilevel index table with the command

df.columns.to_flat_index()

Body:
You have a MultiIndex here, which cannot be processed as an Index of tuple values. You must use the MultiIndex method get_level_values to extract one level:

df.columns = df.columns.get_level_values(0)

Specifically, rename is applied separately on the labels of each level which is not what you want here.


问:
from C++ to C#
What are good c++ to C# articles/tutorial or books?
I am reading http://msdn.microsoft.com/en-us/magazine/cc301520.aspx and will read http://andymcm.com/csharpfaq.htm and http://www.ondotnet.com/pub/a/dotnet/2002/02/11/csharp_traps.html afterwards. Have any of you read any good books for ppl who have a strong understanding of programming && || C++ on the C# language (and libraries)?</p>

答:
I am currently reading Jon Skeet's C# in Depth. It is the best treatment I have seen for C# 2 and 3. If you are an advanced C++ programmer and you have some familiarity with C#, this is the book to take your C# competence to mastery. </p>

<p>Jon provides insights into the evolution of C# and insights into the various new language features. Not just the "hows" but also the "whys". Again, approach it after reading a beginning C# book. It doesn't cover the basic stuff which is covered many times by numerous other C# books. </p>

ContentLicense: CC BY-SA 2.5

Title: from C++ to C#

Body:
I am currently reading Jon Skeet's C# in Depth. It is the best treatment I have seen for C# 2 and 3. If you are an advanced C++ programmer and you have some familiarity with C#, this is the book to take your C# competence to mastery.

Jon provides insights into the evolution of C# and insights into the various new language features. Not just the "hows" but also the "whys". Again, approach it after reading a beginning C# book. It doesn't cover the basic stuff which is covered many times by numerous other C# books.

OwnerDisplayName: m-sharp


问:
docker error on windows : the input device is not a TTY. If you are using mintty, try prefixing the command with 'winpty'
After I run this

```<code>docker run --rm -v "/c/users/vipul rao/documents/github/wappalyzer:/opt/wappalyzer" -it wappalyzer/dev
</code>```

I am getting the following error

the input device is not a TTY.  If you are using mintty, try prefixing the command with 'winpty'

What should I use here? I am running Docker on Windows 8 in MINGW64.

答:
I had the same error when trying to run the docker-compose exec command.
In the help documentation docker-compose exec --help it shows how you can disable the pseudo-tty allocation by adding -T to your command options in the following way:

docker-compose exec -T

From the help documentation:

-T     Disable pseudo-tty allocation. By default docker-compose exec allocates a TTY.

Body:
After I run this

docker run --rm -v "/c/users/vipul rao/documents/github/wappalyzer:/opt/wappalyzer" -it wappalyzer/dev

I am getting the following error

the input device is not a TTY.  If you are using mintty, try prefixing the command with 'winpty'

What should I use here? I am running Docker on Windows 8 in MINGW64.


问:
How to access MERN application deployed to alibaba cloud in the browser
I have deployed my MERN application to Alibaba ECS instance. Is there any way to access it in the browser, just like AWS public DNS? In AWS you use the public DNS to access your deployed application. I am not sure what to use to achieve the same. Below is the NGINX config present in the /etc/nginx/sites-available/default. I am using Ubuntu 18.04.

Surprisingly, I was able to hit the APIs without any issue. you can check the pm2 logs below

I am new to cloud deployment. If I have missed anything or if you need more information please let me know. Any help would be highly appreciated.

答:
Maybe you can find solution on this two articles on Alibaba Cloud documentation for that problem, if I understood your question correctly:

IP addresses of ECS instances within VPCs: https://www.alibabacloud.com/help/doc-detail/25434.htm

Connect to a Linux instance by using a username and password: https://www.alibabacloud.com/help/doc-detail/25434.htm

Hope this would help


答:
You could do this with a table-valued-parameter and user-defined-type, then inner join:

SELECT * FROM EntityPermission ep
INNER JOIN @foo f ON f.Id = ep.Id AND f.HasAccess = ep.HasAccess
```

<p>However: UDTs and TVPs are really very awkward to work with; frankly, I'd be tempted to just create two concatenated strings:</p>

<pre class="lang-cs prettyprint-override"><code>string with = string.Join(",", list.Where(x => x.HasAccess).Select(x => x.Id));
string without = string.Join(",", list.Where(x => !x.HasAccess).Select(x => x.Id));
</code>```

and pass that down as parameters to use with string_split:

SELECT *
FROM EntityPermission
WHERE (Id in (select value from string_split(@with, ',')) and HasAccess = 1)
OR (Id in (select value from string_split(@without, ',')) and HasAccess = 0)

```

Title: Comparing sql with c# list in query?

Body:
You could do this with a table-valued-parameter and user-defined-type, then inner join:

SELECT * FROM EntityPermission ep
INNER JOIN @foo f ON f.Id = ep.Id AND f.HasAccess = ep.HasAccess

However: UDTs and TVPs are really very awkward to work with; frankly, I'd be tempted to just create two concatenated strings:

string with = string.Join(",", list.Where(x => x.HasAccess).Select(x => x.Id));
string without = string.Join(",", list.Where(x => !x.HasAccess).Select(x => x.Id));

and pass that down as parameters to use with string_split:

SELECT *
FROM EntityPermission
WHERE (Id in (select value from string_split(@with, ',')) and HasAccess = 1)
OR (Id in (select value from string_split(@without, ',')) and HasAccess = 0)


问:
click second radio button with java selenium
i want to klick on the second radio button with java/selenium.
Ids are dynamic and i dont know why xpath dont work.
It would be really helpful if you guys can show me how this works.

HTML

```<code>   <div class="form-radiobutton-group group-horizontal" id="id29">
            <div class="form-radiobutton-element">
                <span class="form-radiobutton-wrapper">
                    <input class="salutation_f feedback-panel-trigger wicket-id29" id="id4" name="personaldataPanel:salutation:choices" value="radio9" type="radio">
                    <label for="id4" class=""></label>
                </span>
                <label for="id4">
                    Frau
                </label>
            </div>
            <div class="form-radiobutton-element">
                <span class="form-radiobutton-wrapper">
                    <input class="salutation_m feedback-panel-trigger wicket-id29" id="id3" name="personaldataPanel:salutation:choices" value="radio11" type="radio">
                    <label for="id3" class=""></label>
                </span>
                <label for="id3">
                    Herr
                </label>
            </div>
        </div>
</code>```

Code right now

```<code>WebElement m = driver.findElement(By.xpath("//div[2]/span/input"));
m.click();
</code>```

答:
```<code>driver.findElement(By.xpath("//*[text()='the label text']").click();
</code>```

by this way, you can find out the name of the label and click on the particular radio button by this.

ContentLicense: CC BY-SA 3.0

Body:
i want to klick on the second radio button with java/selenium.
Ids are dynamic and i dont know why xpath dont work.
It would be really helpful if you guys can show me how this works.

HTML

                    <input class="salutation_f feedback-panel-trigger wicket-id29" id="id4" name="personaldataPanel:salutation:choices" value="radio9" type="radio">

                    Frau

                    <input class="salutation_m feedback-panel-trigger wicket-id29" id="id3" name="personaldataPanel:salutation:choices" value="radio11" type="radio">

                    Herr

Code right now

WebElement m = driver.findElement(By.xpath("//div[2]/span/input"));
m.click();

Body:
driver.findElement(By.xpath("//*[text()='the label text']").click();

by this way, you can find out the name of the label and click on the particular radio button by this.