问:
How do I get all the elements with a specific ID from an SQLite table using Django?
I'm a beginner in SQLite, and I need to know how do I select all the elements from an SQLite table and put them in a list. Here's what I tried:

```<code><select name="users" id="users">
    {% for user_reg in db.user_registration_models %}
    {% if user.is_authenticated %}
    <option value="/all_users/{{ user_reg.id }}">{{ user_reg.username }}</option>
    {% endif %}
    {% endfor %}
</select>
</code>```

Thanks in advance for your answers!

答:
You can either return all the users in the db or return only the authenticated one, if you want to print the username of current user if he is authenticated user the following code:

```<code>{% if request.user.is_authenticated %}
   <select name="users" id="users">
    <option >{{ request.user.username }}</option>
   </select>
{% endif %}

</code>```

If you need to print the username of the current user, just use request.user.username but..
If you want to select anything from db (model) which is created by the current user e.g. posts that created by the current user so can do it by the following:

In model.py file.

```<code>from django.db import models
from django.contrib.auth.models import User

class PostModel(models.Model):
    user= models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=250)
    text = models.CharField(max_length=5000)

</code>```

In veiws.py

```<code>from .modal import PostModel
from django.shortcuts import render

def home_view(request):
 if request.user.is_authenticated:
    posts = PostModel.objects.filter(user=request.user)
    return render(request, 'index.html', {'posts': posts})
 else:
    #you can return anything instead of redirect the user to login page
    # if the user not authenticated

    return render(request, 'login.html', {})
</code>```

In index.html

```<code>{% for item in posts %}

 <div class='post-container' >
   <div class='user'> {item.user.first_name }</div>
   <div class='title'> {item.title}</div>
   <div class='text'> {item.text}</div>

 </div>

{% endfor %}

</code>```

user filter method to get anything with specific parameters, e.g.

```<code>posts = PostModel.objects.filter(user__id=1)
posts = PostModel.objects.filter(title='my post')
users = User.objects.filter(first_name='first name')
</code>```

and so on. Read about filter function in the documentation:
https://docs.djangoproject.com/en/4.0/ref/models/querysets/#filter

Body:
I'm a beginner in SQLite, and I need to know how do I select all the elements from an SQLite table and put them in a list. Here's what I tried:

<select name="users" id="users">
    {% for user_reg in db.user_registration_models %}
    {% if user.is_authenticated %}
    <option value="/all_users/{{ user_reg.id }}">{{ user_reg.username }}</option>
    {% endif %}
    {% endfor %}
</select>

Thanks in advance for your answers!

Body:
You can either return all the users in the db or return only the authenticated one, if you want to print the username of current user if he is authenticated user the following code:

{% if request.user.is_authenticated %}
   <select name="users" id="users">
    <option >{{ request.user.username }}</option>
   </select>
{% endif %}

If you need to print the username of the current user, just use request.user.username but..
If you want to select anything from db (model) which is created by the current user e.g. posts that created by the current user so can do it by the following:

In model.py file.

from django.db import models
from django.contrib.auth.models import User

class PostModel(models.Model):
    user= models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=250)
    text = models.CharField(max_length=5000)

In veiws.py

from .modal import PostModel
from django.shortcuts import render

def home_view(request):
 if request.user.is_authenticated:
    posts = PostModel.objects.filter(user=request.user)
    return render(request, 'index.html', {'posts': posts})
 else:
    #you can return anything instead of redirect the user to login page
    # if the user not authenticated

    return render(request, 'login.html', {})

In index.html

{% for item in posts %}

 <div class='post-container' >
   <div class='user'> {item.user.first_name }</div>
   <div class='title'> {item.title}</div>
   <div class='text'> {item.text}</div>

 </div>

{% endfor %}

user filter method to get anything with specific parameters, e.g.

posts = PostModel.objects.filter(user__id=1)
posts = PostModel.objects.filter(title='my post')
users = User.objects.filter(first_name='first name')

and so on. Read about filter function in the documentation:
https://docs.djangoproject.com/en/4.0/ref/models/querysets/#filter


来源: stackexchange

问:
[Vue warn]: Failed to resolve component: router-view
I'm a newbie to Vue.js and first time dealing with vue-router.
Just created a few files and for some reason I don't get to see the template. Compiled successfully but in the browser I get the following error: Failed to resolve component: router-view

main.js

import { createApp } from 'vue';
import VueRouter from 'vue-router';
import { store } from './store';
import App from './App.vue';
import AuthHandler from './components/AuthHandler';

const router = new VueRouter({
    mode: 'history',
    routes: [
        { path: '/oauth2/callback', component: AuthHandler }
    ]
});

const app = createApp(App)
app.use(router)
app.use(store)
app.mount('#app')
```
<h1>App.vue</h1>
<pre class="lang-html prettyprint-override"><code><template>
  <div>
    <AppHeader></AppHeader>
    <router-view></router-view>
  </div>
</template>

<script>
import AppHeader from "./components/AppHeader";
export default {
  name: "App",
  components: {
    AppHeader
  }
};
</script>
</code>```

components/AuthHandler.vue

<template>

    ... Please wait

</template>

```
<p>Here is the package.json</p>
<h1>package.json</h1>
<pre class="lang-js prettyprint-override"><code>{
  "name": "images",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "core-js": "^3.6.5",
    "lodash": "^4.17.21",
    "qs": "^6.10.1",
    "vue": "^3.0.0",
    "vue-router": "^3.5.2",
    "vuex": "^4.0.2"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^7.0.0"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}
</code>```

答:
I was an idiot, I wanted to use 'vue add vue-router'. Of course it didn't work.

```<code>Vue add router
</code>```

is the command.

```<code>npm install vue-router@4
</code>```

only installs the package, won't add it to the app. If all is well, main.js should look like this:

```<code>import App from "./App.vue";
import router from "./router";

createApp(App).use(router).mount("#app");

</code>```

Unfortunately they forgot to add it to the documentation...

ContentLicense: CC BY-SA 4.0

Body:
I'm a newbie to Vue.js and first time dealing with vue-router.
Just created a few files and for some reason I don't get to see the template. Compiled successfully but in the browser I get the following error: Failed to resolve component: router-view

main.js

import { createApp } from 'vue';
import VueRouter from 'vue-router';
import { store } from './store';
import App from './App.vue';
import AuthHandler from './components/AuthHandler';

const router = new VueRouter({
    mode: 'history',
    routes: [
        { path: '/oauth2/callback', component: AuthHandler }
    ]
});

const app = createApp(App)
app.use(router)
app.use(store)
app.mount('#app')

App.vue

<template>

    <AppHeader></AppHeader>
    <router-view></router-view>

</template>

components/AuthHandler.vue

<template>

    ... Please wait

</template>

Here is the package.json

package.json

