问:
Switching an active bootstrap tab?
As far as I can see I've followed a w3 example exactly regarding bootstrap tabs (https://www.w3schools.com/bootstrap/bootstrap_tabs_pills.asp). However with my following code, the tabs don't change when clicked. The only tab displayed is the active tab. I'm not hugely familiar with bootstrap so I imagine the solution may probably be simple.

HTML:

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Login</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="css/login.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <script src="js/login.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</head>

<body>
  <div class="container">
    <!-- <div id="tabs" class="container"> -->
      <ul class="nav nav-tabs">
        <li class="active">
          <a data-toggle="tab" href="#student">Student</a>
        </li>

        <li>
          <a data-toggle="tab" href="#employee">Employee</a>
        </li>

        <li>
          <a data-toggle="tab" href="#admin">Admin</a>
        </li>
      </ul>

      <div class="tab-content">
        <div id="student" class="tab-pane fade in active">
          <h1>TEST</h1>
        </div>
        <div id="employee" class="tab-pane fade">
          <h1>TEST2</h1>
        </div>
        <div id="admin" class="tab-pane fade">
          <h1>TEST3</h1>
        </div>
      </div>

    <!-- </div> -->
  </div>

</body>
</html>
</code>```

答:
The example from W3 is not working either! Try this

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <title>Login</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/login.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <script src="js/login.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    </head>

    <body>
        <div class="container">
            <!-- Nav tabs -->
            <ul class="nav nav-tabs" role="tablist">
                <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>
                <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>
                <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>
                <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>
            </ul>

            <!-- Tab panes -->
            <div class="tab-content">
                <div role="tabpanel" class="tab-pane active" id="home">
                    TEST 1
                </div>
                <div role="tabpanel" class="tab-pane" id="profile">
                    TEST 2
                </div>
                <div role="tabpanel" class="tab-pane" id="messages">
                    TEST 3
                </div>
                <div role="tabpanel" class="tab-pane" id="settings">
                    TEST 4
                </div>
            </div>

        </div>
    </body>
</html>
</code>```

And check: https://getbootstrap.com/docs/3.3/javascript/#tabs for more information

EDIT

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</code>```

This line must go before bootstrap.min.js, like this:

```<code><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</code>```

Title: Switching an active bootstrap tab?

Body:
As far as I can see I've followed a w3 example exactly regarding bootstrap tabs (https://www.w3schools.com/bootstrap/bootstrap_tabs_pills.asp). However with my following code, the tabs don't change when clicked. The only tab displayed is the active tab. I'm not hugely familiar with bootstrap so I imagine the solution may probably be simple.

HTML:

<!DOCTYPE html>

  <title>Login</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="css/login.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

          Student

          Employee

          Admin

TEST

TEST2

TEST3

Body:
The example from W3 is not working either! Try this

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Login</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/login.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <script src="js/login.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    </head>

    <body>
        <div class="container">
            <!-- Nav tabs -->
            <ul class="nav nav-tabs" role="tablist">
                <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>
                <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>
                <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>
                <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>
            </ul>

            <!-- Tab panes -->
            <div class="tab-content">
                <div role="tabpanel" class="tab-pane active" id="home">
                    TEST 1
                </div>
                <div role="tabpanel" class="tab-pane" id="profile">
                    TEST 2
                </div>
                <div role="tabpanel" class="tab-pane" id="messages">
                    TEST 3
                </div>
                <div role="tabpanel" class="tab-pane" id="settings">
                    TEST 4
                </div>
            </div>

        </div>
    </body>
</html>

And check: https://getbootstrap.com/docs/3.3/javascript/#tabs for more information

EDIT

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

This line must go before bootstrap.min.js, like this:

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


来源: stackexchange

问:
AppWidgetProvider with Android Architecture Component
I want to implement Android Architecture Component with AppWidgetProvider.

I'm not sure to map properly Widget LifeCycle to LifeCycle events.

I created a BaseAppWidgetProvider to be extented by my widgets:

```<code>/**
 * Base class for {@link BaseAppWidgetProvider} to manage {@link Lifecycle}
 */

public abstract class BaseAppWidgetProvider extends AppWidgetProvider implements LifecycleOwner {
    private final AppWidgetProviderLifecycleDispatcher mDispatcher = new AppWidgetProviderLifecycleDispatcher(this);

    public BaseAppWidgetProvider(){
        mDispatcher.onConstructor();
    }

    @CallSuper
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        mDispatcher.onUpdate();
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    @CallSuper
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        mDispatcher.onDeleted();
        super.onDeleted(context, appWidgetIds);
    }

    @CallSuper
    @Override
    public void onEnabled(Context context) {
        mDispatcher.onEnabled();
        super.onEnabled(context);
    }

    @CallSuper
    @Override
    public void onDisabled(Context context) {
        mDispatcher.onDisabled();
        super.onDisabled(context);
    }

    @CallSuper
    @Override
    public void onRestored(Context context, int[] oldWidgetIds, int[] newWidgetIds) {
        mDispatcher.onRestored();
        super.onRestored(context, oldWidgetIds, newWidgetIds);
    }

    @CallSuper
    @Override
    public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
        mDispatcher.onAppWidgetOptionsChanged();
        super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mDispatcher.getLifecycle();
    }
}
</code>```

And the dispatcher

```<code>public class AppWidgetProviderLifecycleDispatcher {
    private final LifecycleRegistry mRegistry;
    private final Handler mHandler;
    private DispatchRunnable mLastDispatchRunnable;

    /**
     * @param provider {@link LifecycleOwner} for a service, usually it is a service itself
     */
    public AppWidgetProviderLifecycleDispatcher(@NonNull LifecycleOwner provider) {
        mRegistry = new LifecycleRegistry(provider);
        mHandler = new Handler();
    }
    private void postDispatchRunnable(Lifecycle.Event event) {
        Timber.d("postDispatchRunnable event="+event);
        if (mLastDispatchRunnable != null) {
            mLastDispatchRunnable.run();
        }
        mLastDispatchRunnable = new DispatchRunnable(mRegistry, event);
        mHandler.postAtFrontOfQueue(mLastDispatchRunnable);
    }

    /**
     * Must be a first call in {@link android.appwidget.AppWidgetProvider#AppWidgetProvider()} constructor, even before super call.
     */
    public void onConstructor(){
        postDispatchRunnable(Lifecycle.Event.ON_CREATE);
        postDispatchRunnable(Lifecycle.Event.ON_START);
    }

    /**
     * Must be a first call in {@link android.appwidget.AppWidgetProvider#onDeleted(Context, int[])} method, even before super.onDeleted call.
     */
    public void onDeleted(){
        postDispatchRunnable(Lifecycle.Event.ON_PAUSE);
        postDispatchRunnable(Lifecycle.Event.ON_STOP);
        postDispatchRunnable(Lifecycle.Event.ON_DESTROY);
    }

    /**
     * Must be a first call in {@link android.appwidget.AppWidgetProvider#onDisabled(Context)} method, even before super.onDisabled call.
     */
    public void onDisabled(){
        postDispatchRunnable(Lifecycle.Event.ON_PAUSE);
        postDispatchRunnable(Lifecycle.Event.ON_STOP);
        postDispatchRunnable(Lifecycle.Event.ON_DESTROY);
    }

    /**
     * Must be a first call in {@link android.appwidget.AppWidgetProvider#onEnabled(Context)} method, even before super.onEnabled call.
     */
    public void onEnabled(){
        postDispatchRunnable(Lifecycle.Event.ON_CREATE);
        postDispatchRunnable(Lifecycle.Event.ON_START);
    }

    /**
     * Must be a first call in {@link android.appwidget.AppWidgetProvider#onRestored(Context, int[], int[])} method, even before super.onRestored call.
     */
    public void onRestored(){
        postDispatchRunnable(Lifecycle.Event.ON_CREATE);
        postDispatchRunnable(Lifecycle.Event.ON_START);
    }

    /**
     * Must be a first call in {@link android.appwidget.AppWidgetProvider#onUpdate(Context, AppWidgetManager, int[])} method, even before super.onUpdate call.
     */
    public void onUpdate(){
        postDispatchRunnable(Lifecycle.Event.ON_RESUME);
    }

    /**
     * @return {@link Lifecycle} for the given {@link LifecycleOwner}
     */
    public Lifecycle getLifecycle() {
        return mRegistry;
    }

    public void onAppWidgetOptionsChanged() {
        postDispatchRunnable(Lifecycle.Event.ON_RESUME);
    }

    static class DispatchRunnable implements Runnable {
        private final LifecycleRegistry mRegistry;
        final Lifecycle.Event mEvent;
        private boolean mWasExecuted = false;
        DispatchRunnable(@NonNull LifecycleRegistry registry, Lifecycle.Event event) {
            mRegistry = registry;
            mEvent = event;
        }
        @Override
        public void run() {
            if (!mWasExecuted) {
                mRegistry.handleLifecycleEvent(mEvent);
                mWasExecuted = true;
            }
        }
    }

}
</code>```

答: An AppWidgetProvider is a BroadcastReceiver. It does not have a lifecycle. An instance of your AppWidgetProvider lives for exactly one callback method (e.g., onUpdate()). Hence, there is no mapping to Lifecycle events, just as there is no mapping of Lifecycle events to an ordinary BrodadcastReceiver.

ContentLicense: CC BY-SA 3.0

Body:
I want to implement Android Architecture Component with AppWidgetProvider.

I'm not sure to map properly Widget LifeCycle to LifeCycle events.

I created a BaseAppWidgetProvider to be extented by my widgets:

/**
 * Base class for {@link BaseAppWidgetProvider} to manage {@link Lifecycle}
 */

public abstract class BaseAppWidgetProvider extends AppWidgetProvider implements LifecycleOwner {
    private final AppWidgetProviderLifecycleDispatcher mDispatcher = new AppWidgetProviderLifecycleDispatcher(this);

    public BaseAppWidgetProvider(){
        mDispatcher.onConstructor();
    }

    @CallSuper
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        mDispatcher.onUpdate();
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    @CallSuper
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        mDispatcher.onDeleted();
        super.onDeleted(context, appWidgetIds);
    }

    @CallSuper
    @Override
    public void onEnabled(Context context) {
        mDispatcher.onEnabled();
        super.onEnabled(context);
    }

    @CallSuper
    @Override
    public void onDisabled(Context context) {
        mDispatcher.onDisabled();
        super.onDisabled(context);
    }

    @CallSuper
    @Override
    public void onRestored(Context context, int[] oldWidgetIds, int[] newWidgetIds) {
        mDispatcher.onRestored();
        super.onRestored(context, oldWidgetIds, newWidgetIds);
    }

    @CallSuper
    @Override
    public void onAppWidgetOptionsChanged(Context context, AppWidgetManager appWidgetManager, int appWidgetId, Bundle newOptions) {
        mDispatcher.onAppWidgetOptionsChanged();
        super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions);
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mDispatcher.getLifecycle();
    }
}

And the dispatcher

public class AppWidgetProviderLifecycleDispatcher {
    private final LifecycleRegistry mRegistry;
    private final Handler mHandler;
    private DispatchRunnable mLastDispatchRunnable;

    /**
     * @param provider {@link LifecycleOwner} for a service, usually it is a service itself
     */
    public AppWidgetProviderLifecycleDispatcher(@NonNull LifecycleOwner provider) {
        mRegistry = new LifecycleRegistry(provider);
        mHandler = new Handler();
    }
    private void postDispatchRunnable(Lifecycle.Event event) {
        Timber.d("postDispatchRunnable event="+event);
        if (mLastDispatchRunnable != null) {
            mLastDispatchRunnable.run();
        }
        mLastDispatchRunnable = new DispatchRunnable(mRegistry, event);
        mHandler.postAtFrontOfQueue(mLastDispatchRunnable);
    }

    /**
     * Must be a first call in {@link android.appwidget.AppWidgetProvider#AppWidgetProvider()} constructor, even before super call.
     */
    public void onConstructor(){
        postDispatchRunnable(Lifecycle.Event.ON_CREATE);
        postDispatchRunnable(Lifecycle.Event.ON_START);
    }

    /**
     * Must be a first call in {@link android.appwidget.AppWidgetProvider#onDeleted(Context, int[])} method, even before super.onDeleted call.
     */
    public void onDeleted(){
        postDispatchRunnable(Lifecycle.Event.ON_PAUSE);
        postDispatchRunnable(Lifecycle.Event.ON_STOP);
        postDispatchRunnable(Lifecycle.Event.ON_DESTROY);
    }

    /**
     * Must be a first call in {@link android.appwidget.AppWidgetProvider#onDisabled(Context)} method, even before super.onDisabled call.
     */
    public void onDisabled(){
        postDispatchRunnable(Lifecycle.Event.ON_PAUSE);
        postDispatchRunnable(Lifecycle.Event.ON_STOP);
        postDispatchRunnable(Lifecycle.Event.ON_DESTROY);
    }

    /**
     * Must be a first call in {@link android.appwidget.AppWidgetProvider#onEnabled(Context)} method, even before super.onEnabled call.
     */
    public void onEnabled(){
        postDispatchRunnable(Lifecycle.Event.ON_CREATE);
        postDispatchRunnable(Lifecycle.Event.ON_START);
    }

    /**
     * Must be a first call in {@link android.appwidget.AppWidgetProvider#onRestored(Context, int[], int[])} method, even before super.onRestored call.
     */
    public void onRestored(){
        postDispatchRunnable(Lifecycle.Event.ON_CREATE);
        postDispatchRunnable(Lifecycle.Event.ON_START);
    }

    /**
     * Must be a first call in {@link android.appwidget.AppWidgetProvider#onUpdate(Context, AppWidgetManager, int[])} method, even before super.onUpdate call.
     */
    public void onUpdate(){
        postDispatchRunnable(Lifecycle.Event.ON_RESUME);
    }

    /**
     * @return {@link Lifecycle} for the given {@link LifecycleOwner}
     */
    public Lifecycle getLifecycle() {
        return mRegistry;
    }

    public void onAppWidgetOptionsChanged() {
        postDispatchRunnable(Lifecycle.Event.ON_RESUME);
    }

    static class DispatchRunnable implements Runnable {
        private final LifecycleRegistry mRegistry;
        final Lifecycle.Event mEvent;
        private boolean mWasExecuted = false;
        DispatchRunnable(@NonNull LifecycleRegistry registry, Lifecycle.Event event) {
            mRegistry = registry;
            mEvent = event;
        }
        @Override
        public void run() {
            if (!mWasExecuted) {
                mRegistry.handleLifecycleEvent(mEvent);
                mWasExecuted = true;
            }
        }
    }

}


问:
Python: Create text file, write to it, replace string
I am creating a file, writing to it, then I want to replace a string. I have everything working, except the replace. I have tried re.sub, str.replace, etc. I can't figure it out.

```<code>target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file, "w+")
file.write(target_string)
target_string = re.sub('4', '55', target_string)

