问:
My class cannot be used as type parameter 'TEventArgs' in the generic type or method 'System.EventHandler<TEventArgs>' in .Net 4
I have trying to learn about EventHandler and I have to use a notification project.
Here is the link of project :
https://codeload.github.com/mike-eason/WPF_ToastNotifications/zip/master

All I did is changing .Net-framework from 4.5 to 4

And I faced with this error:

My class cannot be used as type parameter 'TEventArgs' in the generic
  type or method 'System.EventHandler'

ToastNotification Class:

```<code> [TemplatePart(Name = "PART_DismissButton", Type = typeof(Button))]
    public class ToastNotification : ContentControl
    {
        public event EventHandler Dismissed;

        public string Title
        {
            get { return (string)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, value); }
        }

        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register("Title", typeof(string), typeof(ToastNotification));

        public string Message
        {
            get { return (string)GetValue(MessageProperty); }
            set { SetValue(MessageProperty, value); }
        }

        public static readonly DependencyProperty MessageProperty =
            DependencyProperty.Register("Message", typeof(string), typeof(ToastNotification));

        public ToastTypes ToastType
        {
            get { return (ToastTypes)GetValue(ToastTypeProperty); }
            set { SetValue(ToastTypeProperty, value); }
        }

        public static readonly DependencyProperty ToastTypeProperty =
            DependencyProperty.Register("ToastType", typeof(ToastTypes), typeof(ToastNotification), new PropertyMetadata(new PropertyChangedCallback(OnToastTypeChanged)));

        private static void OnToastTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ToastNotification toast = (ToastNotification)d;

            toast.RefreshBackgroundColour();
        }

        private void RefreshBackgroundColour()
        {
            switch (ToastType)
            {
                case ToastTypes.Success:
                    Background = ColourSuccess;
                    break;
                case ToastTypes.Error:
                    Background = ColourDanger;
                    break;
                case ToastTypes.Info:
                    Background = ColourInfo;
                    break;
                case ToastTypes.Warning:
                    Background = ColourWarning;
                    break;
            }
        }

        public bool IsPersistent
        {
            get { return (bool)GetValue(IsPersistentProperty); }
            set { SetValue(IsPersistentProperty, value); }
        }

        public static readonly DependencyProperty IsPersistentProperty =
            DependencyProperty.Register("IsPersistent", typeof(bool), typeof(ToastNotification));

        public double FontSizeTitle
        {
            get { return (double)GetValue(FontSizeTitleProperty); }
            set { SetValue(FontSizeTitleProperty, value); }
        }

        public static readonly DependencyProperty FontSizeTitleProperty =
            DependencyProperty.Register("FontSizeTitle", typeof(double), typeof(ToastNotification));

        public Brush ColourSuccess
        {
            get { return (Brush)GetValue(ColourSuccessProperty); }
            set { SetValue(ColourSuccessProperty, value); }
        }

        public static readonly DependencyProperty ColourSuccessProperty =
            DependencyProperty.Register("ColourSuccess", typeof(Brush), typeof(ToastNotification));

        public Brush ColourDanger
        {
            get { return (Brush)GetValue(ColourDangerProperty); }
            set { SetValue(ColourDangerProperty, value); }
        }

        public static readonly DependencyProperty ColourDangerProperty =
            DependencyProperty.Register("ColourDanger", typeof(Brush), typeof(ToastNotification));

        public Brush ColourInfo
        {
            get { return (Brush)GetValue(ColourInfoProperty); }
            set { SetValue(ColourInfoProperty, value); }
        }

        public static readonly DependencyProperty ColourInfoProperty =
            DependencyProperty.Register("ColourInfo", typeof(Brush), typeof(ToastNotification));

        public Brush ColourWarning
        {
            get { return (Brush)GetValue(ColourWarningProperty); }
            set { SetValue(ColourWarningProperty, value); }
        }

        public static readonly DependencyProperty ColourWarningProperty =
            DependencyProperty.Register("ColourWarning", typeof(Brush), typeof(ToastNotification));

        static ToastNotification()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ToastNotification), new FrameworkPropertyMetadata(typeof(ToastNotification)));
        }

        public ToastNotification()
        {
            this.Loaded += ToastNotification_Loaded;
        }

        private void ToastNotification_Loaded(object sender, RoutedEventArgs e)
        {
            Storyboard sb = this.FindResource("ToastScaleInStoryboard") as Storyboard;
            Storyboard.SetTarget(sb, this);
            sb.Begin();
        }

        public override void OnApplyTemplate()
        {
            ButtonBase PART_DismissButton = this.GetTemplateChild("PART_DismissButton") as ButtonBase;

            if (PART_DismissButton != null)
                PART_DismissButton.Click += OnDismissed;

            base.OnApplyTemplate();

            RefreshBackgroundColour();
        }

        protected void OnDismissed(object sender, RoutedEventArgs e)
        {
            var eh = Dismissed;

            if (eh != null)
                eh(this, EventArgs.Empty);
        }
    }
</code>```

Toast Class:

```<code>  internal class Toast
    {
        public event EventHandler<ToastNotification> ToastClosing;

        private DispatcherTimer _Timer;
        private ToastNotification _Notification;

        public Toast(ToastNotification notification)
        {
            _Notification = notification;

            _Notification.Dismissed += Notification_Dismissed;
        }

        private void Notification_Dismissed(object sender, EventArgs e)
        {
            OnToastClosing();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            //Stop and close the window.
            _Timer.Stop();

            OnToastClosing();
        }

        public void Show(TimeSpan displayTime)
        {
            //Only start the timer if the notification is not persistent.
            if (!_Notification.IsPersistent)
            {
                //Set up the timer
                _Timer = new DispatcherTimer();
                _Timer.Interval = displayTime;
                _Timer.Tick += Timer_Tick;

                //Start the timer
                _Timer.Start();
            }
        }

        protected void OnToastClosing()
        {
            //Unsubscribe from the on dismiss event first (to avoid memory leaks)
            _Notification.Dismissed -= Notification_Dismissed;

            var eh = ToastClosing;

            if (eh != null)
                eh(this, _Notification);
        }
    }
</code>```

答:
System.EventHandler<T> delegate was changed in .NET 4.5. Before 4.5 it has the following signature:

```<code>public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e)
    where TEventArgs : EventArgs;
</code>```

Starting with .NET 4.5 it has another definition:

```<code>public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);
</code>```

Note that where ... part has been removed. So before .NET 4.5 the type you use for event handler argument should inherit from EventArgs. Your ToastNotification does not inherit from that class, so cannot be used, hence your compiler error. When project targets .NET 4.5+ - you can use any type there so it compiles fine.

You can change your ToastClosing to

```<code>public event Action<object, ToastNotification> ToastClosing;
</code>```

and it will compile just fine.

Body:
I have trying to learn about EventHandler and I have to use a notification project.
Here is the link of project :
https://codeload.github.com/mike-eason/WPF_ToastNotifications/zip/master