{
  "name": "images",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "core-js": "^3.6.5",
    "lodash": "^4.17.21",
    "qs": "^6.10.1",
    "vue": "^3.0.0",
    "vue-router": "^3.5.2",
    "vuex": "^4.0.2"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^7.0.0"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}

Body:
I was an idiot, I wanted to use 'vue add vue-router'. Of course it didn't work.

Vue add router

is the command.

npm install vue-router@4

only installs the package, won't add it to the app. If all is well, main.js should look like this:

import App from "./App.vue";
import router from "./router";

createApp(App).use(router).mount("#app");

Unfortunately they forgot to add it to the documentation...


问:
Android how to draw line?

Possible Duplicate:

  How do you set a line's width when drawing in Android?

I've seen How to draw a line in android but how can I set line width? I tried to set Paint

```<code>    colorCenter = new Paint();
    colorCenter.setAntiAlias(true);
    colorCenter.setStrokeWidth(100);
    colorCenter.setColor(0xFF00FFFF);
</code>```

then in onDraw()

```<code>canvas.drawLine(0, 0, 40, 40, colorCenter);
</code>```

but it always 1px.

I also tried to find class LineShape and use it with ShapeDrawable, but there is no such class!

答:
Add..</p>

```<code>  colorCenter.setStyle(Paint.Style.STROKE);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android how to draw line?

Body:
Possible Duplicate:

  How do you set a line's width when drawing in Android?

I've seen How to draw a line in android but how can I set line width? I tried to set Paint

    colorCenter = new Paint();
    colorCenter.setAntiAlias(true);
    colorCenter.setStrokeWidth(100);
    colorCenter.setColor(0xFF00FFFF);

then in onDraw()

canvas.drawLine(0, 0, 40, 40, colorCenter);

but it always 1px.

I also tried to find class LineShape and use it with ShapeDrawable, but there is no such class!

Body:
Add..

  colorCenter.setStyle(Paint.Style.STROKE);


问:
FB chat plugin error on CORS policy and customerchat net::ERR_FAILED
I got an error implementing the code below inside the body:

```<code><div id="fb-root"></div>
<div id="fb-customer-chat" class="fb-customerchat">
</div>
<script>
  var chatbox = document.getElementById('fb-customer-chat');
  chatbox.setAttribute("page_id", "YOURPAGEIDHERE");
  chatbox.setAttribute("attribution", "biz_inbox");

  window.fbAsyncInit = function() {
  FB.init({
    xfbml            : true,
    version          : 'v12.0'
  });
  };

  (function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = 'https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js';
  fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
</script>
</code>```

Error:

I already Whitelisted the Domains inside FB Advanced Messaging. I'm not sure if I missed something else on the code.

答:
I was also getting these error. I found that the pageId, I was using was wrong♀. These errors come only when your pageId is wrong or the domain is not whitelisted properly(I even tried with a ngrok url and it worked).

So the steps which I followed were-

1)In buisness.facebook.com go to inbox from sidebar and select chat plugin.

2)Click on setup to add your domain.

3)Pick a setup method(standard for react/nextjs) and setup chat plugin(add language, domain , copy code and paste it)

4)You can add multiple domains[https://i.stack.imgur.com/zGdgx.png]

5)You will get pageId already embedded

use this code and paste it in _document.js file in nextjs.
and after deploying it will work perfectly.
For any confusion please let me know.
Thanks, Happy Coding ☺

Body:
I got an error implementing the code below inside the body:

Error:

I already Whitelisted the Domains inside FB Advanced Messaging. I'm not sure if I missed something else on the code.


问:
Backpack for Laravel : Redirection after login
In "Backpack for Laravel", where can I change the redirect after login?
By default, it redirects to /admin/dashboard

I tried modifying in app > Http > Middleware > RedirectifAuthenticated.php file but it doesn't work.

Ideas ? Thank you.

答:
You can change it modifying $this->redirectTo = 'new redirect path / route / function';, defining there the new route to which the user will be redirected once logged in, under __construct() method, in the file app/Http/Controllers/Auth/LoginController.php.

If you need a redirect based on other parameters, or perform actions actions prior to redirecting after login, you can omit $this->redirectTo in construct(), and add the authenticated() method to that same file, which will override the original at backpack\CRUD\app\Library\Auth\AuthenticatesUsers.php

For example, in app/Http/Controllers/Auth/LoginController.php:

```<code>/**
  * The user has been authenticated.
  *
  * @param \Illuminate\Http\Request $request
  * @param mixed $user
  * @return mixed
  */
 protected function authenticated(Request $request, $user)
 {
     // get custom admin user prefered main section
     // return redirect(backpack_url($user_section));
 }
</code>```

Body:
You can change it modifying $this->redirectTo = 'new redirect path / route / function';, defining there the new route to which the user will be redirected once logged in, under __construct() method, in the file app/Http/Controllers/Auth/LoginController.php.

If you need a redirect based on other parameters, or perform actions actions prior to redirecting after login, you can omit $this->redirectTo in construct(), and add the authenticated() method to that same file, which will override the original at backpack\CRUD\app\Library\Auth\AuthenticatesUsers.php

For example, in app/Http/Controllers/Auth/LoginController.php:

/**
  * The user has been authenticated.
  *
  * @param \Illuminate\Http\Request $request
  * @param mixed $user
  * @return mixed
  */
 protected function authenticated(Request $request, $user)
 {
     // get custom admin user prefered main section
     // return redirect(backpack_url($user_section));
 }


问:
Flutter and google_sign_in plugin: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)
The dialog (Google form) for the credentials is opened successfully, but after I fill my credentials I'm getting this error. I followed the instructions from here. Created a Firebase project, enabled the Google Drive API (that's what I need for now) from the Google APIs Console.

The code throwing the exception:

```<code>final GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: [
    'https://www.googleapis.com/auth/drive',
  ],
);

await _googleSignIn.signIn();
</code>```

That's the stack trace:

```<code>E/flutter ( 5068): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter ( 5068): PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)
E/flutter ( 5068): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:551:7)
E/flutter ( 5068): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:292:18)
E/flutter ( 5068): <asynchronous suspension>
E/flutter ( 5068): #2      GoogleSignIn._callMethod (package:google_sign_in/google_sign_in.dart:226:58)
E/flutter ( 5068): <asynchronous suspension>
E/flutter ( 5068): #3      GoogleSignIn._addMethodCall (package:google_sign_in/google_sign_in.dart:268:20)
E/flutter ( 5068): #4      GoogleSignIn.signIn (package:google_sign_in/google_sign_in.dart:339:48)
E/flutter ( 5068): #5      ThatsMyComponentState.theSignInFuction.<anonymous closure> (package:my_app/widgets/my_file.dart:666:45)
E/flutter ( 5068): <asynchronous suspension>
E/flutter ( 5068): #6      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14)
E/flutter ( 5068): #7      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:562:30)
E/flutter ( 5068): #8      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
E/flutter ( 5068): #9      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
E/flutter ( 5068): #10     TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:204:7)
E/flutter ( 5068): #11     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
E/flutter ( 5068): #12     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:184:20)
E/flutter ( 5068): #13     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:158:22)
E/flutter ( 5068): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:138:7)
E/flutter ( 5068): #15     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
E/flutter ( 5068): #16     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
E/flutter ( 5068): #17     _invoke1 (dart:ui/hooks.dart:168:13)
E/flutter ( 5068): #18     _dispatchPointerDataPacket (dart:ui/hooks.dart:122:5)
</code>```

The version of the google_sign_in plugin is 4.0.0.

That's the output of flutter doctot -v:

```<code>[√] Flutter (Channel stable, v1.0.0, on Microsoft Windows [Version 10.0.17763.253], locale en-US)
• Flutter version 1.0.0 at C:\src\flutter-0.7.3\flutter
• Framework revision 5391447fae (10 weeks ago), 2018-11-29 19:41:26 -0800
• Engine revision 7375a0f414
• Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)

[√] Android toolchain - develop for Android devices (Android SDK 28.0.3)
• Android SDK at C:\Users\myuser\AppData\Local\Android\Sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-28, build-tools 28.0.3
• ANDROID_HOME = C:\Users\myuser\AppData\Local\Android\Sdk
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
• All Android licenses accepted.

[√] Android Studio (version 3.3)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 32.0.1
• Dart plugin version 182.5124
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[!] IntelliJ IDEA Community Edition (version 2018.1)
• IntelliJ at C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.1.6
X Flutter plugin not installed; this adds Flutter specific functionality.
X Dart plugin not installed; this adds Dart specific functionality.
• For information about installing plugins, see
  https://flutter.io/intellij-setup/#installing-the-plugins

[!] VS Code, 64-bit edition (version 1.30.2)
• VS Code at C:\Program Files\Microsoft VS Code
• Flutter extension not installed; install from
  https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[√] Connected device (1 available)
• Android SDK built for x86 • emulator-5554 • android-x86 • Android 8.1.0 (API 27) (emulator)

! Doctor found issues in 2 categories.
</code>```

Any help will be much appreciated. Thanks!

答: In my case, the problem was at the point that when I added flavors to my project, I set a different application-id for each flavor. But at the Firebase console, I had only one. Double-check the application ID, please.

Body:
The dialog (Google form) for the credentials is opened successfully, but after I fill my credentials I'm getting this error. I followed the instructions from here. Created a Firebase project, enabled the Google Drive API (that's what I need for now) from the Google APIs Console.

The code throwing the exception:

final GoogleSignIn _googleSignIn = GoogleSignIn(
  scopes: [
    'https://www.googleapis.com/auth/drive',
  ],
);

await _googleSignIn.signIn();

That's the stack trace:

E/flutter ( 5068): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter ( 5068): PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)
E/flutter ( 5068): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:551:7)
E/flutter ( 5068): #1      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:292:18)
E/flutter ( 5068): <asynchronous suspension>
E/flutter ( 5068): #2      GoogleSignIn._callMethod (package:google_sign_in/google_sign_in.dart:226:58)
E/flutter ( 5068): <asynchronous suspension>
E/flutter ( 5068): #3      GoogleSignIn._addMethodCall (package:google_sign_in/google_sign_in.dart:268:20)
E/flutter ( 5068): #4      GoogleSignIn.signIn (package:google_sign_in/google_sign_in.dart:339:48)
E/flutter ( 5068): #5      ThatsMyComponentState.theSignInFuction.<anonymous closure> (package:my_app/widgets/my_file.dart:666:45)
E/flutter ( 5068): <asynchronous suspension>
E/flutter ( 5068): #6      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14)
E/flutter ( 5068): #7      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:562:30)
E/flutter ( 5068): #8      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
E/flutter ( 5068): #9      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
E/flutter ( 5068): #10     TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:204:7)
E/flutter ( 5068): #11     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
E/flutter ( 5068): #12     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:184:20)
E/flutter ( 5068): #13     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:158:22)
E/flutter ( 5068): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:138:7)
E/flutter ( 5068): #15     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
E/flutter ( 5068): #16     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
E/flutter ( 5068): #17     _invoke1 (dart:ui/hooks.dart:168:13)
E/flutter ( 5068): #18     _dispatchPointerDataPacket (dart:ui/hooks.dart:122:5)

The version of the google_sign_in plugin is 4.0.0.

That's the output of flutter doctot -v:

[√] Flutter (Channel stable, v1.0.0, on Microsoft Windows [Version 10.0.17763.253], locale en-US)
• Flutter version 1.0.0 at C:\src\flutter-0.7.3\flutter
• Framework revision 5391447fae (10 weeks ago), 2018-11-29 19:41:26 -0800
• Engine revision 7375a0f414
• Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)

[√] Android toolchain - develop for Android devices (Android SDK 28.0.3)
• Android SDK at C:\Users\myuser\AppData\Local\Android\Sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-28, build-tools 28.0.3
• ANDROID_HOME = C:\Users\myuser\AppData\Local\Android\Sdk
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
• All Android licenses accepted.

[√] Android Studio (version 3.3)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 32.0.1
• Dart plugin version 182.5124
• Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[!] IntelliJ IDEA Community Edition (version 2018.1)
• IntelliJ at C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.1.6
X Flutter plugin not installed; this adds Flutter specific functionality.
X Dart plugin not installed; this adds Dart specific functionality.
• For information about installing plugins, see
  https://flutter.io/intellij-setup/#installing-the-plugins

[!] VS Code, 64-bit edition (version 1.30.2)
• VS Code at C:\Program Files\Microsoft VS Code
• Flutter extension not installed; install from
  https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[√] Connected device (1 available)
• Android SDK built for x86 • emulator-5554 • android-x86 • Android 8.1.0 (API 27) (emulator)

! Doctor found issues in 2 categories.

Any help will be much appreciated. Thanks!


问:
My Bootstrap 5.0 Navbar flashes on large screens, and then disappears
This seemed to be working, until I came back to it some time later - now the navbar links only appear on large screens in Chrome, not FF or Edge.

On loading the page, the links in the navbar below the primary logo at page top appear momentarily, and then are gone.

The navbar behaviour seems to be as expected once the viewport width is reduced to expose the mobile hamburger prompt.

A link to the page exhibiting this behaviour

The HTML markup for the navbar element:

```<code><nav class="navbar navbar-expand-md navbar-light fixed-top background-color-FFF5E5 font-bellotatext-bold pt-md-9">
<div class="container-fluid">
    <a class="navbar-brand d-block d-md-none" href=""><img src="/images/navbar/logo-gongeando.svg" class="d-block img-fluid" alt="" /></a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavDropdown">
        <ul class="navbar-nav mx-auto">
            <li class="nav-item">
                <a class="nav-link" href="#">Home</a>
            </li>
            <!--
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">Science</a>
                <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                    <li><a class="dropdown-item" href="#"></a></li>
                    <li><a class="dropdown-item" href="#"></a></li>
                    <li><a class="dropdown-item" href="#"></a></li>
                </ul>
            </li>
            -->
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">Tools</a>
                <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                    <li><a class="dropdown-item" href="#">Find your inner voice</a></li>
                    <li><a class="dropdown-item" href="#">Meditations</a></li>
                    <li><a class="dropdown-item" href="#">A Glossary</a></li>
                </ul>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">About</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Events</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Testimonials</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Contact me</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href=""><img src="/images/navbar/icon-navbar.svg" title="" /></a>
            </li>
            <!--<li class="nav-item">
                <a class="nav-link" href="#">Shop</a>
            </li>-->
        </ul>
    </div>