Desired Output: foo55bar5555foobar555555foobar, foo55bar
</code>```

Thanks.

答:
Try this, before writing the target string do the replacement and close the file:    </p>

```<code>target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file,"w")
target_string= re.sub('4', '55', target_string)
file.write(target_string)
file.close()

OR

target_string = 'foo4bar44foobar444foobar, foo4bar'
with open(source_file,"w") as f:
  target_string = re.sub('4', '55', target_string)
  f.write(target_string)
</code>```

Body:
I am creating a file, writing to it, then I want to replace a string. I have everything working, except the replace. I have tried re.sub, str.replace, etc. I can't figure it out.

target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file, "w+")
file.write(target_string)
target_string = re.sub('4', '55', target_string)

Desired Output: foo55bar5555foobar555555foobar, foo55bar

Thanks.

Body:
Try this, before writing the target string do the replacement and close the file:

target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file,"w")
target_string= re.sub('4', '55', target_string)
file.write(target_string)
file.close()

OR

target_string = 'foo4bar44foobar444foobar, foo4bar'
with open(source_file,"w") as f:
  target_string = re.sub('4', '55', target_string)
  f.write(target_string)


问:
Firebase onTokenRefresh() is not called
In my MainActivityin my log, I can see the token using FirebaseInstanceId.getInstance().getToken() and it display the generated token.  But it seems like in my  MyFirebaseInstanceIDService where it is extends to FirebaseInstanceIdService, the onTokenRefresh() is not called, where in this function it was said that the token is initially generated here. I needed to call sendRegistrationToServer() that's why I'm trying to know why it doesn't go in the onTokenRefresh().

Here is my code

```<code>public class MyFirebaseInstanceIDService  extends FirebaseInstanceIdService {

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

        sendRegistrationToServer(refreshedToken);
    }
}
</code>```

答: Reinstalling did the trick for me!</p>

Title: Firebase onTokenRefresh() is not called

Body:
In my MainActivityin my log, I can see the token using FirebaseInstanceId.getInstance().getToken() and it display the generated token.  But it seems like in my  MyFirebaseInstanceIDService where it is extends to FirebaseInstanceIdService, the onTokenRefresh() is not called, where in this function it was said that the token is initially generated here. I needed to call sendRegistrationToServer() that's why I'm trying to know why it doesn't go in the onTokenRefresh().

Here is my code

public class MyFirebaseInstanceIDService  extends FirebaseInstanceIdService {

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

        sendRegistrationToServer(refreshedToken);
    }
}

Body: Reinstalling did the trick for me!


问:
SharePoint send email with javascript on add list item
I like to send an email to the administrator when a user adds a item to my List. I already changed the NewForm for the list and execute the add item with:

```<code>SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems);
</code>```

Now in my SharePoint the email notification on Lists has been disabled by the company. So I'd like some code to send an email automatically after the user added an item.
I already have the username of the person who added the item.

```<code>var loginName = "";
var userid = _spPageContextInfo.userId;
GetCurrentUser();

function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
</code>```

The email has to be send to an address of the companies outlook server. An SMTP can be used.

Marco

答: It seems that it was still possible to set an alert on a list when an item was added. So that solved my problem.</p>

Body:
I like to send an email to the administrator when a user adds a item to my List. I already changed the NewForm for the list and execute the add item with:

SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems);

Now in my SharePoint the email notification on Lists has been disabled by the company. So I'd like some code to send an email automatically after the user added an item.
I already have the username of the person who added the item.

var loginName = "";
var userid = _spPageContextInfo.userId;
GetCurrentUser();

function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";

The email has to be send to an address of the companies outlook server. An SMTP can be used.

Marco


问:
Rails tutorial chapter 7 sign up form error doesn't appear right
Working on a failed signup form with error and it currently appears visually off as in the image below:

There is a red box around the errors part which shouldn't be there and there is asterisks next to each list error which shouldn't be there and there is no error for password confirmation for some reason. Also all the input fields have shrunk and are overly highlighted red.

(please note for fun I changed the user resource to a dog resource)

Here is my Custom css.scss

```<code>@import "bootstrap";

/* mixins, variables, etc. */

$grayMediumLight: #eaeaea;

@mixin box_sizing {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

/* universal */

html {
  overflow-y: scroll;
}

body {
  padding-top: 60px;
}

section {
  overflow: auto;
}

textarea {
  resize: vertical;
}

.center {
  text-align: center;
  h1 {
    margin-bottom: 10px;
  }
}

/* typography */

h1, h2, h3, h4, h5, h6 {
  line-height: 1;
}

h1 {
  font-size: 3em;
  letter-spacing: -2px;
  margin-bottom: 30px;
  text-align: center;
}

h2 {
  font-size: 1.2em;
  letter-spacing: -1px;
  margin-bottom: 30px;
  text-align: center;
  font-weight: normal;
  color: $grayLight;
}

p {
  font-size: 1.1em;
  line-height: 1.7em;
}

/* header */

#logo {
  float: left;
  margin-right: 10px;
  font-size: 1.7em;
  color: white;
  text-transform: uppercase;
  letter-spacing: -1px;
  padding-top: 9px;
  font-weight: bold;
  line-height: 1;
  &:hover {
    color: white;
    text-decoration: none;
  }
}
/* footer */

footer {
  margin-top: 45px;
  padding-top: 5px;
  border-top: 1px solid $grayMediumLight;
  color: $grayLight;
  a {
    color: $gray;
    &:hover {
      color: $grayDarker;
    }
  }
  small {
    float: left;
  }
  ul {
    float: right;
    list-style: none;
    li {
      float: left;
      margin-left: 10px;
    }
  }
}

/* sidebar */