All I did is changing .Net-framework from 4.5 to 4

And I faced with this error:

My class cannot be used as type parameter 'TEventArgs' in the generic
  type or method 'System.EventHandler'

ToastNotification Class:

 [TemplatePart(Name = "PART_DismissButton", Type = typeof(Button))]
    public class ToastNotification : ContentControl
    {
        public event EventHandler Dismissed;

        public string Title
        {
            get { return (string)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, value); }
        }

        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register("Title", typeof(string), typeof(ToastNotification));

        public string Message
        {
            get { return (string)GetValue(MessageProperty); }
            set { SetValue(MessageProperty, value); }
        }

        public static readonly DependencyProperty MessageProperty =
            DependencyProperty.Register("Message", typeof(string), typeof(ToastNotification));

        public ToastTypes ToastType
        {
            get { return (ToastTypes)GetValue(ToastTypeProperty); }
            set { SetValue(ToastTypeProperty, value); }
        }

        public static readonly DependencyProperty ToastTypeProperty =
            DependencyProperty.Register("ToastType", typeof(ToastTypes), typeof(ToastNotification), new PropertyMetadata(new PropertyChangedCallback(OnToastTypeChanged)));

        private static void OnToastTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ToastNotification toast = (ToastNotification)d;

            toast.RefreshBackgroundColour();
        }

        private void RefreshBackgroundColour()
        {
            switch (ToastType)
            {
                case ToastTypes.Success:
                    Background = ColourSuccess;
                    break;
                case ToastTypes.Error:
                    Background = ColourDanger;
                    break;
                case ToastTypes.Info:
                    Background = ColourInfo;
                    break;
                case ToastTypes.Warning:
                    Background = ColourWarning;
                    break;
            }
        }

        public bool IsPersistent
        {
            get { return (bool)GetValue(IsPersistentProperty); }
            set { SetValue(IsPersistentProperty, value); }
        }

        public static readonly DependencyProperty IsPersistentProperty =
            DependencyProperty.Register("IsPersistent", typeof(bool), typeof(ToastNotification));

        public double FontSizeTitle
        {
            get { return (double)GetValue(FontSizeTitleProperty); }
            set { SetValue(FontSizeTitleProperty, value); }
        }

        public static readonly DependencyProperty FontSizeTitleProperty =
            DependencyProperty.Register("FontSizeTitle", typeof(double), typeof(ToastNotification));

        public Brush ColourSuccess
        {
            get { return (Brush)GetValue(ColourSuccessProperty); }
            set { SetValue(ColourSuccessProperty, value); }
        }

        public static readonly DependencyProperty ColourSuccessProperty =
            DependencyProperty.Register("ColourSuccess", typeof(Brush), typeof(ToastNotification));

        public Brush ColourDanger
        {
            get { return (Brush)GetValue(ColourDangerProperty); }
            set { SetValue(ColourDangerProperty, value); }
        }

        public static readonly DependencyProperty ColourDangerProperty =
            DependencyProperty.Register("ColourDanger", typeof(Brush), typeof(ToastNotification));

        public Brush ColourInfo
        {
            get { return (Brush)GetValue(ColourInfoProperty); }
            set { SetValue(ColourInfoProperty, value); }
        }

        public static readonly DependencyProperty ColourInfoProperty =
            DependencyProperty.Register("ColourInfo", typeof(Brush), typeof(ToastNotification));

        public Brush ColourWarning
        {
            get { return (Brush)GetValue(ColourWarningProperty); }
            set { SetValue(ColourWarningProperty, value); }
        }

        public static readonly DependencyProperty ColourWarningProperty =
            DependencyProperty.Register("ColourWarning", typeof(Brush), typeof(ToastNotification));

        static ToastNotification()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ToastNotification), new FrameworkPropertyMetadata(typeof(ToastNotification)));
        }

        public ToastNotification()
        {
            this.Loaded += ToastNotification_Loaded;
        }

        private void ToastNotification_Loaded(object sender, RoutedEventArgs e)
        {
            Storyboard sb = this.FindResource("ToastScaleInStoryboard") as Storyboard;
            Storyboard.SetTarget(sb, this);
            sb.Begin();
        }

        public override void OnApplyTemplate()
        {
            ButtonBase PART_DismissButton = this.GetTemplateChild("PART_DismissButton") as ButtonBase;

            if (PART_DismissButton != null)
                PART_DismissButton.Click += OnDismissed;

            base.OnApplyTemplate();

            RefreshBackgroundColour();
        }

        protected void OnDismissed(object sender, RoutedEventArgs e)
        {
            var eh = Dismissed;

            if (eh != null)
                eh(this, EventArgs.Empty);
        }
    }

Toast Class:

  internal class Toast
    {
        public event EventHandler<ToastNotification> ToastClosing;

        private DispatcherTimer _Timer;
        private ToastNotification _Notification;

        public Toast(ToastNotification notification)
        {
            _Notification = notification;

            _Notification.Dismissed += Notification_Dismissed;
        }

        private void Notification_Dismissed(object sender, EventArgs e)
        {
            OnToastClosing();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            //Stop and close the window.
            _Timer.Stop();

            OnToastClosing();
        }

        public void Show(TimeSpan displayTime)
        {
            //Only start the timer if the notification is not persistent.
            if (!_Notification.IsPersistent)
            {
                //Set up the timer
                _Timer = new DispatcherTimer();
                _Timer.Interval = displayTime;
                _Timer.Tick += Timer_Tick;

                //Start the timer
                _Timer.Start();
            }
        }

        protected void OnToastClosing()
        {
            //Unsubscribe from the on dismiss event first (to avoid memory leaks)
            _Notification.Dismissed -= Notification_Dismissed;

            var eh = ToastClosing;

            if (eh != null)
                eh(this, _Notification);
        }
    }

Body:
System.EventHandler<T> delegate was changed in .NET 4.5. Before 4.5 it has the following signature:

public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e)
    where TEventArgs : EventArgs;

Starting with .NET 4.5 it has another definition:

public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);

Note that where ... part has been removed. So before .NET 4.5 the type you use for event handler argument should inherit from EventArgs. Your ToastNotification does not inherit from that class, so cannot be used, hence your compiler error. When project targets .NET 4.5+ - you can use any type there so it compiles fine.

You can change your ToastClosing to

public event Action<object, ToastNotification> ToastClosing;

and it will compile just fine.


来源: stackexchange

问:
Error:cannot get automation extension for chrome with selenium
 Iam getting below Exception when i run test case ,this is happening after my chrome browser got updated to 62.0 version. I have updated chrome driver to 2.33 version ,even after updating facing the same issue. Selenium version being used is 2.52</p>