</div>
</code>```

I can only guess that in modifying the vanilla bootstrap navbar in order to try and add in the centered logo element for -lg screens, i have gone wrong somewhere?

答: Using fixed-top and setting the z-index for the first container was for some reason obscuring the navbar in firefox. No idea why

Body:
This seemed to be working, until I came back to it some time later - now the navbar links only appear on large screens in Chrome, not FF or Edge.

On loading the page, the links in the navbar below the primary logo at page top appear momentarily, and then are gone.

The navbar behaviour seems to be as expected once the viewport width is reduced to expose the mobile hamburger prompt.

A link to the page exhibiting this behaviour

The HTML markup for the navbar element:

    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

    </button>

                Home

                Tools

Find your inner voice

Meditations

A Glossary

                About

                Events

                Testimonials

                Contact me

I can only guess that in modifying the vanilla bootstrap navbar in order to try and add in the centered logo element for -lg screens, i have gone wrong somewhere?


问:
HOW TO POST IMAGE FILE WITH ALAMOFIRE 5.5
i want to POST an image file with multipartform using alamofire 5.5
im success to implement the GET method with this recently alamofire but get stuck with the POST method.

TIA

答:
For Uploading images to server we need to use multipart request, you can upload the image to a server by using the following code snippet.</p>
```<code> func uploadImage(imgType:String,imgData:Data,imageName:String){
    // params to send additional data, for eg. AccessToken or userUserId
    let params = ["userID":"userId","accessToken":"your accessToken"]
    print(params)
    AF.upload(multipartFormData: { multiPart in
        for (key,keyValue) in params{
            if let keyData = keyValue.data(using: .utf8){
                multiPart.append(keyData, withName: key)
            }
        }

        multiPart.append(imgData, withName: "key",fileName: imageName,mimeType: "image/*")
    }, to: "Your URL",headers: []).responseJSON { apiResponse in

        switch apiResponse.result{
        case .success(_):
            let apiDictionary = apiResponse.value as? [String:Any]
            print("apiResponse --- \(apiDictionary)")
        case .failure(_):
            print("got an error")
        }
    }
}
</code>```

Body:
For Uploading images to server we need to use multipart request, you can upload the image to a server by using the following code snippet.

 func uploadImage(imgType:String,imgData:Data,imageName:String){
    // params to send additional data, for eg. AccessToken or userUserId
    let params = ["userID":"userId","accessToken":"your accessToken"]
    print(params)
    AF.upload(multipartFormData: { multiPart in
        for (key,keyValue) in params{
            if let keyData = keyValue.data(using: .utf8){
                multiPart.append(keyData, withName: key)
            }
        }

        multiPart.append(imgData, withName: "key",fileName: imageName,mimeType: "image/*")
    }, to: "Your URL",headers: []).responseJSON { apiResponse in

        switch apiResponse.result{
        case .success(_):
            let apiDictionary = apiResponse.value as? [String:Any]
            print("apiResponse --- \(apiDictionary)")
        case .failure(_):
            print("got an error")
        }
    }
}


Title: Why does tkinter remove spaces in label?

Body:
I am completely new to python and I added a label

l1 = Label(master, text = """

##     ##       ###        ######     ########    ########    ########     ##     ##    ####    ##   ##    ########
### ###      ## ##      ##    ##       ##       ##          ##     ##    ###   ###     ##     ###   ##    ##     ##
#### ####     ##   ##     ##             ##       ##          ##     ##    #### ####     ##     ####  ##    ##     ##
## ### ##    ##     ##     ######        ##       ######      ########     ## ### ##     ##     ## ## ##    ##     ##
##     ##    #########          ##       ##       ##          ##   ##      ##     ##     ##     ##  ####    ##     ##
##     ##    ##     ##    ##    ##       ##       ##          ##    ##     ##     ##     ##     ##   ###    ##     ##
##     ##    ##     ##     ######        ##       ########    ##     ##    ##     ##    ####    ##    ##    ########
""")

# grid method to arrange labels in respective
# rows and columns as specified
l1.grid(row = 0, column = 0, pady = 2)

But the output I get is quite different than printing MASTERMIND,
output:

Why is this happening? I tried Text widget and with correct height and width it worked but I wanted to ask why doesn't it work with Label widget

Body:
You need to use monospaced font, like 'Courier', and set justify='left' in the Label widget:

l1 = Label(master, text = """

##     ##       ###        ######     ########    ########    ########     ##     ##    ####    ##    ##    ########
###   ###      ## ##      ##    ##       ##       ##          ##     ##    ###   ###     ##     ###   ##    ##     ##
#### ####     ##   ##     ##             ##       ##          ##     ##    #### ####     ##     ####  ##    ##     ##
## ### ##    ##     ##     ######        ##       ######      ########     ## ### ##     ##     ## ## ##    ##     ##
##     ##    #########          ##       ##       ##          ##   ##      ##     ##     ##     ##  ####    ##     ##
##     ##    ##     ##    ##    ##       ##       ##          ##    ##     ##     ##     ##     ##   ###    ##     ##
##     ##    ##     ##     ######        ##       ########    ##     ##    ##     ##    ####    ##    ##    ########
""", font='Courier 8', justify='left')

Result:


问:
Visual C++ (.NET 4.0) - Serializing/Copy custom struct to Byte-Array for sending via NetworkStream
I am working on a TCP-Communication with another person's program. For proper Communication he defined a Header-Struct for the Messages sent via TCP. It is defined something as following:

```<code>typedef struct
{
    uint16_t  number1;
    uint16_t  number2;
    char      name1[64];
    char      name2[64];
    uint32_t  size;
} headerStruct;
</code>```

The struct is somehow filled, most importantly headerStruct.size sets the number of bytes following the header and is the size of the messages to be sent.

I now tried to serialize the header like this:

```<code>headerStruct sourceHeader;
// ... filling Header-Struct here ...

array<Byte>^ result = gcnew array<Byte>(520);  // I tried sizeof(headerStruct) instead of '520', but then I get errors
double allreadyCopied = 0;

// serialize uint16_t 'number1'
array<Byte>^ array1 = BitConverter::GetBytes( sourceHeader.number1 );
Array::Copy(array1 , 0, result, allreadyCopied, array1 ->Length);
allreadyCopied += array1 ->Length;

// serialize uint16_t 'number2'
array<Byte>^ array2 = BitConverter::GetBytes( sourceHeader.number2 );
Array::Copy(array2 , 0, result, allreadyCopied, array2->Length);
allreadyCopied += array2->Length;

// serialize char-Array 'name1'
for (int i = 0; i < sizeof(sourceHeader.name1); i++)
{
    array<Byte>^ arrayName1 = BitConverter::GetBytes( sourceHeader.name1[i] );
    Array::Copy(arrayName1 , 0, result, allreadyCopied, arrayName1->Length);
    allreadyCopied += arrayName1->Length;
}

// serialize char-Array 'name2'
for (int i = 0; i < sizeof(sourceHeader.name2); i++)
{
    array<Byte>^ arrayName2 = BitConverter::GetBytes( sourceHeader.name2[i] );
    Array::Copy(arrayName2 , 0, result, allreadyCopied, arrayName2->Length);
    allreadyCopied += arrayName2->Length;
}