aside {
  section {
    padding: 10px 0;
    border-top: 1px solid $grayLighter;
    &:first-child {
      border: 0;
      padding-top: 0;
    }
    span {
      display: block;
      margin-bottom: 3px;
      line-height: 1;
    }
   h1 {
      font-size: 1.4em;
      text-align: left;
      letter-spacing: -1px;
      margin-bottom: 3px;
      margin-top: 0px;
    }
  }
}

.gravatar {
  float: left;
  margin-right: 10px;
}

/* miscellaneous */

.debug_dump {
  clear: both;
  float: left;
  width: 100%;
  margin-top: 45px;
  @include box_sizing;
}

/* forms */

input, textarea, select, .uneditable-input {
  border: 1px solid #bbb;
  width: 100%;
  margin-bottom: 15px;
  @include box_sizing;
}

input {
  height: auto !important;
}

#error_explanation {
  color: #f00;
  ul {
    list-style: none;
    margin: 0 0 18px 0;
  }
}

.field_with_errors {
  @extend .control-group;
  @extend .error;
}
</code>```

Here is the new.html.erb

```<code><% provide(:title, 'Sign up') %>
<h1>Sign up</h1>

<div class="row">
<div class="span6 offset3">
    <%= form_for(@dog) do |f| %>
        <%= render 'shared/error_messages' %>

        <%= f.label :name %>
        <%= f.text_field :name %>

        <%= f.label :email %>
        <%= f.text_field :email %>

        <%= f.label :password %>
        <%= f.password_field :password %>

        <%= f.label :password_confirmation, "Password Confirmation" %>
        <%= f.password_field :password_confirmation %>

        <%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
    <% end %>
</div>
</code>```

and lastely the shared/_error_messages.html.erb

```<code><% if @dog.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-error">
      The form contains <%= pluralize(@dog.errors.count, "error") %>.
    </div>
    <ul>
      <% @dog.errors.full_messages.each do |msg| %>
        <li>* <%= msg %></li>
      <% end %>
    </ul>
  </div>
<% end %>
</code>```

Ah and my DogsController incase that helps (interesting note the create action has a render 'new' but if I click on the submit button with invalid information it is redirected to the index url (/dogs) but still has the form with error?? It appears like that also on the tutorial but just found that interesting as a side note.)

```<code>class DogsController < ApplicationController
  def new
@dog = Dog.new
  end

  def show
@dog = Dog.find(params[:id])
  end

  def create
@dog = Dog.new(dog_params)
if @dog.save
    redirect_to @dog
else
    render 'new'
end
 end

private

  def dog_params
    params.require(:dog).permit(:name, :email, :password,
                               :password_confirmation)
  end
end
</code>```

Any help is appreciated thanks!

答:
The problems is : in scaffolds.scss there are

```<code>#error_explanation {
  width: 450px;
  border: 2px solid red;
  padding: 7px 7px 0;
  margin-bottom: 20px;
  background-color: #f0f0f0;

  h2 {
    text-align: left;
    font-weight: bold;
    padding: 5px 5px 5px 15px;
    font-size: 12px;
    margin: -7px -7px 0;
    background-color: #c00;
    color: #fff;
  }

  ul li {
    font-size: 12px;
    list-style: square;
  }
}
</code>```

delete them and your css work . But I suggest change id="error_explanation"
to id="error_explanation_signup" (_error_messages.html.erb) for keeping original css.

Body:
Working on a failed signup form with error and it currently appears visually off as in the image below:

There is a red box around the errors part which shouldn't be there and there is asterisks next to each list error which shouldn't be there and there is no error for password confirmation for some reason. Also all the input fields have shrunk and are overly highlighted red.

(please note for fun I changed the user resource to a dog resource)

Here is my Custom css.scss

@import "bootstrap";

/* mixins, variables, etc. */

$grayMediumLight: #eaeaea;

@mixin box_sizing {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

/* universal */

html {
  overflow-y: scroll;
}

body {
  padding-top: 60px;
}

section {
  overflow: auto;
}

textarea {
  resize: vertical;
}

.center {
  text-align: center;
  h1 {
    margin-bottom: 10px;
  }
}

/* typography */

h1, h2, h3, h4, h5, h6 {
  line-height: 1;
}

h1 {
  font-size: 3em;
  letter-spacing: -2px;
  margin-bottom: 30px;
  text-align: center;
}

h2 {
  font-size: 1.2em;
  letter-spacing: -1px;
  margin-bottom: 30px;
  text-align: center;
  font-weight: normal;
  color: $grayLight;
}

p {
  font-size: 1.1em;
  line-height: 1.7em;
}

/* header */

#logo {
  float: left;
  margin-right: 10px;
  font-size: 1.7em;
  color: white;
  text-transform: uppercase;
  letter-spacing: -1px;
  padding-top: 9px;
  font-weight: bold;
  line-height: 1;
  &:hover {
    color: white;
    text-decoration: none;
  }
}
/* footer */

footer {
  margin-top: 45px;
  padding-top: 5px;
  border-top: 1px solid $grayMediumLight;
  color: $grayLight;
  a {
    color: $gray;
    &:hover {
      color: $grayDarker;
    }
  }
  small {
    float: left;
  }
  ul {
    float: right;
    list-style: none;
    li {
      float: left;
      margin-left: 10px;
    }
  }
}

/* sidebar */

aside {
  section {
    padding: 10px 0;
    border-top: 1px solid $grayLighter;
    &:first-child {
      border: 0;
      padding-top: 0;
    }
    span {
      display: block;
      margin-bottom: 3px;
      line-height: 1;
    }
   h1 {
      font-size: 1.4em;
      text-align: left;
      letter-spacing: -1px;
      margin-bottom: 3px;
      margin-top: 0px;
    }
  }
}

.gravatar {
  float: left;
  margin-right: 10px;
}

/* miscellaneous */

.debug_dump {
  clear: both;
  float: left;
  width: 100%;
  margin-top: 45px;
  @include box_sizing;
}

/* forms */

input, textarea, select, .uneditable-input {
  border: 1px solid #bbb;
  width: 100%;
  margin-bottom: 15px;
  @include box_sizing;
}

input {
  height: auto !important;
}

#error_explanation {
  color: #f00;
  ul {
    list-style: none;
    margin: 0 0 18px 0;
  }
}

.field_with_errors {
  @extend .control-group;
  @extend .error;
}

Here is the new.html.erb

<% provide(:title, 'Sign up') %>

Sign up

    <%= form_for(@dog) do |f| %>
        <%= render 'shared/error_messages' %>

        <%= f.label :name %>
        <%= f.text_field :name %>

        <%= f.label :email %>
        <%= f.text_field :email %>

        <%= f.label :password %>
        <%= f.password_field :password %>

        <%= f.label :password_confirmation, "Password Confirmation" %>
        <%= f.password_field :password_confirmation %>

        <%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
    <% end %>

and lastely the shared/_error_messages.html.erb

<% if @dog.errors.any? %>

      The form contains <%= pluralize(@dog.errors.count, "error") %>.

      <% @dog.errors.full_messages.each do |msg| %>

* <%= msg %>

      <% end %>

<% end %>

Ah and my DogsController incase that helps (interesting note the create action has a render 'new' but if I click on the submit button with invalid information it is redirected to the index url (/dogs) but still has the form with error?? It appears like that also on the tutorial but just found that interesting as a side note.)

class DogsController < ApplicationController
  def new
@dog = Dog.new
  end

  def show
@dog = Dog.find(params[:id])
  end

  def create
@dog = Dog.new(dog_params)
if @dog.save
    redirect_to @dog
else
    render 'new'
end
 end

private

  def dog_params
    params.require(:dog).permit(:name, :email, :password,
                               :password_confirmation)
  end
end

Any help is appreciated thanks!

Body:
The problems is : in scaffolds.scss there are

#error_explanation {
  width: 450px;
  border: 2px solid red;
  padding: 7px 7px 0;
  margin-bottom: 20px;
  background-color: #f0f0f0;

  h2 {
    text-align: left;
    font-weight: bold;
    padding: 5px 5px 5px 15px;
    font-size: 12px;
    margin: -7px -7px 0;
    background-color: #c00;
    color: #fff;
  }

  ul li {
    font-size: 12px;
    list-style: square;
  }
}

delete them and your css work . But I suggest change id="error_explanation"
to id="error_explanation_signup" (_error_messages.html.erb) for keeping original css.


问:
How to ignore warnings and errors of a postbuild event?
I have a postbuild event in my csproj. I want to ignore the output from this command, but whenever I do command >nul 2>&1 this csproj goes corrupt, probably because of the ">". I noticed when I write ">" from the postbuild window instead of editing the csproj directly if gets encoded.. Is there a workaround (other than running it from a bat file)</p>

答:
This can be done using MSBuild's <Exec> task from a custom target instead of relying on the default pre/post build script properties.

You can add this to your csproj file instead of using the default pre/post build scripts:

```<code><Target Name="PostBuild" AfterTargets="PostBuildEvent">
  <Exec Command="some command" IgnoreExitCode="true" />
</Target>
</code>```

Note that for "sdk-based" projects (ASP.NET Core, .NET Core, .NET Standard) the above format is what is added when specifying a post build event in the Visual Studio UI already with the exception of the IgnoreExitCode attribute.

Body:
This can be done using MSBuild's <Exec> task from a custom target instead of relying on the default pre/post build script properties.

You can add this to your csproj file instead of using the default pre/post build scripts:

<Target Name="PostBuild" AfterTargets="PostBuildEvent">
  <Exec Command="some command" IgnoreExitCode="true" />
</Target>

Note that for "sdk-based" projects (ASP.NET Core, .NET Core, .NET Standard) the above format is what is added when specifying a post build event in the Visual Studio UI already with the exception of the IgnoreExitCode attribute.


问:
Is using a case statement in my ruby on rails example ok?
I have a built a little online tool using rails. The app has no database.
(I know I should have used another simpler framework, like Sinatra for Ruby).
So I need to capture selected car model from the interface and use its power, speed, and dimensions properties
Is it ok to use case statement, like the code below:

```<code>class Car
def get_car_properties (dropdown_selection)
    info = {}
    info=Hash.new{2}
    case dropdown_selection
        when 'Mazda 3'
             info = { speed: 'fast', power: 'real strong', dimensions: '4X3X3'}
        when 'Lancer 81'
             info = { speed: 'slow', power: 'real weak', dimensions: '2X2X2'}
         else
             info={}

    end
    return info