```<code>         org.openqa.selenium.WebDriverException: unknown error: cannot get automation extension
from unknown error: page could not be found: chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 10.10 seconds
Build info: version: '2.35.0', revision: '8df0c6bedf70ff9f22c647788f9fe9c8d22210e2', time: '2013-08-17 12:46:41'
System info: os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_71'
Session ID: 30ad534f9914fe71f672dd12e56a0aea
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={userDataDir=C:\Users\ab83622\AppData\Local\Temp\scoped_dir6624_25177, chromedriverVersion=2.29.461591 (62ebf098771772160f391d75e589dc567915b233)}, networkConnectionEnabled=false, unexpectedAlertBehaviour=, rotatable=false, locationContextEnabled=true, mobileEmulationEnabled=false, version=62.0.3202.94, pageLoadStrategy=normal, takesHeapSnapshot=true, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true, browserConnectionEnabled=false, webStorageEnabled=true, nativeEvents=true, hasTouchScreen=false, applicationCacheEnabled=false, takesScreenshot=true}]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:191)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)
    at org.openqa.selenium.remote.RemoteWebDriver$RemoteWebDriverOptions$RemoteWindow.maximize(RemoteWebDriver.java:783)
    at com.ctlts.bpm.console.test.selenium.SeleniumRule.before(SeleniumRule.java:98)
    at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:46)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at com.ctlts.bpm.console.test.testtools.TestRunner.run(TestRunner.java:82)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code>```

答:
The error says it all WebDriverException: unknown error: cannot get automation extension

As per your Error Stack Trace you are using :

chromedriver=2.29

chrome=62.0

The Release Notes of chromedriver=2.29 clearly mentions the following :

Supports Chrome v56-58

The Release Notes of chromedriver=2.33 clearly mentions the following :

Supports Chrome v60-62

Solution :

The solution will be either to upgrade chromedriver binary to v2.33 levels or to downgrade your Chrome Browser binary to v56-58

ContentLicense: CC BY-SA 3.0

Body:
 Iam getting below Exception when i run test case ,this is happening after my chrome browser got updated to 62.0 version. I have updated chrome driver to 2.33 version ,even after updating facing the same issue. Selenium version being used is 2.52

         org.openqa.selenium.WebDriverException: unknown error: cannot get automation extension
from unknown error: page could not be found: chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 10.10 seconds
Build info: version: '2.35.0', revision: '8df0c6bedf70ff9f22c647788f9fe9c8d22210e2', time: '2013-08-17 12:46:41'
System info: os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_71'
Session ID: 30ad534f9914fe71f672dd12e56a0aea
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{platform=XP, acceptSslCerts=true, javascriptEnabled=true, browserName=chrome, chrome={userDataDir=C:\Users\ab83622\AppData\Local\Temp\scoped_dir6624_25177, chromedriverVersion=2.29.461591 (62ebf098771772160f391d75e589dc567915b233)}, networkConnectionEnabled=false, unexpectedAlertBehaviour=, rotatable=false, locationContextEnabled=true, mobileEmulationEnabled=false, version=62.0.3202.94, pageLoadStrategy=normal, takesHeapSnapshot=true, cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=true, browserConnectionEnabled=false, webStorageEnabled=true, nativeEvents=true, hasTouchScreen=false, applicationCacheEnabled=false, takesScreenshot=true}]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:191)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:145)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)
    at org.openqa.selenium.remote.RemoteWebDriver$RemoteWebDriverOptions$RemoteWindow.maximize(RemoteWebDriver.java:783)
    at com.ctlts.bpm.console.test.selenium.SeleniumRule.before(SeleniumRule.java:98)
    at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:46)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at com.ctlts.bpm.console.test.testtools.TestRunner.run(TestRunner.java:82)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)


问:
Mysql - php query fetch array results using multiple parameters
I have a mysql table as below,

```<code>+---+-------+-----------+
|Sl | Name  | Status    |
+---+-------+-----------+
| 1 | Name1 | Active    |
| 2 | Name2 | Inactive  |
| 3 | Name3 | Pending   |
| 4 | Name4 | Dont Know |
| 5 | Name5 | Active    |
+---+-------+-----------+
</code>```

I have a sql query $query="select * from table ";
which fetch array and give me all records. But I want to display only specific rows with  Status= Active or Inactive.

答:
You need to alter your SQL</p>

```<code>SELECT * FROM table WHERE Status = 'Active' OR Status = 'Inactive'
</code>```

Body:
I have a mysql table as below,

+---+-------+-----------+
|Sl | Name  | Status    |
+---+-------+-----------+
| 1 | Name1 | Active    |
| 2 | Name2 | Inactive  |
| 3 | Name3 | Pending   |
| 4 | Name4 | Dont Know |
| 5 | Name5 | Active    |
+---+-------+-----------+

I have a sql query $query="select * from table ";
which fetch array and give me all records. But I want to display only specific rows with  Status= Active or Inactive.

Body:
You need to alter your SQL

SELECT * FROM table WHERE Status = 'Active' OR Status = 'Inactive'

ContentLicense: CC BY-SA 2.5


问:
Error importing tensorflow in Python 3 on Ubuntu 16.04 SyntaxError: l.append("%s=%s" % (attr, `value`))

I have python 3.5 installed on my Linux Mint (Ubuntu 16.04 Xenial)

I also had installed protobuf installed using pip3 install protobuf

I installed tensorflow using pip3 install tensorflow

Then I tried to import tensorflow in python 3 it failed with error presented below:

```<code>Traceback (most recent call last):
  File "/home/abdullah/face_recognition/tensorflow_test.py", line 1, in <module>
    import tensorflow
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/__init__.py", line 83, in <module>
    from tensorflow.python.estimator import estimator_lib as estimator
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/estimator_lib.py", line 35, in <module>
    from tensorflow.python.estimator.inputs import inputs
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/inputs/inputs.py", line 22, in <module>
    from tensorflow.python.estimator.inputs.numpy_io import numpy_input_fn
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/inputs/numpy_io.py", line 22, in <module>
    from tensorflow.python.estimator.inputs.queues import feeding_functions
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/inputs/queues/feeding_functions.py", line 40, in <module>
    import pandas as pd
  File "/usr/local/lib/python3.5/dist-packages/pandas/__init__.py", line 23, in <module>
    from pandas.compat.numpy import *
  File "/usr/local/lib/python3.5/dist-packages/pandas/compat/__init__.py", line 361, in <module>
    from dateutil import parser as _date_parser
  File "/usr/local/lib/python3.5/dist-packages/dateutil/parser.py", line 158
    l.append("%s=%s" % (attr, `value`))
                              ^
SyntaxError: invalid syntax
</code>```

Consulting through many questions posted on SO and other forums, I tried uninstalling protobuf then I encountered following error.

```<code>Traceback (most recent call last):
  File "/home/abdullah/face_recognition/tensorflow_test.py", line 1, in <module>
    import tensorflow
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/__init__.py", line 52, in <module>
    from tensorflow.core.framework.graph_pb2 import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/core/framework/graph_pb2.py", line 6, in <module>
    from google.protobuf import descriptor as _descriptor
ImportError: No module named 'google.protobuf'
</code>```