// serialize uint32_t 'size'
array<Byte>^ arraySize = BitConverter::GetBytes( sourceHeader.size);
Array::Copy(arraySize, 0, result, allreadyCopied, arraySize->Length);
allreadyCopied += arraySize->Length;
</code>```

Now this seems to work for me, BUT:

I tried using sizeof(headerStruct) instead of the hardcoded value 520 for the size if the result-array. I just "calculated" it with the variable allreadyCopied. But why are they different? Where's my error here?

This method is surely not very elegant. Is there a better way to do this? I tried the Marshal-Class but did not manage to get it working!

Somehow it feels like this approach is wrong. Is this the right way or am I completely wrong here?

Any help is appreciated a lot! Thanks!

Edit:

OK just checked:

```<code>sizeof(headerStruct);       // = 136;
sizeof(char);               // = 1;
sizeof(sourceHeader.name1); // = 64;
</code>```

BUT

```<code>arrayName1->Length;         // = 4;
</code>```

Why? Very confusing: MSDN (link here) says that the returned Array should be of length 2, not 4.

答:
You are getting yourself into trouble my mixing native (unmanaged) and managed types.  The sizeof(headerStruct) doesn't work because you forgot that you add extra bytes after it.  The arrayName1->Length is 4 because you are passing a native char to GetBytes().  The compiler promotes it to the next compatible managed type, Int32.  Only a Char is 2 bytes, note the capital C.  Equivalent to wchar_t in native code.

Sending binary data like this across a network is usually a mistake.  You hope that the other end uses the same kind of compiler and same kind of endian-ness.  Which is fine when you control both ends but it sounds like you don't.  A generic works-everywhere format is XML.  That's trivial in .NET but not for a native type.  You'd have to write a wrapper for the struct that's a ref class and uses managed types.  Also the reason why you have trouble with the Marshal class.

Body:
I am working on a TCP-Communication with another person's program. For proper Communication he defined a Header-Struct for the Messages sent via TCP. It is defined something as following:

typedef struct
{
    uint16_t  number1;
    uint16_t  number2;
    char      name1[64];
    char      name2[64];
    uint32_t  size;
} headerStruct;

The struct is somehow filled, most importantly headerStruct.size sets the number of bytes following the header and is the size of the messages to be sent.

I now tried to serialize the header like this:

headerStruct sourceHeader;
// ... filling Header-Struct here ...

array<Byte>^ result = gcnew array<Byte>(520);  // I tried sizeof(headerStruct) instead of '520', but then I get errors
double allreadyCopied = 0;

// serialize uint16_t 'number1'
array<Byte>^ array1 = BitConverter::GetBytes( sourceHeader.number1 );
Array::Copy(array1 , 0, result, allreadyCopied, array1 ->Length);
allreadyCopied += array1 ->Length;

// serialize uint16_t 'number2'
array<Byte>^ array2 = BitConverter::GetBytes( sourceHeader.number2 );
Array::Copy(array2 , 0, result, allreadyCopied, array2->Length);
allreadyCopied += array2->Length;

// serialize char-Array 'name1'
for (int i = 0; i < sizeof(sourceHeader.name1); i++)
{
    array<Byte>^ arrayName1 = BitConverter::GetBytes( sourceHeader.name1[i] );
    Array::Copy(arrayName1 , 0, result, allreadyCopied, arrayName1->Length);
    allreadyCopied += arrayName1->Length;
}

// serialize char-Array 'name2'
for (int i = 0; i < sizeof(sourceHeader.name2); i++)
{
    array<Byte>^ arrayName2 = BitConverter::GetBytes( sourceHeader.name2[i] );
    Array::Copy(arrayName2 , 0, result, allreadyCopied, arrayName2->Length);
    allreadyCopied += arrayName2->Length;
}

// serialize uint32_t 'size'
array<Byte>^ arraySize = BitConverter::GetBytes( sourceHeader.size);
Array::Copy(arraySize, 0, result, allreadyCopied, arraySize->Length);
allreadyCopied += arraySize->Length;

Now this seems to work for me, BUT:

I tried using sizeof(headerStruct) instead of the hardcoded value 520 for the size if the result-array. I just "calculated" it with the variable allreadyCopied. But why are they different? Where's my error here?

This method is surely not very elegant. Is there a better way to do this? I tried the Marshal-Class but did not manage to get it working!

Somehow it feels like this approach is wrong. Is this the right way or am I completely wrong here?

Any help is appreciated a lot! Thanks!

Edit:

OK just checked:

sizeof(headerStruct);       // = 136;
sizeof(char);               // = 1;
sizeof(sourceHeader.name1); // = 64;

BUT

arrayName1->Length;         // = 4;

Why? Very confusing: MSDN (link here) says that the returned Array should be of length 2, not 4.


问:
Add phone call only MFA to custom policy
I have an existing custom policy (https://github.com/azure-ad-b2c/samples/blob/master/policies/passwordless-email/) and I want to add phone MFA to this.
I found https://github.com/azure-ad-b2c/samples/tree/master/policies/mfa-email-or-phone but this allows email or phone, there is also https://github.com/Azure-Samples/active-directory-b2c-custom-policy-starterpack/tree/master/SocialAndLocalAccountsWithMfa and https://learn.microsoft.com/en-us/azure/active-directory-b2c/multi-factor-auth-technical-profile.

Is there any way to force a phone call as mfa? (don't allow sms)

答:
You need to use this setting:

```<code>"setting.authenticationMode"
</code>```

"The method to validate the phone number. Possible values: sms, phone, or mixed (default)"

Body:
You need to use this setting:

"setting.authenticationMode"

"The method to validate the phone number. Possible values: sms, phone, or mixed (default)"


问:
How long does it take to send a file of 640,000 bits from host A to host B over a circuit-switched network?
Just going over an exam question and can't figure out the correct method to solve it. The question is as follows :

```<code>How long does it take to send a file of
640,000 bits from host A to host B over a
circuit-switched network?

 - All links are 1.536 Mb/s
 - Each link uses TDM with 24 slots/sec (TDM = Time Division Multiplexing)
 - 500 msec to establish end-to-end circuit
</code>```

To my mind, then, the answer would be

```<code> x = (1.536 * 10^6) / 24
 y = 640,000 / x.
 Answer : y + 500 * 10^-3
</code>```

I have a feeling this is catastrophically wrong though. Can anyone help me out please ? :)

答:
Each circuit has a transmission rate of (1.536 Mbps)/24 = 64 kbps.

It takes (640,000 bits)/(64 kbps) = 10 seconds to transmit the file.

To this 10 seconds we add the circuit establishment time, giving 10.5
seconds to send the file.

Note that the transmission time is independent of the number of links:
The transmission time would be 10 seconds if the end-to-end circuit
passed through one link or a hundred links

Body:
Just going over an exam question and can't figure out the correct method to solve it. The question is as follows :

How long does it take to send a file of
640,000 bits from host A to host B over a
circuit-switched network?

 - All links are 1.536 Mb/s
 - Each link uses TDM with 24 slots/sec (TDM = Time Division Multiplexing)
 - 500 msec to establish end-to-end circuit

To my mind, then, the answer would be

 x = (1.536 * 10^6) / 24
 y = 640,000 / x.
 Answer : y + 500 * 10^-3

I have a feeling this is catastrophically wrong though. Can anyone help me out please ? :)


问:
Why did http request and backend service save string data type to database with double quotes?
I am working on a web application. Backend: spring boot and frontend: vuejs.
When I test with Swagger, my controller that provide to save a string data to database work fine but save with double quotes. At the same time when I wrote my data from an input in vue js I face to face same mistake again. My data is in my database but with double quotes.
I hope I can explain my problem clearly.
I don't want to see "sample data" in database, it will be just sample data without double quotes.</p>
```<code>@PatchMapping("addSampleName/{clmnId}")
@Override
public Result addSampleName(@PathVariable ("clmnId") int clmnId, @RequestBody String sampleName)

{
    return this.columnTableService.addSampleName(clmnId, sampleName);
}
</code>```

答:
I found where I made mistake. @RequestBody had got directly String type. I changed my parameter's type to "Map<String, object>" and this fixed my problem. I add my new code block.

```<code>@PatchMapping("addSampleName/{clmnId}")
@Override
public Result addSampleName(@PathVariable ("clmnId") int clmnId, @RequestBody Map<String, Object> data)
{

    return this.columnTableService.addSampleName(clmnId, data);
}
</code>```

(Of course you should change your method that is in service and class that implemented this service.)

Body:
I am working on a web application. Backend: spring boot and frontend: vuejs.
When I test with Swagger, my controller that provide to save a string data to database work fine but save with double quotes. At the same time when I wrote my data from an input in vue js I face to face same mistake again. My data is in my database but with double quotes.
I hope I can explain my problem clearly.
I don't want to see "sample data" in database, it will be just sample data without double quotes.

@PatchMapping("addSampleName/{clmnId}")
@Override
public Result addSampleName(@PathVariable ("clmnId") int clmnId, @RequestBody String sampleName)

{
    return this.columnTableService.addSampleName(clmnId, sampleName);
}

Body:
I found where I made mistake. @RequestBody had got directly String type. I changed my parameter's type to "Map<String, object>" and this fixed my problem. I add my new code block.

@PatchMapping("addSampleName/{clmnId}")
@Override
public Result addSampleName(@PathVariable ("clmnId") int clmnId, @RequestBody Map<String, Object> data)
{

    return this.columnTableService.addSampleName(clmnId, data);
}

(Of course you should change your method that is in service and class that implemented this service.)


问:
How do you detect if a list has exactly 3 items in Haskell?
I have this but I got an error:</p>

```<code>-- test if a list contains exactly three characters
test :: [Char] -> Bool
test xs   | [_ , _ , _] = True
          | otherwise = False
</code>```

答:
```<code>main = do
  a:b:c:[] <- pure "123"  -- fails in runtime in MonadFail if they are not exactly 3
  print a >> print b >> print c
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have this but I got an error:

-- test if a list contains exactly three characters
test :: [Char] -> Bool
test xs   | [_ , _ , _] = True
          | otherwise = False


问:
Gesture recognizer and button actions
I have a view hierarchy that looks something like this:

```<code>UIView (A)
UIView > UIImageView
UIView > UIView (B)
UIView > UIView (B) > Rounded Rect Button
UIView > UIView (B) > UIImageView
UIView > UIView (B) > UILabel
</code>```

I've attached gesture recognizer(s) to my UIView (B). The problem that i'm facing is that i don't get any actions for the Rounded Rect Button which is inside the UIView (B). The singleTap gesture recognizer captures/overrides the button's Touch Up Inside event.

How can i make it work? I thought that the responder chain hierarchy will make sure that the button touch event will be given preference, and it WILL get triggered! What am i missing?

Here's some related code:

```<code>#pragma mark -
#pragma mark View lifecycle (Gesture recognizer setup)

- (void)viewDidLoad {
    [super viewDidLoad];

    // double tap gesture recognizer
    UITapGestureRecognizer *dtapGestureRecognize = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapGestureRecognizer:)];
    dtapGestureRecognize.delegate = self;
    dtapGestureRecognize.numberOfTapsRequired = 2;
    [self.viewB addGestureRecognizer:dtapGestureRecognize];

    // single tap gesture recognizer
    UITapGestureRecognizer *tapGestureRecognize = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureRecognizer:)];
    tapGestureRecognize.delegate = self;
    tapGestureRecognize.numberOfTapsRequired = 1;
    [tapGestureRecognize requireGestureRecognizerToFail:dtapGestureRecognize];
    [self.viewB addGestureRecognizer:tapGestureRecognize];

    // add gesture recodgnizer to the grid view to start the edit mode
    UILongPressGestureRecognizer *pahGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureRecognizerStateChanged:)];
    pahGestureRecognizer.delegate = self;
    pahGestureRecognizer.minimumPressDuration = 0.5;
    [self.viewB addGestureRecognizer:pahGestureRecognizer];

    [dtapGestureRecognize release];
    [tapGestureRecognize release];
    [pahGestureRecognizer release];
}

#pragma mark -
#pragma mark Button actions

- (IBAction)buttonTouchUpInside:(id)sender {
    NSLog(@"%s, %@", __FUNCTION__, sender);
}

#pragma mark -
#pragma mark Gesture recognizer actions

- (void)singleTapGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {
    NSLog(@"%s", __FUNCTION__);
}

- (void)doubleTapGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {
    NSLog(@"%s", __FUNCTION__);
}

- (void)longPressGestureRecognizerStateChanged:(UIGestureRecognizer *)gestureRecognizer {

    switch (gestureRecognizer.state) {

        case UIGestureRecognizerStateEnded: {
            NSLog(@"%s", __FUNCTION__);

            break;
        }
        default:
            break;
    }
}
</code>```