end
end

selected_car=Car.new()
puts selected_car.get_car_properties('Mazda 3')
</code>```

For simplifications, I have not used the exact scenario. Also note that my case statement is about 30 options big and the hash 10 symbols.

答:
The code you're written probably works, but definitely smells and would violate the ruby style guide.

I suggest you utilize a code analyzer, such as rubocop which will enforce the ruby style guide, and help you write conforming code and avoid common pitfalls.

Body:
I have a built a little online tool using rails. The app has no database.
(I know I should have used another simpler framework, like Sinatra for Ruby).
So I need to capture selected car model from the interface and use its power, speed, and dimensions properties
Is it ok to use case statement, like the code below:

class Car
def get_car_properties (dropdown_selection)
    info = {}
    info=Hash.new{2}
    case dropdown_selection
        when 'Mazda 3'
             info = { speed: 'fast', power: 'real strong', dimensions: '4X3X3'}
        when 'Lancer 81'
             info = { speed: 'slow', power: 'real weak', dimensions: '2X2X2'}
         else
             info={}

    end
    return info
end
end

selected_car=Car.new()
puts selected_car.get_car_properties('Mazda 3')

For simplifications, I have not used the exact scenario. Also note that my case statement is about 30 options big and the hash 10 symbols.


问:
How to loop through an array of arrays using jQuery or JavaScript?
I have a json array like this

```<code>var data = key: [
    {
        arr1: [
            {value: 1},
            {value: 2},
            {value: 3},
        ]
    },
    {
        arr2: [
            {value: 1},
            {value: 2},
            {value: 3},
        ]
    },
    {
        arr3: [
            {value: 1},
            {value: 2},
            {value: 3},
        ]
    }
]
</code>```

I wanted to loop through key which is 3 times, and inside the key loop I wanted loop again through each of the elements inside key.

First I tried $.each which works fine for key array. And inside the each function I tried to get the key values using Object.key(this) inside the loop which returned me the names

```<code>arr1, arr2, arr3
</code>```

But I'm not able to loop through the names I got.

```<code>$.each(data, function(i, e) {
    Object.keys(this).each(function(index, element) {
        console.log(element);
    })
})
</code>```

I don't know if this is the right way of doing it, when I tried doing it this was. I got an error telling .each is not a function.

Any help will be much appreciated.

答:
I believe the reason your attempt is not working is because you are trying to .each the individual values themselves, rather than the arrays within data.

This should work:

```<code>$.each(data, function(index, array) { // This each iterates over the arrays.
  $.each(array, function(subindex, value) { // This each iterates over the individual values.
    console.log(value); // Logs the individual values.
  });
});
</code>```

Body:
I have a json array like this

var data = key: [
    {
        arr1: [
            {value: 1},
            {value: 2},
            {value: 3},
        ]
    },
    {
        arr2: [
            {value: 1},
            {value: 2},
            {value: 3},
        ]
    },
    {
        arr3: [
            {value: 1},
            {value: 2},
            {value: 3},
        ]
    }
]

I wanted to loop through key which is 3 times, and inside the key loop I wanted loop again through each of the elements inside key.

First I tried $.each which works fine for key array. And inside the each function I tried to get the key values using Object.key(this) inside the loop which returned me the names

arr1, arr2, arr3

But I'm not able to loop through the names I got.

$.each(data, function(i, e) {
    Object.keys(this).each(function(index, element) {
        console.log(element);
    })
})

I don't know if this is the right way of doing it, when I tried doing it this was. I got an error telling .each is not a function.

Any help will be much appreciated.

Body:
I believe the reason your attempt is not working is because you are trying to .each the individual values themselves, rather than the arrays within data.

This should work:

$.each(data, function(index, array) { // This each iterates over the arrays.
  $.each(array, function(subindex, value) { // This each iterates over the individual values.
    console.log(value); // Logs the individual values.
  });
});


问:
Is it possible in MySQL to search a table for where a column only contains 1 comma?
I have this column in a table which is comma delimited to separate the values.

Here's the sample data:

```<code>2003,2004
2003,2005
2003,2006
2003,2004,2005
2003,2007
</code>```

I want to get all data that contains only 1 comma.

I've been playing around with the '%' and '_' wildcards, but I can't seem to get the results I need.

SELECT column FROM table WHERE column like '%_,%'

答:
Replace the , with '' empty set then take the original length less the replaced length. if 1 then only 1 comma if > 1 then more than 1 comma.

The length difference would represent the number of commas.

Length(column) - length(Replace(column,',','')) as NumOfCommas

or

```<code>where Length(column) - length(Replace(column,',','')) =1
</code>```

While this may solve the problem, I agree with what others have indicated.  Storing multiple values in a single column in a RDBMS is asking for more trouble.  Better to normalize the data and get it to at least 3rd Normal form!

Body:
I have this column in a table which is comma delimited to separate the values.

Here's the sample data:

2003,2004
2003,2005
2003,2006
2003,2004,2005
2003,2007

I want to get all data that contains only 1 comma.

I've been playing around with the '%' and '_' wildcards, but I can't seem to get the results I need.

SELECT column FROM table WHERE column like '%_,%'

Body:
Replace the , with '' empty set then take the original length less the replaced length. if 1 then only 1 comma if > 1 then more than 1 comma.

The length difference would represent the number of commas.

Length(column) - length(Replace(column,',','')) as NumOfCommas

or

where Length(column) - length(Replace(column,',','')) =1

While this may solve the problem, I agree with what others have indicated.  Storing multiple values in a single column in a RDBMS is asking for more trouble.  Better to normalize the data and get it to at least 3rd Normal form!


问:
How to get source code of multiple lambdas inside a single line in Python
Now I have a chained function calls which is similar to the Pandas.

```<code>df.id.map(lambda x: x + 1).map(lambda y: y + 2)
</code>```

In map function, I try to get the source code of the lambda.

I use the inspect.getsource, but it just gets the entire line,
how can I get the exact source code of the right lambda function?

答: If you have the possibility to switch from standard lambda syntax to mini_lambda then you get this feature built-in since each lambda expression becomes printable. The same goes for other lambda expression providers such as SymPy</p>

Body:
Now I have a chained function calls which is similar to the Pandas.

df.id.map(lambda x: x + 1).map(lambda y: y + 2)

In map function, I try to get the source code of the lambda.

I use the inspect.getsource, but it just gets the entire line,
how can I get the exact source code of the right lambda function?


问:
Google Play Games Services testing - OAuth failing?
Trying to follow instructions here:
https://developers.google.com/games/services/console/enabling#step_3_generate_an_oauth_20_client_id

There is a long description of how to generate fingerprints, but this never happened for me... it just said

'Successfully linked your Client ID'

XXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXX.apps.googleusercontent.com

'You only need to include the application ID (1098532227899) in your Android app. '

I did that, I'm testing and I can't connect.  Do I have to get it as an alpha release through the store to test?  I'm listed as a tester, but when I send the invitation I get

'App not available for this account'

If I send myself a signed release APK is that the same as getting it through the store?

答:
Based from this blog, there are certain reasons why you encounter the App not available for this account error. It might be:

Country restriction. The developer can specify application availability for each country and if on the Google Play you will see a clear message about that - on this page, it will look like “App not available for this account”. The best thing which you can do in this case is to ask developers to the associated Google+ community to add your country to the list.

Testers limit. The developer can also specify a maximum amount of beta testers which means that if this limit is 1000 testers, you won’t be able to get an access to this page. I will look like “App not available for this account” either. You can try to contact developers in this case too.

Time delay. Sometimes, even if you joined Google+ community you will see “App not available for this account” just because it may take up to 4 hours (according to the google documentation) before an application will become available for your account. In this case, I would suggest checking this OPT-IN url after some time, according to my experience it usually takes less than 15 minutes.

You may check this SO post for reference: Beta testing: App not appearing in Play Store Beta tab


问:
UITableView subclass init setup not working
I am creating a UITableView subclass with Swift, and my values are not sticking.

I create it like this:

```<code>override init(frame: CGRect, style:UITableViewStyle) {
        super.init(frame: frame, style: style)
        setupTableView()
    }

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func setupTableView() {
    self.delegate = self
    self.dataSource = self
    self.bounces = false
    self.separatorStyle = .None
    self.backgroundColor = Color.lightBackground
    self.addSubview(footerImageView)
    let cellNib = UINib(nibName: "MenuTableViewCell", bundle: nil)
    self.registerNib(cellNib, forCellReuseIdentifier: "MenuTableViewCell")
}
</code>```

When the view appears, the separators are still there, and the background is still white (Color.lightBackground is a light gray). I can see the tableView background, because the cells do not fill the screen. My cells do load the correct background color.

The cells do load, so I know my delegate and datasource are working.

Why do my properties not get set?

答:
I've experienced the same issue, and this trick helped:

```<code>override init(frame: CGRect, style: UITableViewStyle) {
    super.init(frame: frame, style: style)
    setup()
}