At the moment I'm just a beginner for all of this. I don't why protobuf is required why do all this hassle? I just wanted to get tensorflow installed on my system and try to learn something.

答:
I just installed TensorFlow on my system today (Ubuntu 16.04 LTS) using VirtualEnv.

Did you run$ sudo apt-get install python3-pip python3-dev

If so, then try $ pip3 install -upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.4.0-cp35-cp35m-linux_x86_64.whl

Worst comes to worse, you could simply uninstall TensorFlow using $ sudo pip3 uninstall tensorflow and then try reinstalling to see if it corrects any errors.

Body:
I have python 3.5 installed on my Linux Mint (Ubuntu 16.04 Xenial)

I also had installed protobuf installed using pip3 install protobuf

I installed tensorflow using pip3 install tensorflow

Then I tried to import tensorflow in python 3 it failed with error presented below:

Traceback (most recent call last):
  File "/home/abdullah/face_recognition/tensorflow_test.py", line 1, in <module>
    import tensorflow
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/__init__.py", line 83, in <module>
    from tensorflow.python.estimator import estimator_lib as estimator
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/estimator_lib.py", line 35, in <module>
    from tensorflow.python.estimator.inputs import inputs
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/inputs/inputs.py", line 22, in <module>
    from tensorflow.python.estimator.inputs.numpy_io import numpy_input_fn
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/inputs/numpy_io.py", line 22, in <module>
    from tensorflow.python.estimator.inputs.queues import feeding_functions
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/estimator/inputs/queues/feeding_functions.py", line 40, in <module>
    import pandas as pd
  File "/usr/local/lib/python3.5/dist-packages/pandas/__init__.py", line 23, in <module>
    from pandas.compat.numpy import *
  File "/usr/local/lib/python3.5/dist-packages/pandas/compat/__init__.py", line 361, in <module>
    from dateutil import parser as _date_parser
  File "/usr/local/lib/python3.5/dist-packages/dateutil/parser.py", line 158
    l.append("%s=%s" % (attr, `value`))
                              ^
SyntaxError: invalid syntax

Consulting through many questions posted on SO and other forums, I tried uninstalling protobuf then I encountered following error.

Traceback (most recent call last):
  File "/home/abdullah/face_recognition/tensorflow_test.py", line 1, in <module>
    import tensorflow
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/__init__.py", line 52, in <module>
    from tensorflow.core.framework.graph_pb2 import *
  File "/usr/local/lib/python3.5/dist-packages/tensorflow/core/framework/graph_pb2.py", line 6, in <module>
    from google.protobuf import descriptor as _descriptor
ImportError: No module named 'google.protobuf'

At the moment I'm just a beginner for all of this. I don't why protobuf is required why do all this hassle? I just wanted to get tensorflow installed on my system and try to learn something.


问:
getQuantityString not working on real device
I got an odd problem. The getQuantityString() method working on android studio simulator, but not working on the real device.

This is my code in strings.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals name="subtitle_plural">
        <item quantity="one">%1$s crime</item>
        <item quantity="other">%1$s crimes</item>
    </plurals>
</resources>
</code>```

code in my Fragment:

```<code>CrimeLab crimeLab = CrimeLab.get(getActivity());
int crimeSize = crimeLab.getCrimes().size();
String subTitle = getResources()
                .getQuantityString(R.plurals.subtitle_plural, crimeSize, crimeSize);
</code>```

When I run the project on the simulator, it works. but if run it on real device, subTitle will always be ** crimes even if crimeSize equals 1.

How did this happen?

答:
You should use like that:</p>

```<code>CrimeLab crimeLab = CrimeLab.get(getActivity());
int crimeSize = crimeLab.getCrimes().size();
String subTitle = String.format(getResources()
                .getQuantityString(R.plurals.subtitle_plural, crimeSize, crimeSize));
</code>```

Body:
I got an odd problem. The getQuantityString() method working on android studio simulator, but not working on the real device.

This is my code in strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals name="subtitle_plural">
        <item quantity="one">%1$s crime</item>
        <item quantity="other">%1$s crimes</item>
    </plurals>
</resources>

code in my Fragment:

CrimeLab crimeLab = CrimeLab.get(getActivity());
int crimeSize = crimeLab.getCrimes().size();
String subTitle = getResources()
                .getQuantityString(R.plurals.subtitle_plural, crimeSize, crimeSize);

When I run the project on the simulator, it works. but if run it on real device, subTitle will always be ** crimes even if crimeSize equals 1.

How did this happen?

Body:
You should use like that:

CrimeLab crimeLab = CrimeLab.get(getActivity());
int crimeSize = crimeLab.getCrimes().size();
String subTitle = String.format(getResources()
                .getQuantityString(R.plurals.subtitle_plural, crimeSize, crimeSize));


问:
Convert number into culture specific
I have a number like  202667.4. I want to convert this to number based on culture.

For Ex:

In "de"(German) the number should be in 202.667,40.

Any help will be greatly appreciated.

Thanks.

答:
If you want to represent existing number (say, double) in culture specific format, try formatting:

https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings

```<code>double source = 202667.4;

// "n"  - ... group separators, and a decimal separator with optional negative sign
// "de" - German culture
string result = source.ToString("n", CultureInfo.GetCultureInfo("de"));

Console.WriteLine(result);
</code>```

Outcome

```<code>202.667,40
</code>```

If you are given a string and you want a number, put Parse (TryParse):

```<code>string data = "202.667,40";

double result = double.Parse(data, CultureInfo.GetCultureInfo("de"));

Console.WriteLine(data.ToString(CultureInfo.InvariantCulture));
</code>```

If you don't want to specify the culture each time you work with formatting, you can set the culture as a current one:

```<code>CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de");

...

double source = 202667.4;