答:
for Swift 5 inside the delegate you can just add:</p>
```<code>return (touch.view is UIButton) ? false : true
</code>```

Title: Gesture recognizer and button actions

Body:
I have a view hierarchy that looks something like this:

UIView (A)
UIView > UIImageView
UIView > UIView (B)
UIView > UIView (B) > Rounded Rect Button
UIView > UIView (B) > UIImageView
UIView > UIView (B) > UILabel

I've attached gesture recognizer(s) to my UIView (B). The problem that i'm facing is that i don't get any actions for the Rounded Rect Button which is inside the UIView (B). The singleTap gesture recognizer captures/overrides the button's Touch Up Inside event.

How can i make it work? I thought that the responder chain hierarchy will make sure that the button touch event will be given preference, and it WILL get triggered! What am i missing?

Here's some related code:

#pragma mark -
#pragma mark View lifecycle (Gesture recognizer setup)

- (void)viewDidLoad {
    [super viewDidLoad];

    // double tap gesture recognizer
    UITapGestureRecognizer *dtapGestureRecognize = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapGestureRecognizer:)];
    dtapGestureRecognize.delegate = self;
    dtapGestureRecognize.numberOfTapsRequired = 2;
    [self.viewB addGestureRecognizer:dtapGestureRecognize];

    // single tap gesture recognizer
    UITapGestureRecognizer *tapGestureRecognize = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureRecognizer:)];
    tapGestureRecognize.delegate = self;
    tapGestureRecognize.numberOfTapsRequired = 1;
    [tapGestureRecognize requireGestureRecognizerToFail:dtapGestureRecognize];
    [self.viewB addGestureRecognizer:tapGestureRecognize];

    // add gesture recodgnizer to the grid view to start the edit mode
    UILongPressGestureRecognizer *pahGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureRecognizerStateChanged:)];
    pahGestureRecognizer.delegate = self;
    pahGestureRecognizer.minimumPressDuration = 0.5;
    [self.viewB addGestureRecognizer:pahGestureRecognizer];

    [dtapGestureRecognize release];
    [tapGestureRecognize release];
    [pahGestureRecognizer release];
}

#pragma mark -
#pragma mark Button actions

- (IBAction)buttonTouchUpInside:(id)sender {
    NSLog(@"%s, %@", __FUNCTION__, sender);
}

#pragma mark -
#pragma mark Gesture recognizer actions

- (void)singleTapGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {
    NSLog(@"%s", __FUNCTION__);
}

- (void)doubleTapGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {
    NSLog(@"%s", __FUNCTION__);
}

- (void)longPressGestureRecognizerStateChanged:(UIGestureRecognizer *)gestureRecognizer {

    switch (gestureRecognizer.state) {

        case UIGestureRecognizerStateEnded: {
            NSLog(@"%s", __FUNCTION__);

            break;
        }
        default:
            break;
    }
}

Body:
for Swift 5 inside the delegate you can just add:

return (touch.view is UIButton) ? false : true


问:
Converts from timedelta into minutes
I'm calculating with the variables current time and end_program to get the remaining minutes.

```<code>current_time = datetime.timedelta(hours = get_24_hours, minutes = get_24_minutes)
end_program = datetime.timedelta(hours = int(program_hours), minutes = int(program_minutes))
current_program = end_program - current_time
</code>```

Output:

```<code>1:30:00
2:00:00
0:45:00
0:45:00
0:15:00
0:15:00
0:35:00
</code>```

I want to converts the timedelta into minutes:

```<code>90
120
45
45
15
15
35
</code>```

As you can see the timedelta 0:15:00 which it means for 15 minutes so I want to convert it to 15, for 0:35:00 as 35 minutes I want to convert it to 35, for 0:45:00 as 45 minutes I want to convert it to 45, but for 2:00:00 as 2 hours I want to convert it to 120 as 120 minutes. For 1:30:00 as 1 hour and 30 minutes I want to convert it to 90 minutes.

How I can converts from timedelta into minutes?

答:
This is a way work for me

My timestamp data is from https://opendata.edp.com/pages/homepage/wind-farm-1-signals-2016.csv

I load the excel data as df

```<code>input: df.Timestamp[1]
output: '2016-04-19T12:20:00+00:00'
input: df.Timestamp[2]
output: '2016-01-08T23:10:00+00:00'
</code>```

First, convert df.Timestamp[1]-df.Timestamp[2] into the Timedalta format as follows

```<code>input: Timestamp_in_min = pd.Timestamp(df.Timestamp[1])-pd.Timestamp(df.Timestamp[0])
output: Timedelta('101 days 13:10:00')
</code>```

Then convert the Timedelta format into the float format in second as follows:

```<code>input: Timestamp_in_min.total_seconds()
output: 8773800.0
</code>```

Then we can convert the time difference into mins by dividing 60.

Title: Converts from timedelta into minutes

Body:
I'm calculating with the variables current time and end_program to get the remaining minutes.

current_time = datetime.timedelta(hours = get_24_hours, minutes = get_24_minutes)
end_program = datetime.timedelta(hours = int(program_hours), minutes = int(program_minutes))
current_program = end_program - current_time

Output:

1:30:00
2:00:00
0:45:00
0:45:00
0:15:00
0:15:00
0:35:00

I want to converts the timedelta into minutes:

90
120
45
45
15
15
35

As you can see the timedelta 0:15:00 which it means for 15 minutes so I want to convert it to 15, for 0:35:00 as 35 minutes I want to convert it to 35, for 0:45:00 as 45 minutes I want to convert it to 45, but for 2:00:00 as 2 hours I want to convert it to 120 as 120 minutes. For 1:30:00 as 1 hour and 30 minutes I want to convert it to 90 minutes.

How I can converts from timedelta into minutes?

Body:
This is a way work for me

My timestamp data is from https://opendata.edp.com/pages/homepage/wind-farm-1-signals-2016.csv

I load the excel data as df

input: df.Timestamp[1]
output: '2016-04-19T12:20:00+00:00'
input: df.Timestamp[2]
output: '2016-01-08T23:10:00+00:00'

First, convert df.Timestamp[1]-df.Timestamp[2] into the Timedalta format as follows

input: Timestamp_in_min = pd.Timestamp(df.Timestamp[1])-pd.Timestamp(df.Timestamp[0])
output: Timedelta('101 days 13:10:00')

Then convert the Timedelta format into the float format in second as follows:

input: Timestamp_in_min.total_seconds()
output: 8773800.0

Then we can convert the time difference into mins by dividing 60.


问:
Is there a way to specify the icon for a SearchRecentSuggestionsProvider?
I'm looking to specify an icon for my application's local search history, but I am not seeing anything in the docs that would allow me to easily add one. To be clear, I am using the built-in Android search API and utilizing a SearchRecentSuggestionsProvider that I have implemented.

Also, I am targeting API level 7.

-Dan

答:
Okay, I'm not sure if this is the easiest way to accomplish what I had asked, but here's how I did it:

Create another ContentProvider and use that in my searchable.xml

This new ContentProvider's query method will query my SearchRecentSuggestionsProvider with special parameters and a special URI and return that Cursor.

Source code snippet of my new ContentProvider:

```<code>...
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
final String[] PROJECTION = new String[] {
        "_id",
        "display1 AS " + SearchManager.SUGGEST_COLUMN_TEXT_1,
        "display2 AS " + SearchManager.SUGGEST_COLUMN_TEXT_2,
        "query AS " + SearchManager.SUGGEST_COLUMN_QUERY,
        android.R.drawable.ic_menu_recent_history + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1,
    };
    final Uri URI =
        Uri.parse("content://" + SearchHistoryProvider.AUTHORITY + "/suggestions");
    return getContext().getContentResolver().query(
        URI,
        PROJECTION,
        "display1 LIKE ?",
        new String[] {selectionArgs[0] + "%"},
        "date DESC");
}
...
</code>```

If the SearchRecentSuggestionsProvider is not set up to use two lines, 'display2' in the projection above should be changed to 'null' or could probably be omitted altogether.

If the 'suggestions' path is omitted from the URI, it will not work. It must be 'suggestions' otherwise you will see an 'Invalid Uri' Exception.

I dug most of this information up by digging through the source code to SearchRecentSuggestionsProvider.

Body:
Okay, I'm not sure if this is the easiest way to accomplish what I had asked, but here's how I did it:

Create another ContentProvider and use that in my searchable.xml

This new ContentProvider's query method will query my SearchRecentSuggestionsProvider with special parameters and a special URI and return that Cursor.

Source code snippet of my new ContentProvider:

...
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
final String[] PROJECTION = new String[] {
        "_id",
        "display1 AS " + SearchManager.SUGGEST_COLUMN_TEXT_1,
        "display2 AS " + SearchManager.SUGGEST_COLUMN_TEXT_2,
        "query AS " + SearchManager.SUGGEST_COLUMN_QUERY,
        android.R.drawable.ic_menu_recent_history + " AS " + SearchManager.SUGGEST_COLUMN_ICON_1,
    };
    final Uri URI =
        Uri.parse("content://" + SearchHistoryProvider.AUTHORITY + "/suggestions");
    return getContext().getContentResolver().query(
        URI,
        PROJECTION,
        "display1 LIKE ?",
        new String[] {selectionArgs[0] + "%"},
        "date DESC");
}
...