func setup() {
    DispatchQueue.main.async {
        self.delegate = self
        self.dataSource = self
        self.backgroundColor = .clear
        self.register(SearchResultCell.self,  forCellReuseIdentifier: "SearchResultCell")
        self.separatorStyle = .none
        self.tableFooterView = UIView()
    }
}
</code>```

Honestly, I have no idea why it behaves so. But main.async resolves that.

Okay, I got it. The issue was caused by initializing the UITableView's subclass instance in the containing view controller's initializer.
Making the table view lazy var may also resolve the issue.

Body:
I am creating a UITableView subclass with Swift, and my values are not sticking.

I create it like this:

override init(frame: CGRect, style:UITableViewStyle) {
        super.init(frame: frame, style: style)
        setupTableView()
    }

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func setupTableView() {
    self.delegate = self
    self.dataSource = self
    self.bounces = false
    self.separatorStyle = .None
    self.backgroundColor = Color.lightBackground
    self.addSubview(footerImageView)
    let cellNib = UINib(nibName: "MenuTableViewCell", bundle: nil)
    self.registerNib(cellNib, forCellReuseIdentifier: "MenuTableViewCell")
}

When the view appears, the separators are still there, and the background is still white (Color.lightBackground is a light gray). I can see the tableView background, because the cells do not fill the screen. My cells do load the correct background color.

The cells do load, so I know my delegate and datasource are working.

Why do my properties not get set?

Body:
I've experienced the same issue, and this trick helped:

override init(frame: CGRect, style: UITableViewStyle) {
    super.init(frame: frame, style: style)
    setup()
}

func setup() {
    DispatchQueue.main.async {
        self.delegate = self
        self.dataSource = self
        self.backgroundColor = .clear
        self.register(SearchResultCell.self,  forCellReuseIdentifier: "SearchResultCell")
        self.separatorStyle = .none
        self.tableFooterView = UIView()
    }
}

Honestly, I have no idea why it behaves so. But main.async resolves that.

Okay, I got it. The issue was caused by initializing the UITableView's subclass instance in the containing view controller's initializer.
Making the table view lazy var may also resolve the issue.


问:
matplotlib log axis: display powers of 10 only
I have a log-log plot with range of x-axis from 10^9 to 10^12. (This is my first time posting so I am unable to post an image of my plot)

I would like to change the x and y axes so that only the powers of 10 are displayed. Something like 9, 10, 11, 12 on the x-axis.

I used matplotlib.ticker.LogFormatterExponent(base=10.0, labelOnlyBase=True) but it does not quite do the job. Any suggestions?

答:
LogFormatterExponent(base=10.0, labelOnlyBase=True) works as expected.

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker

x = 10**np.linspace(8.5,12.6)
y = np.sin(x)

fig,ax = plt.subplots()
ax.scatter(x,y)
ax.set_xscale('log')
ax.set_xlabel("Quantity [$10^{x}]$")

logfmt = matplotlib.ticker.LogFormatterExponent(base=10.0, labelOnlyBase=True)
ax.xaxis.set_major_formatter(logfmt)

plt.show()
</code>```

Body:
LogFormatterExponent(base=10.0, labelOnlyBase=True) works as expected.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker

x = 10**np.linspace(8.5,12.6)
y = np.sin(x)

fig,ax = plt.subplots()
ax.scatter(x,y)
ax.set_xscale('log')
ax.set_xlabel("Quantity [$10^{x}]$")

logfmt = matplotlib.ticker.LogFormatterExponent(base=10.0, labelOnlyBase=True)
ax.xaxis.set_major_formatter(logfmt)

plt.show()


问:
SQL Server: CASE WHEN with temp tables syntax errroring out
The logic I'm trying to implement is as follows: Replace certain strings with other strings for a specific column.

Leave string values that do not need to be replaced as their original values.

```<code>   SELECT * INTO #df_ERA4_a_temp
            CASE WHEN [REQMNT] = 'A CHEC' THEN 'A CHECK'
                 WHEN [REQMNT] = 'A-12' THEN 'A12'
                 WHEN [REQMNT] = 'A-9' THEN 'A9'
                 WHEN [REQMNT] = 'ADS-B' THEN 'ADSB'
                 WHEN [REQMNT] = 'ADWK' THEN 'ADWORK'
                 WHEN [REQMNT] = 'ALI-W' THEN 'ALI-WRK'
                 ELSE [REQMNT]
            END
    FROM #df_ERA4_a
</code>```

Error: Msg 156, Level 15, State 1, Line 129
Incorrect syntax near the keyword 'CASE'.

答:
See if that helps</p>

```<code>SELECT
      CASE WHEN [REQMNT] = 'A CHEC' THEN 'A CHECK'
                     WHEN [REQMNT] = 'A-12' THEN 'A12'
                     WHEN [REQMNT] = 'A-9' THEN 'A9'
                     WHEN [REQMNT] = 'ADS-B' THEN 'ADSB'
                     WHEN [REQMNT] = 'ADWK' THEN 'ADWORK'
                     WHEN [REQMNT] = 'ALI-W' THEN 'ALI-WRK'
                     ELSE [REQMNT] END,
     * INTO #df_ERA4_a_temp
        FROM #df_ERA4_a
</code>```

Body:
The logic I'm trying to implement is as follows: Replace certain strings with other strings for a specific column.

Leave string values that do not need to be replaced as their original values.

   SELECT * INTO #df_ERA4_a_temp
            CASE WHEN [REQMNT] = 'A CHEC' THEN 'A CHECK'
                 WHEN [REQMNT] = 'A-12' THEN 'A12'
                 WHEN [REQMNT] = 'A-9' THEN 'A9'
                 WHEN [REQMNT] = 'ADS-B' THEN 'ADSB'
                 WHEN [REQMNT] = 'ADWK' THEN 'ADWORK'
                 WHEN [REQMNT] = 'ALI-W' THEN 'ALI-WRK'
                 ELSE [REQMNT]
            END
    FROM #df_ERA4_a

Error: Msg 156, Level 15, State 1, Line 129
Incorrect syntax near the keyword 'CASE'.

Body:
See if that helps

SELECT
      CASE WHEN [REQMNT] = 'A CHEC' THEN 'A CHECK'
                     WHEN [REQMNT] = 'A-12' THEN 'A12'
                     WHEN [REQMNT] = 'A-9' THEN 'A9'
                     WHEN [REQMNT] = 'ADS-B' THEN 'ADSB'
                     WHEN [REQMNT] = 'ADWK' THEN 'ADWORK'
                     WHEN [REQMNT] = 'ALI-W' THEN 'ALI-WRK'
                     ELSE [REQMNT] END,
     * INTO #df_ERA4_a_temp
        FROM #df_ERA4_a


问:
Access all user drives as Admin
I am building a native application that uses Microsoft Graph.
I want to read all the files in OneDrive of all the users in the organization, via admin account.

I am using the (Azure AD 2.0) OAUTH authorization workflow to get the authorization code. After which I get the access token and refresh token.

However when I try to access the drive of any user :

graphClient.Drives["amit@csys.onmicrosoft.com"].Root.Request().GetAsync();
// where graphClient is instance of GraphServiceClient
```

<p>I get:</p>

<blockquote>
  <p>generalException</p>

  <p>Message: Unexpected exception returned from the service.</p>
</blockquote>

<p>With call stack :</p>

<pre class="lang-cs prettyprint-override"><code>  at Microsoft.Graph.HttpProvider.<SendAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.Graph.BaseRequest.<SendRequestAsync>d__34.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.Graph.BaseRequest.<SendAsync>d__32`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.Graph.DriveItemRequest.<GetAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at OneDrive_Writer.OneDriveWriter.<loadRootDriveFolder>d__9d.MoveNext()
</code>```

Is there a way an admin can access all other users drives files?

NOTE: I am able to access the Admin's OneDrive account when I login as Admin.

答:
The Drives indexer in your example expects a driveId, not a upn.

Assuming that your permissions are properly set, and you have a valid access token,
you'll do something like this.

```<code>// Access the users in the org.
var users = await graphClient.Users.Request().GetAsync();

// Get the drives for a user.
var drives = await graphClient.Users[users[0].Id].Drives.Request().GetAsync();

// Get the specific drive metadata for a user
var drive = await graphClient.Drives[drives[0].Id].Request().GetASync();
</code>```

Title: Access all user drives as Admin

Body:
I am building a native application that uses Microsoft Graph.
I want to read all the files in OneDrive of all the users in the organization, via admin account.

I am using the (Azure AD 2.0) OAUTH authorization workflow to get the authorization code. After which I get the access token and refresh token.

However when I try to access the drive of any user :

graphClient.Drives["amit@csys.onmicrosoft.com"].Root.Request().GetAsync();
// where graphClient is instance of GraphServiceClient

I get:

generalException

Message: Unexpected exception returned from the service.

With call stack :

  at Microsoft.Graph.HttpProvider.<SendAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.Graph.BaseRequest.<SendRequestAsync>d__34.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.Graph.BaseRequest.<SendAsync>d__32`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.Graph.DriveItemRequest.<GetAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at OneDrive_Writer.OneDriveWriter.<loadRootDriveFolder>d__9d.MoveNext()

Is there a way an admin can access all other users drives files?

NOTE: I am able to access the Admin's OneDrive account when I login as Admin.

Body:
The Drives indexer in your example expects a driveId, not a upn.

Assuming that your permissions are properly set, and you have a valid access token,
you'll do something like this.

// Access the users in the org.
var users = await graphClient.Users.Request().GetAsync();

// Get the drives for a user.
var drives = await graphClient.Users[users[0].Id].Drives.Request().GetAsync();

// Get the specific drive metadata for a user
var drive = await graphClient.Drives[drives[0].Id].Request().GetASync();


问:
ngFor printing more than it should
I am getting some data from the database and displaying it with ngFor loop.

HTML:

```<code><div
  style="background:black; color:aliceblue;"
  class="col-md-8 col-md-offset-2 text-center"
  [routerLink]="['todo']">
    <h3
    *ngFor="let todo of todos"
    >{{todo.todoHeadline}}</h3>
</div>
</code>```

TS:

```<code>todos: Todo[];
constructor(private todoService: TodoService) { }

ngOnInit() {
  this.todoService.getTodos()
    .subscribe(
      (todos: Todo[]) => {
        this.todos = todos;
      }
    );
}
</code>```

And the service responsible for getting the data:

```<code>getTodos() {
    return this.http.get('http://localhost:3000/todo')
        .map((response: Response) => {
            const todos = response.json().obj;
            let transformedTodos: Todo[] = [];
            for (let todo of todos) {
                transformedTodos.push(new Todo(
                    todo.todoHeadline,
                    todo.todoDescription
                ));
            }
            this.todos = transformedTodos;
            return transformedTodos;
        })
        .catch((error: Response) => {
            return Observable.throw(error.json());
        });
}
</code>```

So I have 8 todos in the database with properties headline and description. Now ngFor prints 8 times h3 and within h3 it prints 8 times more so it displays todoHeadline 64 times. How can I fix that?

答:
First, I would try to refactor this service to a more functional way:

```<code>getTodos() {
  return this.http.get('http://localhost:3000/todo')
  .map( response => response.json().obj)
  .map( todos => todos.map(todo => new Todo(todo.todoHeadline, todo.todoDescription)));
}
</code>```

this will make your code more easy to read and to figure outwhere the problem is.

Title: ngFor printing more than it should

Body:
I am getting some data from the database and displaying it with ngFor loop.

HTML:

{{todo.todoHeadline}}

TS:

todos: Todo[];
constructor(private todoService: TodoService) { }