Console.WriteLine($"{source:n}");
</code>```

Title: Convert number into culture specific

Body:
If you want to represent existing number (say, double) in culture specific format, try formatting:

https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings

double source = 202667.4;

// "n"  - ... group separators, and a decimal separator with optional negative sign
// "de" - German culture
string result = source.ToString("n", CultureInfo.GetCultureInfo("de"));

Console.WriteLine(result);

Outcome

202.667,40

If you are given a string and you want a number, put Parse (TryParse):

string data = "202.667,40";

double result = double.Parse(data, CultureInfo.GetCultureInfo("de"));

Console.WriteLine(data.ToString(CultureInfo.InvariantCulture));

If you don't want to specify the culture each time you work with formatting, you can set the culture as a current one:

CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de");

...

double source = 202667.4;

Console.WriteLine($"{source:n}");


问:
How to compile SWIG via windows
I've downloaded swigwin, sigwin for windows, and have been checking examples. However, most examples have to compile like this: swig -example.i. I tried doing this over the cmd prompt but it does not work. Can you please teach me how I can do this on windows?</p>

答:
You have to choose a language.  To create a Python extension wrapper for C:

```<code>swig -python example.i
</code>```

for C++:

```<code>swig -python -c++ example.i
</code>```

See swig -help.

You may also need to add swig to your path.  Something like:

```<code>path c:\swigwin-2.0.0;%path%
</code>```

Or add it through Control Panel, System, Advanced, Environment Variables (on WinXP).

Title: How to compile SWIG via windows

Body:
You have to choose a language.  To create a Python extension wrapper for C:

swig -python example.i

for C++:

swig -python -c++ example.i

See swig -help.

You may also need to add swig to your path.  Something like:

path c:\swigwin-2.0.0;%path%

Or add it through Control Panel, System, Advanced, Environment Variables (on WinXP).


问:
FFImageLoading: Unhandled Exception: System.TypeLoadException: Could not load list of method overrides occurred
When trying to init FFImage (in my application):

```<code>CachedImageRenderer.Init();
</code>```

I get the mysterious error:

```<code>Unhandled Exception:  System.TypeLoadException: Could not load list of method overrides occurred
</code>```

I can get the FFImage sample app to run okay. I have the dependencies all in order as far as I can tell.

答: Don't use the version 2.2.23 to 2.2.25. Use the 2.2.22. This is very stable and also has the latest features. Hope this helps.</p>

Body:
When trying to init FFImage (in my application):

CachedImageRenderer.Init();

I get the mysterious error:

Unhandled Exception:  System.TypeLoadException: Could not load list of method overrides occurred

I can get the FFImage sample app to run okay. I have the dependencies all in order as far as I can tell.


问:
MySQL - Total count & rate of change in a single SQL query
I'm trying to extract the total number of website hits plus the rate of change(rate of increase/decrease) per client per city per day as a percentage in a single SQL query but not able to get it right.

I've created an example at

http://www.sqlfiddle.com/#!9/fd279/8

Could I please request assistance?

答:
first make a unique number like rownum
and make the same query
and join the rownum columns
then you can see former month as new column and calculate the changing rate.</p>

```<code>SELECT  A.HitDate, A.City, A.sumThis, B.sumFormer, (A.sumThis / B.sumFormer - 1) * 100 as 'ChangingRate'
From    (
        select @rownum1:=@rownum1 + 1 as 'rownum1', HitDate, City, sum(NumVisits) as 'sumThis'
        from page_hits, (Select @rownum1:=0) R
        Where client = 'C'
        Group by HitDate, City
        ) A
Left Join (
        select @rownum2:=@rownum2 + 1 as 'rownum2', HitDate, City, sum(NumVisits) as 'sumFormer'
        from page_hits, (Select @rownum2:=0) R
        Where client = 'C'
        Group by HitDate, City
        ) B On A.rownum1 - 1 = B.rownum2
</code>```

Body:
first make a unique number like rownum
and make the same query
and join the rownum columns
then you can see former month as new column and calculate the changing rate.

SELECT  A.HitDate, A.City, A.sumThis, B.sumFormer, (A.sumThis / B.sumFormer - 1) * 100 as 'ChangingRate'
From    (
        select @rownum1:=@rownum1 + 1 as 'rownum1', HitDate, City, sum(NumVisits) as 'sumThis'
        from page_hits, (Select @rownum1:=0) R
        Where client = 'C'
        Group by HitDate, City
        ) A
Left Join (
        select @rownum2:=@rownum2 + 1 as 'rownum2', HitDate, City, sum(NumVisits) as 'sumFormer'
        from page_hits, (Select @rownum2:=0) R
        Where client = 'C'
        Group by HitDate, City
        ) B On A.rownum1 - 1 = B.rownum2


问:
Assertion failure in -[UITableView _addScrollViewScrollObserver:] while using large title navigation ios 11
I have tab bar controller with view controller that has only a table view in it.

I am setting navigation bar large title using code:

```<code>if (@available(iOS 11.0, *)) {
        [[UINavigationBar appearance] setPrefersLargeTitles:YES];
    } else {
        // Fallback on earlier versions
    }