If the SearchRecentSuggestionsProvider is not set up to use two lines, 'display2' in the projection above should be changed to 'null' or could probably be omitted altogether.

If the 'suggestions' path is omitted from the URI, it will not work. It must be 'suggestions' otherwise you will see an 'Invalid Uri' Exception.

I dug most of this information up by digging through the source code to SearchRecentSuggestionsProvider.


问:
CORS No 'Access-Control-Allow-Origin' error in React app w/ Facebook
I'm a junior developer that's fairly new to using Facebook for Developers.  I'm hitting a wall with the ReactJs application I'm building and could use your help!

My boss has requested a Grid representation of the Page Plugin, not the actual Plugin itself.  For this project, he's requested I make and use a test 'Page' I've found that DevExtreme's Data Grid seems to be the best option in terms of the desired visual, and I'm trying to call my Facebook Page using the Graph API documentation.  I know it's hitting at least the area I want it to with my console.log because it's returning the error message.

Here are the errors my browser is returning:

Access to fetch at 'https://www.facebook.com/Feeds-Tester-170107151801959/' from origin 'https://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

GET https://www.facebook.com/Feeds-Tester-170107151801959/ net::ERR_FAILED

The link you'll see referenced in my URL variable has been triple checked to be the correct link.  Since I'm using NodeJS, I tried installing the CORS npm package but I'm not 100% sure where to put it to use it, I'm wondering if that's the cause of the issue?

Here's my full code snippet (I'm using VS Code, if that helps):

/*global FB*/
import React from 'react';
import { DataGrid, Editing, Scrolling, Lookup, Summary, TotalItem } from 'devextreme-react/data-grid';
import { Button } from 'devextreme-react/button';
import { SelectBox } from 'devextreme-react/select-box';
import CustomStore from 'devextreme/data/custom_store';
import { formatDate } from 'devextreme/localization';
import 'whatwg-fetch';

const URL = 'https://www.facebook.com/Feeds-Tester-170107151801959/';
const REFRESH_MODES = ['full', 'reshape', 'repaint'];
class Grid extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fbData: null,
      ordersData: new CustomStore({
        key: 'OrderID',
        load: () => this.sendRequest(`${URL}`, 'GET'),
      }),
      requests: [],
      refreshMode: 'reshape'
    };
    this.clearRequests = this.clearRequests.bind(this);
    this.handleRefreshModeChange = this.handleRefreshModeChange.bind(this);

  var body = 'Reading JS SDK documentation';
  FB.api('/me/feed', 'post', { message: body }, function(response) {
    if (!response || response.error) {
      console.log('Error occured');
    } else {
      console.log('Post ID: ' + response.id);
    }
  })
}

  sendRequest(url, method, data) {
    method = method || 'GET';
    data = data || {};
    this.logRequest(method, url, data);
    if(method === 'GET') {
      return fetch(url, {
        method: method,
        credentials: 'include',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          'Access-Control-Allow-Origin': '*'
        }
      }).then(result => result.json().then(json => {
        if(result.ok) return json.data;
        throw json.Message;
      }));
    }

    const params = Object.keys(data).map((key) => {
      return `${encodeURIComponent(key) }=${ encodeURIComponent(data[key])}`;
    }).join('&');
    return fetch(url, {
      method: method,
      body: params,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      credentials: 'include'
    }).then(result => {
      if(result.ok) {
        return result.text().then(text => text && JSON.parse(text));
      } else {
        return result.json().then(json => {
          throw json.Message;
        });
      }
    });
  }

  logRequest(method, url, data) {
    const args = Object.keys(data || {}).map(function(key) {
      return `${key }=${ data[key]}`;
    }).join(' ');

    const time = formatDate(new Date(), 'HH:mm:ss');
    const request = [time, method, url.slice(URL.length), args].join(' ');
    this.setState((state) => {
      return { requests: [request].concat(state.requests) };
    });
  }
  clearRequests() {
    this.setState({ requests: [] });
  }
  handleRefreshModeChange(e) {
    this.setState({ refreshMode: e.value });
  }
  render() {
    const { refreshMode, ordersData } = this.state;
    return (
      <React.Fragment>
        <DataGrid
          id="grid"
          showBorders={true}
          dataSource={ordersData}
          repaintChangesOnly={true}
        >
          <Editing
            refreshMode={refreshMode}
            mode="cell"
            allowAdding={true}
            allowDeleting={true}
            allowUpdating={true}
          />

          <Scrolling
            mode="virtual"
          />

          <Lookup dataSource={ordersData} valueExpr="Value" displayExpr="Text" />

            {/* <TotalItem column="CustomerID" summaryType="count" />
            <TotalItem column="Freight" summaryType="sum" valueFormat="#0.00" /> */}

        </DataGrid>

Options

            Refresh Mode:
            <SelectBox
              value={refreshMode}
              items={REFRESH_MODES}
              onValueChanged={this.handleRefreshModeChange}
            />

Network Requests

              <Button id="clear" text="Clear" onClick={this.clearRequests} />

              {this.state.requests.map((request, index) =>
{request}
)}

      </React.Fragment>
    );
  }
}

export default Grid;```

This is the link to the docs for the module I'm trying to reference

I'm trying to not bite off more than I can chew and just start with retrieving the data before I even think about manipulating it or sending any in return.  Any insight or guidance you can provide would be greatly appreciated.  Thank you!! :)

答:
I was also getting these error. I found that the pageId, I was using was wrong♀. These errors come only when your pageId is wrong or the domain is not whitelisted properly(I even tried with a ngrok url and it worked).

So the steps which I followed were:

In buisness.facebook.com go to inbox from sidebar and select chat plugin. [https://i.stack.imgur.com/rDk5d.png]

Click on setup to add your domain. [https://i.stack.imgur.com/exOi2.png]

Pick a setup method(standard for react/nextjs) and setup chat plugin(add language, domain, copy code and paste it). [https://i.stack.imgur.com/hDArZ.png]

You can add multiple domains. [https://i.stack.imgur.com/zGdgx.png]

You will get pageId already embedded. [https://i.stack.imgur.com/iRT13.png]

Use this code and paste it in _document.js file in nextjs. and after deploying it will work perfectly. For any confusion please let me know. Thanks, Happy Coding ☺

Body:
I'm a junior developer that's fairly new to using Facebook for Developers.  I'm hitting a wall with the ReactJs application I'm building and could use your help!

My boss has requested a Grid representation of the Page Plugin, not the actual Plugin itself.  For this project, he's requested I make and use a test 'Page' I've found that DevExtreme's Data Grid seems to be the best option in terms of the desired visual, and I'm trying to call my Facebook Page using the Graph API documentation.  I know it's hitting at least the area I want it to with my console.log because it's returning the error message.

Here are the errors my browser is returning:

Access to fetch at 'https://www.facebook.com/Feeds-Tester-170107151801959/' from origin 'https://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

GET https://www.facebook.com/Feeds-Tester-170107151801959/ net::ERR_FAILED

The link you'll see referenced in my URL variable has been triple checked to be the correct link.  Since I'm using NodeJS, I tried installing the CORS npm package but I'm not 100% sure where to put it to use it, I'm wondering if that's the cause of the issue?

Here's my full code snippet (I'm using VS Code, if that helps):

/*global FB*/
import React from 'react';
import { DataGrid, Editing, Scrolling, Lookup, Summary, TotalItem } from 'devextreme-react/data-grid';
import { Button } from 'devextreme-react/button';
import { SelectBox } from 'devextreme-react/select-box';
import CustomStore from 'devextreme/data/custom_store';
import { formatDate } from 'devextreme/localization';
import 'whatwg-fetch';

const URL = 'https://www.facebook.com/Feeds-Tester-170107151801959/';
const REFRESH_MODES = ['full', 'reshape', 'repaint'];
class Grid extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fbData: null,
      ordersData: new CustomStore({
        key: 'OrderID',
        load: () => this.sendRequest(`${URL}`, 'GET'),
      }),
      requests: [],
      refreshMode: 'reshape'
    };
    this.clearRequests = this.clearRequests.bind(this);
    this.handleRefreshModeChange = this.handleRefreshModeChange.bind(this);

  var body = 'Reading JS SDK documentation';
  FB.api('/me/feed', 'post', { message: body }, function(response) {
    if (!response || response.error) {
      console.log('Error occured');
    } else {
      console.log('Post ID: ' + response.id);
    }
  })
}

  sendRequest(url, method, data) {
    method = method || 'GET';
    data = data || {};
    this.logRequest(method, url, data);
    if(method === 'GET') {
      return fetch(url, {
        method: method,
        credentials: 'include',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          'Access-Control-Allow-Origin': '*'
        }
      }).then(result => result.json().then(json => {
        if(result.ok) return json.data;
        throw json.Message;
      }));
    }

    const params = Object.keys(data).map((key) => {
      return `${encodeURIComponent(key) }=${ encodeURIComponent(data[key])}`;
    }).join('&');
    return fetch(url, {
      method: method,
      body: params,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      credentials: 'include'
    }).then(result => {
      if(result.ok) {
        return result.text().then(text => text && JSON.parse(text));
      } else {
        return result.json().then(json => {
          throw json.Message;
        });
      }
    });
  }

  logRequest(method, url, data) {
    const args = Object.keys(data || {}).map(function(key) {
      return `${key }=${ data[key]}`;
    }).join(' ');

    const time = formatDate(new Date(), 'HH:mm:ss');
    const request = [time, method, url.slice(URL.length), args].join(' ');
    this.setState((state) => {
      return { requests: [request].concat(state.requests) };
    });
  }
  clearRequests() {
    this.setState({ requests: [] });
  }
  handleRefreshModeChange(e) {
    this.setState({ refreshMode: e.value });
  }
  render() {
    const { refreshMode, ordersData } = this.state;
    return (
      <React.Fragment>
        <DataGrid
          id="grid"
          showBorders={true}
          dataSource={ordersData}
          repaintChangesOnly={true}
        >
          <Editing
            refreshMode={refreshMode}
            mode="cell"
            allowAdding={true}
            allowDeleting={true}
            allowUpdating={true}
          />

          <Scrolling
            mode="virtual"
          />

          <Lookup dataSource={ordersData} valueExpr="Value" displayExpr="Text" />

            {/* <TotalItem column="CustomerID" summaryType="count" />
            <TotalItem column="Freight" summaryType="sum" valueFormat="#0.00" /> */}

        </DataGrid>

Options

            Refresh Mode:
            <SelectBox
              value={refreshMode}
              items={REFRESH_MODES}
              onValueChanged={this.handleRefreshModeChange}
            />

Network Requests

              <Button id="clear" text="Clear" onClick={this.clearRequests} />

              {this.state.requests.map((request, index) =>
{request}
)}

      </React.Fragment>
    );
  }
}

export default Grid;

This is the link to the docs for the module I'm trying to reference

I'm trying to not bite off more than I can chew and just start with retrieving the data before I even think about manipulating it or sending any in return.  Any insight or guidance you can provide would be greatly appreciated.  Thank you!! :)


问:
Read the value of an attribute of a method
I need to be able to read the value of my attribute from within my Method, how can I do that?</p>

```<code>[MyAttribute("Hello World")]
public void MyMethod()
{
    // Need to read the MyAttribute attribute and get its value
}
</code>```

答:
I used this method :

```<code>public static TAttributeMember? GetMethodAttributeValue<TAttribute, TAttributeMember>(Expression<Func<object>> property, Func<TAttribute, TAttributeMember> valueSelector) where TAttribute : Attribute
{
    var methodInfo = ((MemberExpression)property.Body).Member as PropertyInfo;
    var attr = methodInfo?.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
    return attr != null && valueSelector != null ? valueSelector(attr) : default(TAttributeMember);
}