ngOnInit() {
  this.todoService.getTodos()
    .subscribe(
      (todos: Todo[]) => {
        this.todos = todos;
      }
    );
}

And the service responsible for getting the data:

getTodos() {
    return this.http.get('http://localhost:3000/todo')
        .map((response: Response) => {
            const todos = response.json().obj;
            let transformedTodos: Todo[] = [];
            for (let todo of todos) {
                transformedTodos.push(new Todo(
                    todo.todoHeadline,
                    todo.todoDescription
                ));
            }
            this.todos = transformedTodos;
            return transformedTodos;
        })
        .catch((error: Response) => {
            return Observable.throw(error.json());
        });
}

So I have 8 todos in the database with properties headline and description. Now ngFor prints 8 times h3 and within h3 it prints 8 times more so it displays todoHeadline 64 times. How can I fix that?

Body:
First, I would try to refactor this service to a more functional way:

getTodos() {
  return this.http.get('http://localhost:3000/todo')
  .map( response => response.json().obj)
  .map( todos => todos.map(todo => new Todo(todo.todoHeadline, todo.todoDescription)));
}

this will make your code more easy to read and to figure outwhere the problem is.


问:
Cannot initialize FFImageLoading, exception thrown
I am trying to use the FFImageLoading in a cross-platform xamarin app.

I followed the instructions, and installed the Xamarin.FFImageLoading and Xamarin.FFImageLoading.Forms in both the android and IOS projects.

I then use this code to intitialize the library:

```<code>[Activity (Label = "app", Icon = "@drawable/icon", Theme="@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    protected override void OnCreate (Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate (bundle);

        CachedImageRenderer.Init();

        global::Xamarin.Forms.Forms.Init (this, bundle);
        global::Xamarin.Auth.Presenters.XamarinAndroid.AuthenticationConfiguration.Init(this, bundle);

        LoadApplication (new TheWillowEffect.App ());

    }
}
</code>```

I haven't tried in it IOS yet. Not a priority.

I have the following XAML just to see if it works:

```<code><ContentPage
....xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"....>

....

    <ffimageloading:CachedImage HorizontalOptions="Center" VerticalOptions="Center"
        WidthRequest="300" HeightRequest="300"
        DownsampleToViewSize="true"
        Source = "http://loremflickr.com/600/600/nature?filename=simple.jpg"
        Grid.Column="1"
        Grid.Row="1">
</code>```

When I run it, I get:

```<code>System.MissingMethodException: method 'FFImageLoading.Forms.Droid.CachedImageRenderer.init()' not found.
</code>```

Not sure what's going on. I suspect intellisense would have caught a missing using, and there are no errors during compile, only the one above, at runtime.

What have I done wrong!?

答: Just had to clean the project and rebuild.</p>

Body:
I am trying to use the FFImageLoading in a cross-platform xamarin app.

I followed the instructions, and installed the Xamarin.FFImageLoading and Xamarin.FFImageLoading.Forms in both the android and IOS projects.

I then use this code to intitialize the library:

[Activity (Label = "app", Icon = "@drawable/icon", Theme="@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    protected override void OnCreate (Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate (bundle);

        CachedImageRenderer.Init();

        global::Xamarin.Forms.Forms.Init (this, bundle);
        global::Xamarin.Auth.Presenters.XamarinAndroid.AuthenticationConfiguration.Init(this, bundle);

        LoadApplication (new TheWillowEffect.App ());

    }
}

I haven't tried in it IOS yet. Not a priority.

I have the following XAML just to see if it works:

<ContentPage
....xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"....>

....

    <ffimageloading:CachedImage HorizontalOptions="Center" VerticalOptions="Center"
        WidthRequest="300" HeightRequest="300"
        DownsampleToViewSize="true"
        Source = "http://loremflickr.com/600/600/nature?filename=simple.jpg"
        Grid.Column="1"
        Grid.Row="1">

When I run it, I get:

System.MissingMethodException: method 'FFImageLoading.Forms.Droid.CachedImageRenderer.init()' not found.

Not sure what's going on. I suspect intellisense would have caught a missing using, and there are no errors during compile, only the one above, at runtime.

What have I done wrong!?


问:
How to make a div's background color translucent?
I only want the background color of white in my div to be translucent roughly 50%.  The content should be fully opaque.  What's the proper way to do this?  I imagined when I looked up the background CSS property, I'd find an opacity setting, but didn't.  Don't care about IE6.

UPDATE: solving with the rgba solution given below in conjunction with CSS3PIE's solution for getting rgba to work in IE browsers.

答:
If you want cross-browser opacity, you can handle each within your css definition</p>

```<code>div
{
    opacity: .50; /* Standard: FF gt 1.5, Opera, Safari, CSS3 */
    filter: alpha(opacity=50); /* IE lt 8 */
    -ms-filter: "alpha(opacity=50)"; /* IE 8 */
    -khtml-opacity: .50; /* Safari 1.x */
    -moz-opacity: .50; /* FF lt 1.5, Netscape */
}
</code>```

Body:
If you want cross-browser opacity, you can handle each within your css definition

div
{
    opacity: .50; /* Standard: FF gt 1.5, Opera, Safari, CSS3 */
    filter: alpha(opacity=50); /* IE lt 8 */
    -ms-filter: "alpha(opacity=50)"; /* IE 8 */
    -khtml-opacity: .50; /* Safari 1.x */
    -moz-opacity: .50; /* FF lt 1.5, Netscape */
}

ContentLicense: CC BY-SA 2.5


问:
How to make two
...
 in the same row?
I mean, the two  tags have the same height.

答:
Use a div container and put inside all your divs.

```<code>.div_container{
    display: flex;
    flex-direction: row;
}
</code>```

That easy!

Title: How to make two <div>...</div> in the same row?

Body:
Use a div container and put inside all your divs.

.div_container{
    display: flex;
    flex-direction: row;
}

That easy!


问:
PHP Get Site URL Protocol - http vs https
I've written a little function to establish the current site url protocol but I don't have SSL and don't know how to test if it works under https. Can you tell me if this is correct?

```<code>function siteURL()
{
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'].'/';
    return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );
</code>```

Is it necessary to do it like above or can I just do it like?:

```<code>function siteURL()
{
    $protocol = 'http://';
    $domainName = $_SERVER['HTTP_HOST'].'/'
    return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );
</code>```

Under SSL, doesn't the server automatically convert the url to https even if the anchor tag url is using http? Is it necessary to check for the protocol?

Thank you!

答:
Here is how I do it ... it is a shorthand if else version of Rid Iculous's answer ...

```<code>$protocol = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on' || $_SERVER['HTTPS'] === 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ? 'https' : 'http';
</code>```

Body:
I've written a little function to establish the current site url protocol but I don't have SSL and don't know how to test if it works under https. Can you tell me if this is correct?

function siteURL()
{
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'].'/';
    return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );

Is it necessary to do it like above or can I just do it like?:

function siteURL()
{
    $protocol = 'http://';
    $domainName = $_SERVER['HTTP_HOST'].'/'
    return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );

Under SSL, doesn't the server automatically convert the url to https even if the anchor tag url is using http? Is it necessary to check for the protocol?

Thank you!

Body:
Here is how I do it ... it is a shorthand if else version of Rid Iculous's answer ...

$protocol = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] === 'on' || $_SERVER['HTTPS'] === 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ? 'https' : 'http';


问:
Google Vision crashes when getting UIImage from sample buffer
I finally decided to use Google Mobile Vision sdk for detecting faces and smiling in camera and their sdk and sample look very good and promising.

But after I pasted their sample code into my project it always crashes in captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) callback.
Here is the code snap which always throws BAD_ACCESS exception.

```<code>func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    if (faceDetector == nil) {
        self.faceDetector = GMVDetector(ofType: GMVDetectorTypeFace, options: [GMVDetectorFaceLandmarkType: GMVDetectorFaceLandmark.all.rawValue,
                                                                               GMVDetectorFaceClassificationType: GMVDetectorFaceClassification.all.rawValue,
                                                                               GMVDetectorFaceMinSize: 0.3,
                                                                               GMVDetectorFaceTrackingEnabled: true])
    }
    guard let image = GMVUtility.sampleBufferTo32RGBA(sampleBuffer) else { // <-- this is where throws exception
        print("Invalid sample buffer")
        return
    }
}
</code>```

Possible duplicate Google Face Detection crashing when converting to image and trying to detect face but there's no correct answer to it.

Thanks in any advance.

答:
Finally ended up setting sessionPresset of AVCaptureSession to AVCaptureSessionPresetMedium.

```<code>    self.session.sessionPreset = .medium
</code>```

Obviously there's a memory leak in the library.

Body:
I finally decided to use Google Mobile Vision sdk for detecting faces and smiling in camera and their sdk and sample look very good and promising.

But after I pasted their sample code into my project it always crashes in captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) callback.
Here is the code snap which always throws BAD_ACCESS exception.

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    if (faceDetector == nil) {
        self.faceDetector = GMVDetector(ofType: GMVDetectorTypeFace, options: [GMVDetectorFaceLandmarkType: GMVDetectorFaceLandmark.all.rawValue,
                                                                               GMVDetectorFaceClassificationType: GMVDetectorFaceClassification.all.rawValue,
                                                                               GMVDetectorFaceMinSize: 0.3,
                                                                               GMVDetectorFaceTrackingEnabled: true])
    }
    guard let image = GMVUtility.sampleBufferTo32RGBA(sampleBuffer) else { // <-- this is where throws exception
        print("Invalid sample buffer")
        return
    }
}

Possible duplicate Google Face Detection crashing when converting to image and trying to detect face but there's no correct answer to it.

Thanks in any advance.

Body:
Finally ended up setting sessionPresset of AVCaptureSession to AVCaptureSessionPresetMedium.

    self.session.sessionPreset = .medium

Obviously there's a memory leak in the library.


问:
Find the maximum number of points per game
The input is an array of cards. In one move, you can remove any group of consecutive identical cards. For removing k cards, you get k * k points. Find the maximum number of points you can get per game.

Time limit: O(n4)

Example:

Input: [1, 8, 7, 7, 7, 8, 4, 8, 1]

Output: 23

Does anyone have an idea how to solve this?

To clarify, in the given example, one path to the best solution is