</code>```

It's crashing app when I open tab 2nd time. or randomly shifting tabs with following message.

Error message is shown below:

```<code>Assertion failure in -[UITableView _addScrollViewScrollObserver:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3694.4.18/UIScrollView.m:7693
</code>```

Any idea to fix issue. Thanks.

答:
Crash is caused by this method [[UINavigationBar appearance] setPrefersLargeTitles:YES]; Don't use above method.

Use following code in your UIViewControllers

```<code>if (@available(iOS 11.0, *))
    {
        self.navigationController.navigationBar.prefersLargeTitles = true;
        self.navigationController.navigationBar.topItem.title = @"Your Title here";
        self.navigationController.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAutomatic;

        NSDictionary *attributes = @{NSForegroundColorAttributeName: [UIColor redColor]};
        self.navigationController.navigationBar.largeTitleTextAttributes = attributes;
    }
    else
    {
        // Fallback on earlier versions
    }
</code>```

Body:
I have tab bar controller with view controller that has only a table view in it.

I am setting navigation bar large title using code:

if (@available(iOS 11.0, *)) {
        [[UINavigationBar appearance] setPrefersLargeTitles:YES];
    } else {
        // Fallback on earlier versions
    }

It's crashing app when I open tab 2nd time. or randomly shifting tabs with following message.

Error message is shown below:

Assertion failure in -[UITableView _addScrollViewScrollObserver:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3694.4.18/UIScrollView.m:7693

Any idea to fix issue. Thanks.

Body:
Crash is caused by this method [[UINavigationBar appearance] setPrefersLargeTitles:YES]; Don't use above method.

Use following code in your UIViewControllers

if (@available(iOS 11.0, *))
    {
        self.navigationController.navigationBar.prefersLargeTitles = true;
        self.navigationController.navigationBar.topItem.title = @"Your Title here";
        self.navigationController.navigationItem.largeTitleDisplayMode = UINavigationItemLargeTitleDisplayModeAutomatic;

        NSDictionary *attributes = @{NSForegroundColorAttributeName: [UIColor redColor]};
        self.navigationController.navigationBar.largeTitleTextAttributes = attributes;
    }
    else
    {
        // Fallback on earlier versions
    }


问:
How do I adjust the height of a particular listview when the content is more in android?
This is my code to display the content from firebase. But when the content is more, '..' will be displayed as shown in the image.
How do I make it to adjust the height automatically and display the full content instead of ..?

Screen-shot of the activity

```<code>Public class InstituteMessageBoard extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_institute_message_board);

        insTool = (Toolbar) findViewById(R.id.institute_toolbar);
        setSupportActionBar(insTool);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("Institute Notice");

        listView = (ListView) findViewById(R.id.listView);
        dRef = FirebaseDatabase.getInstance().getReference();

        adapter  = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, list);
        listView.setAdapter(adapter);

        DatabaseReference classPostRef = dRef.child("admin").child("classPost");
        classPostRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                    String post = dataSnapshot.child("post").getValue(String.class);
                    list.add(post);
                    adapter.notifyDataSetChanged();
    }

}
</code>```

答:
Try,

```<code>android.R.layout.simple_list_item_1
</code>```

instead of,

```<code>android.R.layout.simple_dropdown_item_1line
</code>```

Body:
This is my code to display the content from firebase. But when the content is more, '..' will be displayed as shown in the image.
How do I make it to adjust the height automatically and display the full content instead of ..?

Screen-shot of the activity

Public class InstituteMessageBoard extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_institute_message_board);

        insTool = (Toolbar) findViewById(R.id.institute_toolbar);
        setSupportActionBar(insTool);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("Institute Notice");

        listView = (ListView) findViewById(R.id.listView);
        dRef = FirebaseDatabase.getInstance().getReference();

        adapter  = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, list);
        listView.setAdapter(adapter);

        DatabaseReference classPostRef = dRef.child("admin").child("classPost");
        classPostRef.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {

                    String post = dataSnapshot.child("post").getValue(String.class);
                    list.add(post);
                    adapter.notifyDataSetChanged();
    }

}

Body:
Try,

android.R.layout.simple_list_item_1

instead of,

android.R.layout.simple_dropdown_item_1line


问:
UITableViewCell : UIImageView in ContentView overlaps images in iPhone SDK.
In my iPhone app,  I am using a tableView and have added the imageView as ContentView in my tableViewcell.

At the click of button I am changing the tableView Contents. So every time I click a button it should show the corresponding image in tableViewCell.

Problem:

Suppose I am loading images 1.png, 2.png and 3.png in tableView on click of button A, B and C respectively.

Now let us consider that initially I clicked button A and 1.png appears. Now when I click the button B then 2.png appears but 1.png also remains in background. So basically it overlaps the tableViewCell with a new image.

Troubleshooting I already have done:

1) I tried releasing imageView and setting imageView.image = nil;

2) I tried reloading the table and empty out table before each button click.

3) Even I tried putting the whole code in if(cell==nil) clause of cellForRowAtIndexPath method

答:
I have got the answer and I am really thankful to Ben Gottlieb:

remove image from tableViewCell created programmatically

ContentLicense: CC BY-SA 4.0


问:
Getting all selected checkboxes in an array
So I have these checkboxes:

```<code><input type="checkbox" name="type" value="4" />
<input type="checkbox" name="type" value="3" />
<input type="checkbox" name="type" value="1" />
<input type="checkbox" name="type" value="5" />
</code>```

And so on. There are about 6 of them and are hand-coded (i.e not fetched from a db) so they are likely to remain the same for a while.

My question is how I can get them all in an array (in javascript), so I can use them while making an AJAX $.post request using Jquery.

Any thoughts?

Edit: I would only want the selected checkboxes to be added to the array

答:
On checking add the value for checkbox and on dechecking subtract the value

$('#myDiv').change(function() {
  var values = 0.00;
  {
    $('#myDiv :checked').each(function() {
      //if(values.indexOf($(this).val()) === -1){
      values=values+parseFloat(($(this).val()));
      // }
    });
    console.log( parseFloat(values));
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="myDiv">
  <input type="checkbox" name="type" value="4.00" />
  <input type="checkbox" name="type" value="3.75" />
  <input type="checkbox" name="type" value="1.25" />
  <input type="checkbox" name="type" value="5.50" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script></code>```

OwnerDisplayName: Click Upvote

Body:
So I have these checkboxes:

<input type="checkbox" name="type" value="4" />
<input type="checkbox" name="type" value="3" />
<input type="checkbox" name="type" value="1" />
<input type="checkbox" name="type" value="5" />

And so on. There are about 6 of them and are hand-coded (i.e not fetched from a db) so they are likely to remain the same for a while.

My question is how I can get them all in an array (in javascript), so I can use them while making an AJAX $.post request using Jquery.

Any thoughts?

Edit: I would only want the selected checkboxes to be added to the array

Body:
On checking add the value for checkbox and on dechecking subtract the value

$('#myDiv').change(function() {
  var values = 0.00;
  {
    $('#myDiv :checked').each(function() {
      //if(values.indexOf($(this).val()) === -1){
      values=values+parseFloat(($(this).val()));
      // }
    });
    console.log( parseFloat(values));
  }
});

<div id="myDiv">
  <input type="checkbox" name="type" value="4.00" />
  <input type="checkbox" name="type" value="3.75" />
  <input type="checkbox" name="type" value="1.25" />
  <input type="checkbox" name="type" value="5.50" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


问:
Display queryset and it's foreign keys in order by id in django template
I am building a quiz program. Every test has question and questions have options. Option has foreign key to a question and question has foreign key to a test.
Every thing is good. But sometimes when displaying these in template, choice appear in reverse order that is sometimes choice d appears first and choice A appears last.

Here is the code:

```<code>{% for question in test.sscquestions_set.all %}

    <div class='well quest'>
         <h3 style= 'font-weight:bold;'> {{question.text}} </h3>
               {% for choice in question.choices_set.all %}
                     <p> {{choice.text}}</p>
    </div>
{%endfor%}
</code>```

How to always display choices in particular order (ie. OptionA first and Option D last)

答:
Or maybe you could specify the ordering in the model itself.</p>

```<code>class Option(models.Model):
    class Meta:
        ordering = ['pk']
</code>```

Body:
I am building a quiz program. Every test has question and questions have options. Option has foreign key to a question and question has foreign key to a test.
Every thing is good. But sometimes when displaying these in template, choice appear in reverse order that is sometimes choice d appears first and choice A appears last.

Here is the code:

{% for question in test.sscquestions_set.all %}

 {{question.text}}

               {% for choice in question.choices_set.all %}

 {{choice.text}}

{%endfor%}

How to always display choices in particular order (ie. OptionA first and Option D last)

Body:
Or maybe you could specify the ordering in the model itself.

class Option(models.Model):
    class Meta:
        ordering = ['pk']


问:
Azure AD V2 / msal.js restrict personal accounts?
I'm using msal.js to allow users to sign in with their AAD accounts. I created the application in https://apps.dev.microsoft.com/ using an account in the target tenant. I was under the impression that doing this would create the application under that tenant as well and that msal.js would just work. However, when loginRedirect() is called, I end up at the /common/ endpoint, and I'm allowed to sign in using all kinds of organization and personal accounts.

I was able to redirect to the correct login url by specifying the authority like so:

```<code>new Msal.UserAgentApplication({client_id}, 'https://login.microsoftonline.com/{tenant_id}/', () => {});
</code>```

However, this still doesn't restrict signing in using only accounts from that organization. In fact, I can also login with personal accounts.

I read from Is there a way to find whether authentication followed MSA or Azure AD in MSAL.js and https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-tokens that I could use the Guid portion of the iss property of the decoded id_token to determine if the user signed in using MSA or AAD. However, this always returns the same value which is https://sts.windows.net/{tenant_id}/ regardless if I sign in using MSA or other accounts.