</code>```

Then can use like this:

```<code>var group = GetMethodAttributeValue<FieldAttribs, FieldGroups>(() => dd.Param2, a => a.Group);
</code>```

Body:
I need to be able to read the value of my attribute from within my Method, how can I do that?

[MyAttribute("Hello World")]
public void MyMethod()
{
    // Need to read the MyAttribute attribute and get its value
}

Body:
I used this method :

public static TAttributeMember? GetMethodAttributeValue<TAttribute, TAttributeMember>(Expression<Func<object>> property, Func<TAttribute, TAttributeMember> valueSelector) where TAttribute : Attribute
{
    var methodInfo = ((MemberExpression)property.Body).Member as PropertyInfo;
    var attr = methodInfo?.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() as TAttribute;
    return attr != null && valueSelector != null ? valueSelector(attr) : default(TAttributeMember);
}

Then can use like this:

var group = GetMethodAttributeValue<FieldAttribs, FieldGroups>(() => dd.Param2, a => a.Group);


问:
Convert Text-Formatted "Day Name, Month Name, Date of Month, Year" to "YYYY-MM-DD" Date Format
I have an Excel sheet with thousands of dates saved in Text format, written the following way:

I want these cells to be converted into "YYYY-MM-DD" format. However, Excel cannot detect these cells as Date Format; hence, when I try to use the "Format Cells" (or Ctrl+1) to change the date format, it does not work and stays the same. I need them to be in "YYYY-MM-DD" because I will be using the date in multiple functions throughout my workbook and the Text formatted Dates do not allow that.

答:
You may try FILTERXML() in this way.

```<code>=FILTERXML("<t><s>"&SUBSTITUTE(A1,", ","</s><s>",1)&"</s></t>","//s[last()]")
</code>```

Then format resulting cells as YYYY-MM-DD. Or you can use TEXT() function to get output directly as date.

```<code>=TEXT(FILTERXML("<t><s>"&SUBSTITUTE(A1,", ","</s><s>",1)&"</s></t>","//s[last()]"),"YYYY-MM-DD")
</code>```

Body:
You may try FILTERXML() in this way.

=FILTERXML("<t><s>"&SUBSTITUTE(A1,", ","</s><s>",1)&"</s></t>","//s[last()]")

Then format resulting cells as YYYY-MM-DD. Or you can use TEXT() function to get output directly as date.

=TEXT(FILTERXML("<t><s>"&SUBSTITUTE(A1,", ","</s><s>",1)&"</s></t>","//s[last()]"),"YYYY-MM-DD")


问:
Copying the data from MS SQL server to MySQL
I need to copy all the data from MS SQL server to MySQL server. I am planning to use the Quartz scheduler to perform this. This scheduler will run every night and move the data from MS-SQL-Server to MySQL server. Can anyone please tell if this is fine or is there any other better way to do this?

Update:

I need to transfer only one table with 40 columns (from MS SQL server to MySQL)

答:
I agree with @bohemian - running a job to transfer a single table every night sounds like a great candidate for a cron job (or "scheduled task" if on Windows). Using a framework like Quartz for this task seems like overkill.

There are many solutions for moving data from SQL Server to MySQL, others have listed great solutions such as Talend. If it would benefit you to only transfer certain columns (for example, to avoid leaking PII), my product SQLpipe might help, as it transfers the result of a query, not an entire table.

Here is a blog post showing how to use the product to transfer data from SQL Server to MySQL.


问:
Data binding check if not null in xml
I am using data binding to trigger onClick with ImageView.

```<code><androidx.appcompat.widget.AppCompatImageView
            android:onClick="@{(view) -> listener.zoomImage(view, connectedItem.largeImage)}"
           />
</code>```

The problem is connectedItem.largeImage can be sometimes null, and I need that the onClick will no trigger if its null.

I tried:

```<code>android:onClick="@{(view) -> connectedItem.largeImage?? listener.zoomImage(view, connectedItem.largeImage)}"
</code>```

But the sitax is wrong.

How can I accomplish that?

答:
you can check it inside the zoomImage function, change type of large image to nullable and check it in the function:

if we consider that your function is :

```<code>fun zoomImage(view:View, largeImage:String){
    //your function logic
}
</code>```

change it to:

```<code>fun zoomImage(view:View, largeImage:String?){
    if(largeImage != null){
        //your function logic
    }
}
</code>```

Title: Data binding check if not null in xml

Body:
I am using data binding to trigger onClick with ImageView.

<androidx.appcompat.widget.AppCompatImageView
            android:onClick="@{(view) -> listener.zoomImage(view, connectedItem.largeImage)}"
           />

The problem is connectedItem.largeImage can be sometimes null, and I need that the onClick will no trigger if its null.

I tried:

android:onClick="@{(view) -> connectedItem.largeImage?? listener.zoomImage(view, connectedItem.largeImage)}"

But the sitax is wrong.

How can I accomplish that?

Body:
you can check it inside the zoomImage function, change type of large image to nullable and check it in the function:

if we consider that your function is :

fun zoomImage(view:View, largeImage:String){
    //your function logic
}

change it to:

fun zoomImage(view:View, largeImage:String?){
    if(largeImage != null){
        //your function logic
    }
}


问:
beautifulsoup get last tag from snippet, if tag exists
Here's html snippet 1:

```<code><td class="firstleft lineupopt-name" style=""><a href="/link/link_url?id=222" title="Donald Trump" target="_blank">Trump, Donald</a> <span style="color:#666;font-size:10px;">B</span>  <span style="color:#cc1100;font-size:10px;font-weight:bold;">TTT</span></td>
</code>```

Here's html snippet 2:

```<code><td class="firstleft lineupopt-name" style=""><a href="/link/link_url2?id=221" title="Hillary Clinton" target="_blank">Clinton, Hillary</a>  <span style="color:#cc1100;font-size:10px;font-weight:bold;">TTT</span></td>
</code>```

Here's my relevant code:

```<code>all = cols[1].find_all('span')
for ele in all:
    if (ele is not None):
        ttt = cols[1].span.text
    else:
        ttt = 'none'
</code>```

Issue: my code works in both instances, but for html snippet 2, it grabs content from the first span tag. In both instances, if the tag exists, I'd like to grab content from only the last span tag. How can this be done?

答:
BS4 now supports last-child so a possible approach could be:

```<code>soup.select('td span:last-child')
</code>```

To get the texts out just iterat the resultset.

Example

```<code>from bs4 import BeautifulSoup

html='''
<td class="firstleft lineupopt-name" style=""><a href="/link/link_url?id=222" title="Donald Trump" target="_blank">Trump, Donald</a> <span style="color:#666;font-size:10px;">B</span>  <span style="color:#cc1100;font-size:10px;font-weight:bold;">TTT</span></td>
<td class="firstleft lineupopt-name" style=""><a href="/link/link_url2?id=221" title="Hillary Clinton" target="_blank">Clinton, Hillary</a>  <span style="color:#cc1100;font-size:10px;font-weight:bold;">TTT</span></td>
'''
soup = BeautifulSoup(html)

[t.text for t in soup.select('td span:last-child')]
</code>```

Output

```<code>['TTT', 'TTT']
</code>```

Body:
Here's html snippet 1:

Trump, Donald B  TTT

Here's html snippet 2:

Clinton, Hillary  TTT

Here's my relevant code:

all = cols[1].find_all('span')
for ele in all:
    if (ele is not None):
        ttt = cols[1].span.text
    else:
        ttt = 'none'

Issue: my code works in both instances, but for html snippet 2, it grabs content from the first span tag. In both instances, if the tag exists, I'd like to grab content from only the last span tag. How can this be done?

Body:
BS4 now supports last-child so a possible approach could be:

soup.select('td span:last-child')

To get the texts out just iterat the resultset.

Example

from bs4 import BeautifulSoup

html='''
<td class="firstleft lineupopt-name" style=""><a href="/link/link_url?id=222" title="Donald Trump" target="_blank">Trump, Donald</a>&nbsp;<span style="color:#666;font-size:10px;">B</span> &nbsp;<span style="color:#cc1100;font-size:10px;font-weight:bold;">TTT</span></td>
<td class="firstleft lineupopt-name" style=""><a href="/link/link_url2?id=221" title="Hillary Clinton" target="_blank">Clinton, Hillary</a> &nbsp;<span style="color:#cc1100;font-size:10px;font-weight:bold;">TTT</span></td>
'''
soup = BeautifulSoup(html)

[t.text for t in soup.select('td span:last-child')]

Output

['TTT', 'TTT']


问:
SQL Server proc running 5x slower than plain query
I have the following query:

```<code>DECLARE @DaysNotUsed int = 14
DECLARE @DaysNotPhoned int = 7