```<code>Remove   Points   Total   new hand
 3 7s      9        9     [1, 8, 8, 4, 8, 1]
 1 4       1       10     [1, 8, 8, 8, 1]
 3 8s      9       19     [1, 1]
 2 1s      4       23     []
</code>```

答:
Approach

Recursion would fit well here.

First, identify the contiguous sequences in the array -- one lemma of this problem is that if you decide to remove at least one 7, you want to remove the entire sequence of three.  From here on, you'll work with both cards and quantities.  For instance,

```<code>card  = [1, 8, 7, 8, 4, 8, 1]
quant = [1, 1, 3, 1, 1, 1, 1]
</code>```

Now you're ready for the actual solving.  Iterate through the array.  For each element, remove that element, and add the score for that move.
Check to see whether the elements on either side match; if so, merge those entries.  Recur on the remaining array.

For instance, here's the first turn of what will prove to be the optimal solution for the given input:

Choose and remove the three 7's

```<code>card  = [1, 8, 8, 4, 8, 1]
quant = [1, 1, 1, 1, 1, 1]
score = score + 3*3
</code>```

Merge the adjacent 8 entries:

```<code>card  = [1, 8, 4, 8, 1]
quant = [1, 2, 1, 1, 1]
</code>```

Recur on this game.

Improvement

Use dynamic programming: memoize the solution for every sub game.

Any card that appears only once in the card array can be removed first, without loss of generality.  In the given example, you can remove the 7's and the single 4 to improve the remaining search tree.

Body:
The input is an array of cards. In one move, you can remove any group of consecutive identical cards. For removing k cards, you get k * k points. Find the maximum number of points you can get per game.

Time limit: O(n4)

Example:

Input: [1, 8, 7, 7, 7, 8, 4, 8, 1]

Output: 23

Does anyone have an idea how to solve this?

To clarify, in the given example, one path to the best solution is

Remove   Points   Total   new hand
 3 7s      9        9     [1, 8, 8, 4, 8, 1]
 1 4       1       10     [1, 8, 8, 8, 1]
 3 8s      9       19     [1, 1]
 2 1s      4       23     []

Body:
Approach

Recursion would fit well here.

First, identify the contiguous sequences in the array -- one lemma of this problem is that if you decide to remove at least one 7, you want to remove the entire sequence of three.  From here on, you'll work with both cards and quantities.  For instance,

card  = [1, 8, 7, 8, 4, 8, 1]
quant = [1, 1, 3, 1, 1, 1, 1]

Now you're ready for the actual solving.  Iterate through the array.  For each element, remove that element, and add the score for that move.
Check to see whether the elements on either side match; if so, merge those entries.  Recur on the remaining array.

For instance, here's the first turn of what will prove to be the optimal solution for the given input:

Choose and remove the three 7's

card  = [1, 8, 8, 4, 8, 1]
quant = [1, 1, 1, 1, 1, 1]
score = score + 3*3

Merge the adjacent 8 entries:

card  = [1, 8, 4, 8, 1]
quant = [1, 2, 1, 1, 1]

Recur on this game.

Improvement

Use dynamic programming: memoize the solution for every sub game.

Any card that appears only once in the card array can be removed first, without loss of generality.  In the given example, you can remove the 7's and the single 4 to improve the remaining search tree.


问:
How do you compare a value from jQuery with a fixed number?
How do you compare a value from jQuery with a fixed number?

I thought this might work but it doesn't:

```<code>if (parseInt($("#days").value) > 7) {
            alert("more than one week");
        }
</code>```

答:
if #days is an input then you need .val() instead of value

e.g.

```<code>  if (parseInt($("#days").val()) > 7) {
        alert("more than one week");
   }
</code>```

OwnerDisplayName: IainMH

Body:
How do you compare a value from jQuery with a fixed number?

I thought this might work but it doesn't:

if (parseInt($("#days").value) > 7) {
            alert("more than one week");
        }

Body:
if #days is an input then you need .val() instead of value

e.g.

  if (parseInt($("#days").val()) > 7) {
        alert("more than one week");
   }

OwnerDisplayName: redsquare


问:
Saving SQLite Database to specific File
Introduction

I am using the official sqlite NuGet package (3.13.0) and entity framework (6.2.0). My initial connection string is data source=sample-database.sqlite.

My Question

How can I save the complete database to a different file (e.g. D:\Path\To\NewFile.sqlite)? I just can think of copying the database file to the new location and renaming it, but this solution feels kind of weird.

Thank you. Any help is appreciated!

答:
How can I save the complete database to a different file (e.g.
  D:\Path\To\NewFile.sqlite)? I just can think of copying the database
  file to the new location and renaming it, but this solution feels kind
  of weird.

Nope. Not weird. I have done this and it works just fine. Just need to remember that you may need to be aware of the new DB location when you add another migration + update-database, (if the connection string is defined in various places)

Title: Saving SQLite Database to specific File


问:
Superset cannot connect to my Sqlite database
I have a database in sqlite and followed this tutorial  on how to create it. I checked, the database exists and contains values.

I entered following SQLAlchemy URI in the web interface of the superset: sqlite:///Users/me/Documents/cancellation/item/eventlog.db

and got following error:

```<code>ERROR: {"error": "Connection failed!\n\nThe error message returned
was:\n'NoneType' object has no attribute
'get_password_masked_url_from_uri'"}
</code>```

I do not understand why there should be a password, if in the documentation there are not passwords specified:

http://docs.sqlalchemy.org/en/rel_1_0/core/engines.html#sqlite

Code:

```<code>sqlite_file = 'eventlog.db' # the DB file
conn = sqlite3.connect(sqlite_file)
eventlog.to_sql('eventlog', conn, if_exists='replace', index=False)
from sqlalchemy import create_engine
>engine = create_engine('sqlite:////Users/me/Documents/cancellation/item/eventlog.db)
</code>```

答: This issue drove me crazy for the last few days.  I eventually found that you actually have to save the database config and then return to the page for the "Test Connection" to actually succeed.  Attempts to use the "Test Connection" button prior to hitting Save produce the error message that you listed.</p>

Body:
I have a database in sqlite and followed this tutorial  on how to create it. I checked, the database exists and contains values.

I entered following SQLAlchemy URI in the web interface of the superset: sqlite:///Users/me/Documents/cancellation/item/eventlog.db

and got following error:

ERROR: {"error": "Connection failed!\n\nThe error message returned
was:\n'NoneType' object has no attribute
'get_password_masked_url_from_uri'"}

I do not understand why there should be a password, if in the documentation there are not passwords specified:

http://docs.sqlalchemy.org/en/rel_1_0/core/engines.html#sqlite

Code:

sqlite_file = 'eventlog.db' # the DB file
conn = sqlite3.connect(sqlite_file)
eventlog.to_sql('eventlog', conn, if_exists='replace', index=False)
from sqlalchemy import create_engine
>engine = create_engine('sqlite:////Users/me/Documents/cancellation/item/eventlog.db)


问:
Getting back cookies from the request in Flurl.Http v2.0.1
When using Flurl.Http v1.2 we had the following code:

```<code>1. var cookieJar = new CookieContainer();
2. var url = baseUrl.AppendPathSegment("api/auth/login");
3. var client = url.EnableCookies();
4. ((HttpClientHandler)client.HttpMessageHandler).CookieContainer = cookieJar;
5. var result = await client.PostJsonAsync(new { UserName = userName, Password = password });
6. var cookies = cookieJar.GetCookies(new Uri(baseUrl));
7. _cookie = cookies[0];
</code>```

After upgrading to v2.0.1 line 4 no longer compiles because client is no longer an IFlurlClient it's now an IFlurlRequest, as per the release notes.

I noticed that IFlurlRequest has a Client property, so I changed line 4 to be:

```<code>4. ((HttpClientHandler)client.Client.HttpMessageHandler).CookieContainer = cookieJar;
</code>```

That now compiles but fails at run-time with an InvalidOperationException:

This instance has already started one or more requests. Properties can only be modified before sending the first request.

I'm assuming that's because of the aggressive reuse of the underlying HttpClient. I added a line between 3 and 4 to create a new FlurlClient each time to ensure the instance could not have started a request.

```<code>1. var cookieJar = new CookieContainer();
2. var url = baseUrl.AppendPathSegment("api/auth/login");
3. var request = url.EnableCookies();
3.5 request.Client = new FlurlClient();
4. ((HttpClientHandler)request.Client.HttpMessageHandler).CookieContainer = cookieJar;
5. var result = client.PostJsonAsync(new { UserName = userName, Password = password }).Result;
6. var cookies = cookieJar.GetCookies(new Uri(baseUrl));
7. _cookie = cookies[0];
</code>```

This now works again, but I'm not sure I'm doing this the correct way. Any feedback would be appreciated.

答:
You shouldn't need to manage CookieContainer explicitly; Flurl makes working with cookies a lot simpler.

Generally you want to reuse HttpClient instances as much as possible, and 2.0 does do this for you by default when you don't create FlurlClients explicitly, but in the case of persisting cookies over multiple calls you're probably going to want to manage FlurlClient yourself, otherwise multiple threads could be reading/writing cookies on the same collection.

Still pretty easy. I think your whole example can be reduced to this:

```<code>using (var cli = new FlurlClient(baseUrl).EnableCookies()) {
    await cli.Request("api/auth/login").PostJsonAsync(new {
        UserName = userName,
        Password = password });
    _cookie = cli.Cookies.First().Value;
}
</code>```

Body:
When using Flurl.Http v1.2 we had the following code:

1. var cookieJar = new CookieContainer();
2. var url = baseUrl.AppendPathSegment("api/auth/login");
3. var client = url.EnableCookies();
4. ((HttpClientHandler)client.HttpMessageHandler).CookieContainer = cookieJar;
5. var result = await client.PostJsonAsync(new { UserName = userName, Password = password });
6. var cookies = cookieJar.GetCookies(new Uri(baseUrl));
7. _cookie = cookies[0];

After upgrading to v2.0.1 line 4 no longer compiles because client is no longer an IFlurlClient it's now an IFlurlRequest, as per the release notes.

I noticed that IFlurlRequest has a Client property, so I changed line 4 to be:

4. ((HttpClientHandler)client.Client.HttpMessageHandler).CookieContainer = cookieJar;

That now compiles but fails at run-time with an InvalidOperationException:

This instance has already started one or more requests. Properties can only be modified before sending the first request.

I'm assuming that's because of the aggressive reuse of the underlying HttpClient. I added a line between 3 and 4 to create a new FlurlClient each time to ensure the instance could not have started a request.

1. var cookieJar = new CookieContainer();
2. var url = baseUrl.AppendPathSegment("api/auth/login");
3. var request = url.EnableCookies();
3.5 request.Client = new FlurlClient();
4. ((HttpClientHandler)request.Client.HttpMessageHandler).CookieContainer = cookieJar;
5. var result = client.PostJsonAsync(new { UserName = userName, Password = password }).Result;
6. var cookies = cookieJar.GetCookies(new Uri(baseUrl));
7. _cookie = cookies[0];

This now works again, but I'm not sure I'm doing this the correct way. Any feedback would be appreciated.

Body:
You shouldn't need to manage CookieContainer explicitly; Flurl makes working with cookies a lot simpler.

Generally you want to reuse HttpClient instances as much as possible, and 2.0 does do this for you by default when you don't create FlurlClients explicitly, but in the case of persisting cookies over multiple calls you're probably going to want to manage FlurlClient yourself, otherwise multiple threads could be reading/writing cookies on the same collection.

Still pretty easy. I think your whole example can be reduced to this:

using (var cli = new FlurlClient(baseUrl).EnableCookies()) {
    await cli.Request("api/auth/login").PostJsonAsync(new {
        UserName = userName,
        Password = password });
    _cookie = cli.Cookies.First().Value;
}


问:
how do I get access to the object that I'm intercepting?
I'm using Castle Core to create a custom attribute and interceptor to inject security checks into our code using attributes.
e.g. [Security("Role1")]

In the implementation of the interceptor:

```<code>public class SecurityInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        object o;

        MethodInfo mi = invocation.Method;
        SecurityAttribute[] atts = (SecurityAttribute[])mi.GetCustomAttributes(typeof(SecurityAttribute), true);

        // if method not marked with Security attribute, then pass on call
        if (atts.Length == 0)
        {
            invocation.Proceed();
        }
        else
        {
            //for now assume that there is only one security attribute on the method
            //do some security test
            {
                invocation.Proceed();
            }
        }

    }
</code>```

In the "do some security test" section above, I need access to the HttpContext.Session object in order to retrieve some saved objects to do the security test.

Assume the method that this attribute is on, is a code-behind asp.net page, i.e an instance of the Page class)
I can't just use this.Context in the attribute like this [Security("Role1", this.Context)]
as attributes don't allow that.

So how do I get access to the httpContext inside the Intercept method?

Or is there a better way of doing this in an aspect-like way?

答:
The InvocationTarget property of the IInvocation instance has the target object. So in your case, if you are certain that the interception happens on a Page object, you should be able to do this:

```<code>var page = (Page)invocation.InvocationTarget;
</code>```

If that is not always the case, you should gain access to the HTTP context in another way.

It's true, as Ben points out, that HttpContext.Current gives you access to the current HttpContext from anywhere, but accessing that static property is just icky. There's a better way, however, and that is by registering a factory method that allows for injection of the session state:

```<code>container.Register(
    Component.For<ISessionState>()
        .UsingFactoryMethod(k => new SessionWrapper(HttpContext.Current.Session)
        .Lifestyle.PerWebRequest));
</code>```

assuming that you have created the ISessionState interface and an appropriate wrapper that has the API you wish to use when interacting with the ASP.NET HttpSessionState object.

Now, since the interceptor is pulled from the container like everything else, it can depend on ISessionState:

```<code>public class SecurityInterceptor : IInterceptor
{
    public SecurityInterceptor(ISessionState sessionState)
    {
        //...
    }
}
</code>```

which makes your interceptor nice and testable.

There's probably many other ways to do this, and possible better ways as well. This is just an idea on how you can get on with your project :)

Body:
I'm using Castle Core to create a custom attribute and interceptor to inject security checks into our code using attributes.
e.g. [Security("Role1")]

In the implementation of the interceptor:

public class SecurityInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        object o;

        MethodInfo mi = invocation.Method;
        SecurityAttribute[] atts = (SecurityAttribute[])mi.GetCustomAttributes(typeof(SecurityAttribute), true);

        // if method not marked with Security attribute, then pass on call
        if (atts.Length == 0)
        {
            invocation.Proceed();
        }
        else
        {
            //for now assume that there is only one security attribute on the method
            //do some security test
            {
                invocation.Proceed();
            }
        }

    }

In the "do some security test" section above, I need access to the HttpContext.Session object in order to retrieve some saved objects to do the security test.

Assume the method that this attribute is on, is a code-behind asp.net page, i.e an instance of the Page class)
I can't just use this.Context in the attribute like this [Security("Role1", this.Context)]
as attributes don't allow that.

So how do I get access to the httpContext inside the Intercept method?

Or is there a better way of doing this in an aspect-like way?

Body:
The InvocationTarget property of the IInvocation instance has the target object. So in your case, if you are certain that the interception happens on a Page object, you should be able to do this:

var page = (Page)invocation.InvocationTarget;

If that is not always the case, you should gain access to the HTTP context in another way.

It's true, as Ben points out, that HttpContext.Current gives you access to the current HttpContext from anywhere, but accessing that static property is just icky. There's a better way, however, and that is by registering a factory method that allows for injection of the session state:

container.Register(
    Component.For<ISessionState>()
        .UsingFactoryMethod(k => new SessionWrapper(HttpContext.Current.Session)
        .Lifestyle.PerWebRequest));

assuming that you have created the ISessionState interface and an appropriate wrapper that has the API you wish to use when interacting with the ASP.NET HttpSessionState object.

Now, since the interceptor is pulled from the container like everything else, it can depend on ISessionState:

public class SecurityInterceptor : IInterceptor
{
    public SecurityInterceptor(ISessionState sessionState)
    {
        //...
    }
}

which makes your interceptor nice and testable.

There's probably many other ways to do this, and possible better ways as well. This is just an idea on how you can get on with your project :)


问:
SSL: Servers certificate chain is incomplete
I bought a PositiveSSL Wildcard from https://www.ssls.com/

I have received 3 files a .ca-bundle a .crt and a .p7b.

I configured the certificates with NGINX but I'm getting an error:

"Servers certificate chain is incomplete"

https://www.ssllabs.com/ssltest/analyze.html?d=api.billgun.com

How can I fix this?

答:
Servers certificate chain is incomplete

means you don't have intermediate certificates, certificates have expired or are in wrong order.

It looks like you don't have any intermediate certificates: https://www.sslshopper.com/ssl-checker.html#hostname=https://api.billgun.com/.

When you open your site in a browser you will get green padlock because browsers can download missing intermediate certificates but other tools won't be able to connect ie. curl:

```<code>curl -I 'https://api.billgun.com/'
curl: (60) server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none
More details here: http://curl.haxx.se/docs/sslcerts.html
</code>```

or openssl:

```<code>openssl s_client -connect api.billgun.com:443
CONNECTED(00000003)
depth=0 OU = Domain Control Validated, OU = PositiveSSL Wildcard, CN = *.billgun.com
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 OU = Domain Control Validated, OU = PositiveSSL Wildcard, CN = *.billgun.com
verify error:num=21:unable to verify the first certificate
verify return:1
---
Certificate chain
 0 s:/OU=Domain Control Validated/OU=PositiveSSL Wildcard/CN=*.billgun.com
   i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA     Domain Validation Secure Server CA
---
</code>```

The fastest way to generate correct chain is to:

open your site in a browser

click on green padlock and display certificate properties

export every certificate in the chain (in your case, you should get 3 files: -billguncom.crt, COMODORSADomainValidationSecureServerCA.crt, COMODORSACertificationAuthority.crt)

combine the files in order from leaf to root cert:

```<code>cat -- -billguncom.crt COMODORSADomainValidationSecureServerCA.crt COMODORSACertificationAuthority.crt > billgun_com.crt
</code>```

install new cert on server

test nginx cofiguration nginx -t

restart server service nginx restart

Body:
Servers certificate chain is incomplete

means you don't have intermediate certificates, certificates have expired or are in wrong order.

It looks like you don't have any intermediate certificates: https://www.sslshopper.com/ssl-checker.html#hostname=https://api.billgun.com/.

When you open your site in a browser you will get green padlock because browsers can download missing intermediate certificates but other tools won't be able to connect ie. curl:

curl -I 'https://api.billgun.com/'
curl: (60) server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none
More details here: http://curl.haxx.se/docs/sslcerts.html

or openssl:

openssl s_client -connect api.billgun.com:443
CONNECTED(00000003)
depth=0 OU = Domain Control Validated, OU = PositiveSSL Wildcard, CN = *.billgun.com
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 OU = Domain Control Validated, OU = PositiveSSL Wildcard, CN = *.billgun.com
verify error:num=21:unable to verify the first certificate
verify return:1
---
Certificate chain
 0 s:/OU=Domain Control Validated/OU=PositiveSSL Wildcard/CN=*.billgun.com
   i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA     Domain Validation Secure Server CA
---

The fastest way to generate correct chain is to:

open your site in a browser

click on green padlock and display certificate properties

export every certificate in the chain (in your case, you should get 3 files: -billguncom.crt, COMODORSADomainValidationSecureServerCA.crt, COMODORSACertificationAuthority.crt)

combine the files in order from leaf to root cert:

cat -- -billguncom.crt COMODORSADomainValidationSecureServerCA.crt COMODORSACertificationAuthority.crt > billgun_com.crt

install new cert on server

test nginx cofiguration nginx -t

restart server service nginx restart


问:
Gettinng user profile information for OAuth2 JWT
I am making an api that accepts social logins from a few services, namely Google.

So far, the mobile app allows the user to log in to google with the OAuth2 flow, and obtains a JWT token. The first time I was able to get the profile info from the token (first name, family name, profile pic, etc...). Now, I doesn't contain all of the fields I need.

I remember reading somewhere that google will only send all the fields from time to time...

Since I'm in testing, I tend to wipe the user database often and would like to be able to count on the google JWT to re-create the account.

I'd rather use the token than hitting the userInfo API. Especially since the JWT is technically secure.

So, is there any sure way to get all of the user profile info in the id_token from the google API?

答: I was using an older endpoint, changed to https://accounts.google.com/o/oauth2/v2/auth and everything is ok!