My question is how do I enforce signing in only with user accounts from the same tenant, and if I can't do that, how do I at least get a value to check whether the user signed in using MSA or an account from the same tenant?

答:
You can specify organizations instead of common in the authority to allow only AAD accounts:

```<code>https://login.microsoftonline.com/organizations
</code>```

If you wanted only Microsoft accounts, you can use consumers.

To allow all, use common.

https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols#endpoints

When you create an app in the new v2 portal, the app will be multi-tenant by default, and you won't find it in your directory.

If you want a single-tenant app, use v1.

Body:
I'm using msal.js to allow users to sign in with their AAD accounts. I created the application in https://apps.dev.microsoft.com/ using an account in the target tenant. I was under the impression that doing this would create the application under that tenant as well and that msal.js would just work. However, when loginRedirect() is called, I end up at the /common/ endpoint, and I'm allowed to sign in using all kinds of organization and personal accounts.

I was able to redirect to the correct login url by specifying the authority like so:

new Msal.UserAgentApplication({client_id}, 'https://login.microsoftonline.com/{tenant_id}/', () => {});

However, this still doesn't restrict signing in using only accounts from that organization. In fact, I can also login with personal accounts.

I read from Is there a way to find whether authentication followed MSA or Azure AD in MSAL.js and https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-tokens that I could use the Guid portion of the iss property of the decoded id_token to determine if the user signed in using MSA or AAD. However, this always returns the same value which is https://sts.windows.net/{tenant_id}/ regardless if I sign in using MSA or other accounts.

My question is how do I enforce signing in only with user accounts from the same tenant, and if I can't do that, how do I at least get a value to check whether the user signed in using MSA or an account from the same tenant?

Body:
You can specify organizations instead of common in the authority to allow only AAD accounts:

https://login.microsoftonline.com/organizations

If you wanted only Microsoft accounts, you can use consumers.

To allow all, use common.

https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols#endpoints

When you create an app in the new v2 portal, the app will be multi-tenant by default, and you won't find it in your directory.

If you want a single-tenant app, use v1.


问:
Can someone explain to me why overflow always occurs when the last and second last carry bit are different?
```<code>overflow = c,n ⊕ c,n−1
</code>```

I tried it with all four possible cases

```<code>                            c,n   c,n-1
-7+2      1001+0010         0     0
7+2       0111+0010         0     1
-7+(-2)   1001+1110         1     0
7+(-2)    0111+1110         1     1
</code>```

and it seems to work, but can someone explain or prove why?

答:
It's been so long, I have only a vague understanding of what the notation is saying.  I'd assume that 'c' is a carry flag, and 'n' is a negative flag.  But then what is 'n-1'?

Anyway, I'm guessing your answer pertains to overflow occurring in either direction: from a negative number wrapping over into a positive, and a positive wrapping over into a negative.

Body:
overflow = c,n ⊕ c,n−1

I tried it with all four possible cases

                            c,n   c,n-1
-7+2      1001+0010         0     0
7+2       0111+0010         0     1
-7+(-2)   1001+1110         1     0
7+(-2)    0111+1110         1     1

and it seems to work, but can someone explain or prove why?


问:
UWP : How to get new size of shape after rotation?
How to measure its width and height after rotation in UWP? It can be any shape, such as a polygon or ellipse.

答:
Unfortunately, I can't find a way to compute the bounding box from the XAML visual tree. I normally use Win2D for these types of operations. Have a look at CanvasGeometry and its ability to compute a bounding box.

If you don't have access to Win2D or you just need a quick solution to this problem, here's a helper class that should work on any shape, ellipse, path, etc:

Warning: this is a poor implementation that uses brute force hit-testing. I've added a timer to prove how slow it is.

```<code>public static class BoundsHelper
{
    /// <summary>Computes the axis-aligned minimum bounding box of the given <paramref name="element"/>.</summary>
    /// <param name="element">The element to test.</param>
    /// <param name="tolerance">The precision tolerance expressed in pixels. The lower the value the higher the precision, but the slower the operation.</param>
    public static Rect ComputeBounds(FrameworkElement element, float tolerance = .5f)
    {
        var sw = Stopwatch.StartNew();
        var transform = element.TransformToVisual(null);
        var bounds = new Rect(0, 0, element.ActualWidth, element.ActualHeight);

        bounds = transform.TransformBounds(bounds);

        var minX = TestX(element, bounds, tolerance);
        var minY = TestY(element, bounds, tolerance);
        var maxX = TestX(element, bounds, -tolerance);
        var maxY = TestY(element, bounds, -tolerance);

        sw.Stop();

        Debug.WriteLine($"{sw.Elapsed.TotalMilliseconds} ms to compute bounds with tolerance = {tolerance}");

        return new Rect(new Point(minX, minY), new Point(maxX, maxY));
    }

    private static double TestX(UIElement element, Rect bounds, float tolerance)
    {
        bounds = tolerance > 0
            ? new Rect(bounds.Left, bounds.Top, tolerance, bounds.Height)
            : new Rect(bounds.Right + tolerance, bounds.Top, -tolerance, bounds.Height);

        while (!VisualTreeHelper.FindElementsInHostCoordinates(bounds, element).Any())
        {
            bounds.X += tolerance;
        }

        return bounds.X;
    }

    private static double TestY(UIElement element, Rect bounds, float tolerance)
    {
        bounds = tolerance > 0
            ? new Rect(bounds.Left, bounds.Top, bounds.Width, tolerance)
            : new Rect(bounds.Left, bounds.Bottom + tolerance, bounds.Width, -tolerance);

        while (!VisualTreeHelper.FindElementsInHostCoordinates(bounds, element).Any())
        {
            bounds.Y += tolerance;
        }

        return bounds.Y;
    }
}
</code>```

Body:
Unfortunately, I can't find a way to compute the bounding box from the XAML visual tree. I normally use Win2D for these types of operations. Have a look at CanvasGeometry and its ability to compute a bounding box.

If you don't have access to Win2D or you just need a quick solution to this problem, here's a helper class that should work on any shape, ellipse, path, etc:

Warning: this is a poor implementation that uses brute force hit-testing. I've added a timer to prove how slow it is.

public static class BoundsHelper
{
    /// <summary>Computes the axis-aligned minimum bounding box of the given <paramref name="element"/>.</summary>
    /// <param name="element">The element to test.</param>
    /// <param name="tolerance">The precision tolerance expressed in pixels. The lower the value the higher the precision, but the slower the operation.</param>
    public static Rect ComputeBounds(FrameworkElement element, float tolerance = .5f)
    {
        var sw = Stopwatch.StartNew();
        var transform = element.TransformToVisual(null);
        var bounds = new Rect(0, 0, element.ActualWidth, element.ActualHeight);

        bounds = transform.TransformBounds(bounds);

        var minX = TestX(element, bounds, tolerance);
        var minY = TestY(element, bounds, tolerance);
        var maxX = TestX(element, bounds, -tolerance);
        var maxY = TestY(element, bounds, -tolerance);

        sw.Stop();

        Debug.WriteLine($"{sw.Elapsed.TotalMilliseconds} ms to compute bounds with tolerance = {tolerance}");

        return new Rect(new Point(minX, minY), new Point(maxX, maxY));
    }