--Total Unique Students
DECLARE @totalStudents TABLE (SchoolID uniqueidentifier, TotalUniqueStudents int)
INSERT INTO @totalStudents
SELECT
        SSGG.School,
        COUNT(DISTINCT S.StudentID)
    FROM Student S
        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
        INNER JOIN SessionHistory SH ON (SH.Student = S.StudentID AND SH.School = S.School AND SH.StartDateTime > GETDATE() - @DaysNotUsed)
    WHERE G.IsBuiltIn = 0
        AND S.HasStartedProduct = 1
    GROUP BY SSGG.School

--Last Used On
DECLARE @lastUsed TABLE (SchoolID uniqueidentifier, LastUsedOn datetime)
INSERT INTO @lastUsed
SELECT
        vi.SchoolID,
        MAX(sh.StartDateTime)
    FROM View_Installation as vi
        INNER JOIN SessionHistory as sh on sh.School = vi.SchoolID
    GROUP BY vi.SchoolID

SELECT
        VI.SchoolID,
        INS.DateAdded,
        INS.Removed,
        INS.DateRemoved,
        INS.DateToInclude,
        VI.SchoolName AS [School Name],
        VI.UsersLicensed AS [Licenses],
        ISNULL(TS.TotalUniqueStudents, 0) as [Total Unique Students],
        ISNULL(TS.TotalUniqueStudents, 0) * 100 / VI.UsersLicensed as [% of Students Using],
        S.State,
        LU.LastUsedOn,
        DATEDIFF(DAY, LU.LastUsedOn, GETDATE()) AS [Days Not Used],
        SI.AreaSalesManager AS [Sales Rep],
        SI.CaseNumber AS [Case #],
        SI.RenewalDate AS [Renewal Date],
        SI.AssignedTo AS [Assigned To],
        SI.Notes AS [Notes]
    FROM View_Installation VI
        INNER JOIN School S ON S.SchoolID = VI.SchoolID
        LEFT OUTER JOIN @totalStudents TS on TS.SchoolID = VI.SchoolID
        INNER JOIN @lastUsed LU on LU.SchoolID = VI.SchoolID
        LEFT OUTER JOIN InactiveReports..SchoolInfo SI ON S.SchoolID = SI.SchoolID
        LEFT OUTER JOIN InactiveReports..InactiveSchools INS ON S.SchoolID = INS.SchoolID
    WHERE VI.UsersLicensed > 0
        AND VI.LastPhoneHome > GETDATE() - @DaysNotPhoned
        AND
        (
            (
                SELECT COUNT(DISTINCT S.StudentID)
                    FROM Student S
                        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
                        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
                    WHERE G.IsBuiltIn = 0
                        AND S.School = VI.SchoolID
            ) * 100 / VI.UsersLicensed < 50
            OR
            VI.SchoolID NOT IN
            (
                SELECT DISTINCT SH1.School
                FROM SessionHistory SH1
                WHERE SH1.StartDateTime > GETDATE() - @DaysNotUsed
            )
        )
    ORDER BY [Days Not Used] DESC
</code>```

Running just plain sql like this in SSMS take about 10 seconds to run.  When I created a stored procedure with exactly the same code, the query takes 50 seconds instead.  The only difference in the actual code of the proc is a SET NOCOUNT ON that the IDE put in by default, but adding that line to the query doesn't have any impact.  Any idea what would cause such a dramatic slow down like this?

EDIT I neglected the declare statements at the beginning.  These are not in the proc, but are parameters to it.  Could this be the difference?

答: OK, thank you all for your help.  Turns out it was a terribly stupid rookie mistake.  The first time I created the proc, it created it under my user's schema instead of the dbo schema.  When I called the proc I was simply doing 'exec proc_name', which I'm realizing now was using the version of the proc under my user's schema.  Running 'exec dbo.proc_name' ran as expected.</p>

Body:
I have the following query:

DECLARE @DaysNotUsed int = 14
DECLARE @DaysNotPhoned int = 7

--Total Unique Students
DECLARE @totalStudents TABLE (SchoolID uniqueidentifier, TotalUniqueStudents int)
INSERT INTO @totalStudents
SELECT
        SSGG.School,
        COUNT(DISTINCT S.StudentID)
    FROM Student S
        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
        INNER JOIN SessionHistory SH ON (SH.Student = S.StudentID AND SH.School = S.School AND SH.StartDateTime > GETDATE() - @DaysNotUsed)
    WHERE G.IsBuiltIn = 0
        AND S.HasStartedProduct = 1
    GROUP BY SSGG.School

--Last Used On
DECLARE @lastUsed TABLE (SchoolID uniqueidentifier, LastUsedOn datetime)
INSERT INTO @lastUsed
SELECT
        vi.SchoolID,
        MAX(sh.StartDateTime)
    FROM View_Installation as vi
        INNER JOIN SessionHistory as sh on sh.School = vi.SchoolID
    GROUP BY vi.SchoolID

SELECT
        VI.SchoolID,
        INS.DateAdded,
        INS.Removed,
        INS.DateRemoved,
        INS.DateToInclude,
        VI.SchoolName AS [School Name],
        VI.UsersLicensed AS [Licenses],
        ISNULL(TS.TotalUniqueStudents, 0) as [Total Unique Students],
        ISNULL(TS.TotalUniqueStudents, 0) * 100 / VI.UsersLicensed as [% of Students Using],
        S.State,
        LU.LastUsedOn,
        DATEDIFF(DAY, LU.LastUsedOn, GETDATE()) AS [Days Not Used],
        SI.AreaSalesManager AS [Sales Rep],
        SI.CaseNumber AS [Case #],
        SI.RenewalDate AS [Renewal Date],
        SI.AssignedTo AS [Assigned To],
        SI.Notes AS [Notes]
    FROM View_Installation VI
        INNER JOIN School S ON S.SchoolID = VI.SchoolID
        LEFT OUTER JOIN @totalStudents TS on TS.SchoolID = VI.SchoolID
        INNER JOIN @lastUsed LU on LU.SchoolID = VI.SchoolID
        LEFT OUTER JOIN InactiveReports..SchoolInfo SI ON S.SchoolID = SI.SchoolID
        LEFT OUTER JOIN InactiveReports..InactiveSchools INS ON S.SchoolID = INS.SchoolID
    WHERE VI.UsersLicensed > 0
        AND VI.LastPhoneHome > GETDATE() - @DaysNotPhoned
        AND
        (
            (
                SELECT COUNT(DISTINCT S.StudentID)
                    FROM Student S
                        INNER JOIN StudentStudents_GroupGroups SSGG ON (SSGG.Students = S.StudentID AND SSGG.School = S.School)
                        INNER JOIN [Group] G ON (G.GroupID = SSGG.Groups AND G.School = SSGG.School)
                    WHERE G.IsBuiltIn = 0
                        AND S.School = VI.SchoolID
            ) * 100 / VI.UsersLicensed < 50
            OR
            VI.SchoolID NOT IN
            (
                SELECT DISTINCT SH1.School
                FROM SessionHistory SH1
                WHERE SH1.StartDateTime > GETDATE() - @DaysNotUsed
            )
        )
    ORDER BY [Days Not Used] DESC

Running just plain sql like this in SSMS take about 10 seconds to run.  When I created a stored procedure with exactly the same code, the query takes 50 seconds instead.  The only difference in the actual code of the proc is a SET NOCOUNT ON that the IDE put in by default, but adding that line to the query doesn't have any impact.  Any idea what would cause such a dramatic slow down like this?

EDIT I neglected the declare statements at the beginning.  These are not in the proc, but are parameters to it.  Could this be the difference?


问:
C# system.FormatException: 'Input string was not in a correct format.'
I am getting the above error for the below block of coding. I have tried several articles in this page for similar error. Still could not find a solution. Please help.</p>
```<code>    private void txtDiscount_TextChanged(object sender, EventArgs e)
    {
        // Calculate Discount and Final Fee
        double FinalFee;
        double CourseFee1;
        double Disc;
        CourseFee1 = Convert.ToDouble(lblCourseFee.Text);
        Disc = Convert.ToDouble(txtDiscount.Text);
        FinalFee = CourseFee1 - (CourseFee1 * (Disc / 100));
        //MessageBox.Show(CourseFee1 + "  " + Disc + "  " + FinalFee.ToString("N2"));

        if (Disc > 40)
        {
            string message = "Maximum Discount is 40% ";
            string title = "Discount Maximum Limit Exceeded";
            MessageBoxButtons buttons = MessageBoxButtons.OK;
            DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Warning);
        }
        else
        {
            lblFinalFee.Text = FinalFee.ToString("N2");
        }
    }
</code>```

答:
The error message is plain english, your debugger will point you to the exact line it occurs. We cannot change what the user types into your text fields. If it is not a double, it cannot be converted.

You can either catch that exception, or use Double.TryParse if you want to handle it with an if instead of an exception block. But you have to handle it.

Body:
I am getting the above error for the below block of coding. I have tried several articles in this page for similar error. Still could not find a solution. Please help.

    private void txtDiscount_TextChanged(object sender, EventArgs e)
    {
        // Calculate Discount and Final Fee
        double FinalFee;
        double CourseFee1;
        double Disc;
        CourseFee1 = Convert.ToDouble(lblCourseFee.Text);
        Disc = Convert.ToDouble(txtDiscount.Text);
        FinalFee = CourseFee1 - (CourseFee1 * (Disc / 100));
        //MessageBox.Show(CourseFee1 + "  " + Disc + "  " + FinalFee.ToString("N2"));

        if (Disc > 40)
        {
            string message = "Maximum Discount is 40% ";
            string title = "Discount Maximum Limit Exceeded";
            MessageBoxButtons buttons = MessageBoxButtons.OK;
            DialogResult result = MessageBox.Show(message, title, buttons, MessageBoxIcon.Warning);
        }
        else
        {
            lblFinalFee.Text = FinalFee.ToString("N2");
        }
    }