    private static double TestX(UIElement element, Rect bounds, float tolerance)
    {
        bounds = tolerance > 0
            ? new Rect(bounds.Left, bounds.Top, tolerance, bounds.Height)
            : new Rect(bounds.Right + tolerance, bounds.Top, -tolerance, bounds.Height);

        while (!VisualTreeHelper.FindElementsInHostCoordinates(bounds, element).Any())
        {
            bounds.X += tolerance;
        }

        return bounds.X;
    }

    private static double TestY(UIElement element, Rect bounds, float tolerance)
    {
        bounds = tolerance > 0
            ? new Rect(bounds.Left, bounds.Top, bounds.Width, tolerance)
            : new Rect(bounds.Left, bounds.Bottom + tolerance, bounds.Width, -tolerance);

        while (!VisualTreeHelper.FindElementsInHostCoordinates(bounds, element).Any())
        {
            bounds.Y += tolerance;
        }

        return bounds.Y;
    }
}


问:
Zelle Python Chapter 4 Q1: Why can't I use clone()?
The question is to modify the program below so that each successive click will draw an additional square on the screen.

Here is the program to be modified.

```<code>   def main():
win = GraphWin()
shape = Rectangle(Point(50,50), Point(70,70))
shape.setOutline("red")
shape.setFill("red")
shape.draw(win)
for i in range(10):
    p = win.getMouse()
    c = shape.getCenter()
    dx = p.getX() - c.getX()
    dy = p.getY() - c.getY()
    shape.move(dx,dy)
win.close()
</code>```

To solve this, I have employed the clone() function. Here is my solution:

```<code> def main():
win = GraphWin()
shape = Rectangle(Point(50,50), Point(70,70))
shape.setOutline("red")
shape.setFill("red")
shape.draw(win)
for i in range(10):
    p = win.getMouse()
    c = shape.getCenter()
    dx = p.getX() - c.getX()
    dy = p.getY() - c.getY()
    pshaw = shape.clone()
    pshaw.move(dx, dy)
win.close()
</code>```

However, the program does not work. Other solutions I have seen involve creating a new shape altogether as show below: Why can I not use clone()?

```<code>    def main():
win = GraphWin()
shape = Rectangle(Point(75,75),Point(125,125))
shape.setOutline('Red')
shape.setFill('Red')
shape.draw(win)

for i in range(5):
    p = win.getMouse()
    tx = p.getX()-25
    ty = p.getY()-25
    bx = p.getX()+25
    by = p.getY()+25

    shape2 = Rectangle(Point(tx,ty),Point(bx,by))
    shape2.setOutline('Red')
    shape2.setFill('Red')
    shape2.draw(win)

ct = Text(Point(100,180),'Click again to quit!')
ct.setStyle('bold')
ct.draw(win)
win.getMouse()
win.close()
</code>```

main()

Why does clone() not work here? Is this not the purpose it was created for? The proposed solution with its creating of a new shape from scratch seems redundant to me.

Any attempts to help are greatly appreciated and I would like to say thank you in advance :) My head is spinning- look forward to learning from the masters!

答:
Your simple clone-based solution works fine, you just left off the pshaw.draw(win) command to add your new rectangle to the window:

```<code>from graphics import *

win = GraphWin()

shape = Rectangle(Point(50, 50), Point(70, 70))
shape.setOutline("red")
shape.setFill("red")
shape.draw(win)

for _ in range(10):
    p = win.getMouse()
    c = shape.getCenter()
    dx = p.getX() - c.getX()
    dy = p.getY() - c.getY()
    pshaw = shape.clone()
    pshaw.move(dx, dy)
    pshaw.draw(win)

win.getMouse()
win.close()
</code>```

Body:
The question is to modify the program below so that each successive click will draw an additional square on the screen.

Here is the program to be modified.

   def main():
win = GraphWin()
shape = Rectangle(Point(50,50), Point(70,70))
shape.setOutline("red")
shape.setFill("red")
shape.draw(win)
for i in range(10):
    p = win.getMouse()
    c = shape.getCenter()
    dx = p.getX() - c.getX()
    dy = p.getY() - c.getY()
    shape.move(dx,dy)
win.close()

To solve this, I have employed the clone() function. Here is my solution:

 def main():
win = GraphWin()
shape = Rectangle(Point(50,50), Point(70,70))
shape.setOutline("red")
shape.setFill("red")
shape.draw(win)
for i in range(10):
    p = win.getMouse()
    c = shape.getCenter()
    dx = p.getX() - c.getX()
    dy = p.getY() - c.getY()
    pshaw = shape.clone()
    pshaw.move(dx, dy)
win.close()

However, the program does not work. Other solutions I have seen involve creating a new shape altogether as show below: Why can I not use clone()?

    def main():
win = GraphWin()
shape = Rectangle(Point(75,75),Point(125,125))
shape.setOutline('Red')
shape.setFill('Red')
shape.draw(win)

for i in range(5):
    p = win.getMouse()
    tx = p.getX()-25
    ty = p.getY()-25
    bx = p.getX()+25
    by = p.getY()+25

    shape2 = Rectangle(Point(tx,ty),Point(bx,by))
    shape2.setOutline('Red')
    shape2.setFill('Red')
    shape2.draw(win)

ct = Text(Point(100,180),'Click again to quit!')
ct.setStyle('bold')
ct.draw(win)
win.getMouse()
win.close()

main()

Why does clone() not work here? Is this not the purpose it was created for? The proposed solution with its creating of a new shape from scratch seems redundant to me.

Any attempts to help are greatly appreciated and I would like to say thank you in advance :) My head is spinning- look forward to learning from the masters!

Body:
Your simple clone-based solution works fine, you just left off the pshaw.draw(win) command to add your new rectangle to the window:

from graphics import *

win = GraphWin()

shape = Rectangle(Point(50, 50), Point(70, 70))
shape.setOutline("red")
shape.setFill("red")
shape.draw(win)

for _ in range(10):
    p = win.getMouse()
    c = shape.getCenter()
    dx = p.getX() - c.getX()
    dy = p.getY() - c.getY()
    pshaw = shape.clone()
    pshaw.move(dx, dy)
    pshaw.draw(win)

win.getMouse()
win.close()


答:
You are using default ArrayAdapter with simple_dropdown_item_1line this layout.
It has single Textview with android:singleLine="true"  cause of which data is showing in one line only.

Switch to custom ArrayAdapter and create row layout as per your requirement.

How to create custom array adapter?

Title: How do I adjust the height of a particular listview when the content is more in android?